chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

@@ -0,0 +1,734 @@
package core
import (
"context"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"academy/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
BlockTypeChatCard = 20
BlockTypeDiagram = 21
BlockTypeDivider = 22
BlockTypeFile = 23
BlockTypeGrid = 24
BlockTypeGridColumn = 25
BlockTypeIframe = 26
BlockTypeImage = 27
BlockTypeISV = 28
BlockTypeMindnote = 29
BlockTypeSheet = 30
BlockTypeTable = 31
BlockTypeTableCell = 32
BlockTypeView = 33
BlockTypeQuoteContainer = 34
BlockTypeTask = 35
BlockTypeOKR = 36
BlockTypeOKRObjective = 37
BlockTypeOKRKeyResult = 38
BlockTypeOKRProgress = 39
BlockTypeAddOns = 40
BlockTypeJiraIssue = 41
BlockTypeWikiCatalog = 42
BlockTypeBoard = 43
BlockTypeAgenda = 44
BlockTypeAgendaItem = 45
BlockTypeAgendaItemTitle = 46
BlockTypeAgendaItemContent = 47
BlockTypeLinkPreview = 48
BlockTypeSourceSynced = 49
BlockTypeReferenceSynced = 50
BlockTypeSubPageList = 51
BlockTypeAITemplate = 52
)
// maxDocumentBlocks caps how many blocks a single document contributes, guarding
// against pathological/adversarial documents. Far above any real Feishu doc.
const maxDocumentBlocks = 50000
// TextElementStyle is the inline style of a text element
// (official docx-v1 TextElementStyle; color enums carry no GFM equivalent and
// are not parsed).
type TextElementStyle struct {
Bold bool `json:"bold"`
Italic bool `json:"italic"`
Strikethrough bool `json:"strikethrough"`
InlineCode bool `json:"inline_code"`
Link *TextElementLink `json:"link"`
}
// TextElementLink is the hyperlink payload of TextElementStyle.
type TextElementLink struct {
URL string `json:"url"`
}
// TextRun is the text_run payload of a TextElement.
type TextRun struct {
Content string `json:"content"`
TextElementStyle *TextElementStyle `json:"text_element_style"`
}
// MentionDoc is the mention_doc payload (@-mention of a cloud document). The
// API carries no document title — only the link.
type MentionDoc struct {
URL string `json:"url"`
TextElementStyle *TextElementStyle `json:"text_element_style"`
}
// MentionUser is the mention_user payload. It carries only the user OpenID —
// never a display name — so the renderer can only Emit a generic @ marker.
type MentionUser struct {
UserID string `json:"user_id"`
TextElementStyle *TextElementStyle `json:"text_element_style"`
}
// Equation is the equation payload; Content is KaTeX syntax.
type Equation struct {
Content string `json:"content"`
TextElementStyle *TextElementStyle `json:"text_element_style"`
}
type TextElement struct {
TextRun *TextRun `json:"text_run"`
MentionUser *MentionUser `json:"mention_user"`
MentionDoc *MentionDoc `json:"mention_doc"`
Equation *Equation `json:"equation"`
// file / reminder / inline_block elements carry no renderable text (file
// is token-only and its token must never leak; reminder has no text body;
// inline_block is an ID reference), so they are not parsed.
}
// BlockTextStyle is the block-level style of text-bearing blocks. Code blocks
// carry Language (CodeLanguage enum 1-75); ordered blocks carry Sequence (the
// real list number: a specific value or "auto"; absent in historical docs and
// docs created via OpenAPI).
type BlockTextStyle struct {
Language int `json:"language"`
Sequence string `json:"sequence"`
Done bool `json:"done"` // todo blocks: item completed
// Align: 1 left / 2 center / 3 right. Absent from the API unless the
// author set an explicit non-default alignment.
Align int `json:"align"`
}
// BlockText is the shared shape of text-bearing blocks (text, headingN, bullet…).
type BlockText struct {
Elements []TextElement `json:"elements"`
Style *BlockTextStyle `json:"style"`
}
// BlockTokenRef is the shared shape of sheet/bitable/image block payloads
// (the JSON tag differs per field; only the token matters).
type BlockTokenRef struct {
Token string `json:"token"`
}
// BlockFileRef is the file block payload: the attachment token plus its name.
type BlockFileRef struct {
Token string `json:"token"`
Name string `json:"name"`
}
// Payload structs for the remaining docx block types (official docx-v1 block
// data structures). Only the fields a renderer needs are parsed; the rest are
// dropped by encoding/json.
// BlockChatCard is block_type 20: a group-chat card embedded in the document.
type BlockChatCard struct {
ChatID string `json:"chat_id"`
Align int `json:"align"`
}
// BlockDiagram is block_type 21: a flowchart / UML diagram reference (no
// public render API — rendered as a placeholder note).
type BlockDiagram struct {
DiagramType int `json:"diagram_type"`
}
// BlockGrid is block_type 24: a multi-column layout container; its children
// are BlockGridColumn (25) wrappers rendered in column order.
type BlockGrid struct {
ColumnSize int `json:"column_size"`
}
// BlockGridColumn is block_type 25: one column inside a BlockGrid.
type BlockGridColumn struct {
WidthRatio int `json:"width_ratio"`
}
// BlockIframeComponent is the embedded-webpage payload of BlockIframe.
type BlockIframeComponent struct {
Type int `json:"type"`
URL string `json:"url"`
}
// BlockIframe is block_type 26: an embedded webpage, rendered as a link.
type BlockIframe struct {
Component *BlockIframeComponent `json:"component"`
}
// BlockView is block_type 33: a view container (e.g. tab views); its children
// render in place, so the wrapper itself is transparent.
type BlockView struct {
ViewType int `json:"view_type"`
}
// BlockAddOns is block_type 40: a document widget (timeline etc.) carrying its
// full data inline in Record; recognized component types render as Markdown.
type BlockAddOns struct {
ComponentID string `json:"component_id"`
ComponentTypeID string `json:"component_type_id"`
Record string `json:"record"`
}
// BlockJiraIssue is block_type 41: a Jira issue card (placeholder only — no
// public content API).
type BlockJiraIssue struct {
ID string `json:"id"`
Key string `json:"key"`
}
// BlockWikiCatalog is block_type 42: a Wiki child-page list (placeholder).
type BlockWikiCatalog struct {
WikiToken string `json:"wiki_token"`
}
// BlockBoard is block_type 43: a whiteboard (mind notes ride the same path);
// Token is exported via download_as_image and inlined as an image.
type BlockBoard struct {
Token string `json:"token"`
Align int `json:"align"`
Width int `json:"width"`
Height int `json:"height"`
}
// BlockLinkPreview is block_type 48: a link preview card (placeholder).
type BlockLinkPreview struct {
URL string `json:"url"`
URLType string `json:"url_type"`
}
// BlockTableMergeInfo is one entry of TableProperty.merge_info, parallel to the
// table's cells array: entry i describes the merge anchored at cell i
// (row = i / column_size, col = i % column_size). GFM has no cell span, so the
// renderer fills covered cells with the anchor value.
type BlockTableMergeInfo struct {
RowSpan int `json:"row_span"`
ColSpan int `json:"col_span"`
}
// BlockTableProperty carries the table grid shape.
type BlockTableProperty struct {
ColumnSize int `json:"column_size"`
MergeInfo []BlockTableMergeInfo `json:"merge_info"`
}
// BlockTable is the table block payload: cell block IDs plus grid property.
type BlockTable struct {
Cells []string `json:"cells"`
Property *BlockTableProperty `json:"property"`
}
// 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"`
ChatCard *BlockChatCard `json:"chat_card"`
Diagram *BlockDiagram `json:"diagram"`
Grid *BlockGrid `json:"grid"`
GridColumn *BlockGridColumn `json:"grid_column"`
Iframe *BlockIframe `json:"iframe"`
Mindnote *BlockTokenRef `json:"mindnote"`
View *BlockView `json:"view"`
AddOns *BlockAddOns `json:"add_ons"`
JiraIssue *BlockJiraIssue `json:"jira_issue"`
WikiCatalog *BlockWikiCatalog `json:"wiki_catalog"`
Board *BlockBoard `json:"board"`
LinkPreview *BlockLinkPreview `json:"link_preview"`
Sheet *BlockTokenRef `json:"sheet"`
Bitable *BlockTokenRef `json:"bitable"`
File *BlockFileRef `json:"file"`
Image *BlockTokenRef `json:"image"`
Table *BlockTable `json:"table"`
}
// DocxBlocksData is the data payload of DocxBlocksResponse.
type DocxBlocksData struct {
Items []DocxBlock `json:"items"`
HasMore bool `json:"has_more"`
PageToken string `json:"page_token"`
}
// DocxBlocksResponse is the response for GET .../documents/:id/blocks.
type DocxBlocksResponse struct {
ApiResponse
Data DocxBlocksData `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
// sheetValueRange is the valueRange payload of sheetValuesData.
type sheetValueRange struct {
Values [][]any `json:"values"`
}
// sheetValuesData is the data payload of sheetValuesResponse.
type sheetValuesData struct {
ValueRange sheetValueRange `json:"valueRange"`
}
// sheetValuesResponse is the response for sheets-v2 values read.
type sheetValuesResponse struct {
ApiResponse
Data sheetValuesData `json:"data"`
}
// flexInt decodes a JSON value that may be a number or a numeric string —
// Feishu sheet APIs mix both spellings for row/column indices.
type flexInt int
func (f *flexInt) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), `"`)
v, err := strconv.Atoi(s)
if err != nil {
return fmt.Errorf("invalid integer value %s", s)
}
*f = flexInt(v)
return nil
}
// sheetMergeRange is one merged-cell region of a sheet: 0-based CLOSED
// row/column indices [start..end] as reported by the sheets-v3 metadata API.
type sheetMergeRange struct {
StartRow flexInt `json:"start_row_index"`
EndRow flexInt `json:"end_row_index"`
StartCol flexInt `json:"start_column_index"`
EndCol flexInt `json:"end_column_index"`
}
// sheetQueryResponse is the response for the sheets-v3
// spreadsheets/:spreadsheet_token/sheets/query metadata read.
type sheetQueryResponse struct {
ApiResponse
Data struct {
Sheets []struct {
SheetID string `json:"sheet_id"`
Merges []sheetMergeRange `json:"merges"`
} `json:"sheets"`
} `json:"data"`
}
// sheetMerges returns the merged-cell regions of one sheet of a spreadsheet,
// addressed by the sheet embed token ("spreadsheetToken_sheetId"). The sheet
// entry is looked up by its sheet_id; a spreadsheet without merges carries no
// merges field, which degrades to nil. Errors surface to the caller, which
// silently skips merge filling — the information is cosmetic, never fatal.
// Permission scope: sheets:spreadsheet:readonly (same token as the values read).
func (c *Client) sheetMerges(ctx context.Context, embedToken string) ([]sheetMergeRange, error) {
idx := strings.LastIndex(embedToken, "_")
if idx < 0 {
return nil, fmt.Errorf("invalid sheet embed token: %q", embedToken)
}
spreadsheetToken, sheetID := embedToken[:idx], embedToken[idx+1:]
path := "/open-apis/sheets/v3/spreadsheets/" + url.PathEscape(spreadsheetToken) + "/sheets/query"
var resp sheetQueryResponse
if err := c.DoRequest(ctx, http.MethodGet, path, nil, &resp); err != nil {
return nil, fmt.Errorf("query sheet metadata: %w", err)
}
if resp.Code != 0 {
return nil, fmt.Errorf("query sheet metadata error: code=%d msg=%s", resp.Code, resp.Msg)
}
for _, s := range resp.Data.Sheets {
if s.SheetID == sheetID {
return s.Merges, nil
}
}
return nil, nil
}
// 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)
}
}
// bitableFieldProperty carries a field's type-specific settings.
type bitableFieldProperty struct {
// DateFormatter distinguishes a date-only column from a datetime one.
DateFormatter string `json:"date_formatter"`
}
// bitableField is one entry of bitableFieldsData.Items.
type bitableField struct {
FieldName string `json:"field_name"`
Type int `json:"type"`
Property *bitableFieldProperty `json:"property"`
}
// bitableFieldsData is the data payload of bitableFieldsResponse.
type bitableFieldsData struct {
HasMore bool `json:"has_more"`
PageToken string `json:"page_token"`
Items []bitableField `json:"items"`
}
type bitableFieldsResponse struct {
ApiResponse
Data bitableFieldsData `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
// maxBitableFields caps how many fields one embedded table contributes. The
// list-fields endpoint pages at 100, so this allows 50 pages; a table that keeps
// handing out fresh page tokens stops here instead of growing the header without
// bound.
const maxBitableFields = 5000
// bitableRecord is one entry of bitableRecordsData.Items.
type bitableRecord struct {
Fields map[string]any `json:"fields"`
}
// bitableRecordsData is the data payload of bitableRecordsResponse.
type bitableRecordsData struct {
HasMore bool `json:"has_more"`
PageToken string `json:"page_token"`
Items []bitableRecord `json:"items"`
}
type bitableRecordsResponse struct {
ApiResponse
Data bitableRecordsData `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 := ""
seenFieldPageTokens := make(map[string]struct{})
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 never advances, so the
// size cap below would never trip — stop instead of looping until the
// task deadline. Nothing more to read.
break
}
if !fieldsResp.Data.HasMore || fieldsResp.Data.PageToken == "" {
break
}
if len(cols) >= maxBitableFields {
logger.Warnf(ctx, "[Feishu] bitable %s exceeded %d fields; truncating", embedToken, maxBitableFields)
break
}
// A repeated non-empty token means the vendor is re-serving a page we
// already read; without this the loop would re-append the same fields
// until the task deadline (same guard as the wiki/drive pagination).
if _, exists := seenFieldPageTokens[fieldsResp.Data.PageToken]; exists {
return nil, false, fmt.Errorf("feishu bitable field pagination repeated page token %q",
fieldsResp.Data.PageToken)
}
seenFieldPageTokens[fieldsResp.Data.PageToken] = struct{}{}
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
}
@@ -0,0 +1,696 @@
package core
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strconv"
"strings"
"testing"
"time"
"academy/internal/logger"
)
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)
}
}
// TestSheetMerges_SplitsTokenAndReturnsRegions anchors the v3 metadata read:
// the embed token splits on the last "_", the sheet entry is matched by
// sheet_id, and merge indices decode from both JSON numbers and strings.
func TestSheetMerges_SplitsTokenAndReturnsRegions(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
// One sheet with numeric merge indices, one with string form, and one
// with no merges field at all (a spreadsheet without merged cells).
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"sheets": []any{
map[string]any{"sheet_id": "0", "merges": []any{
map[string]any{
"start_row_index": 0, "end_row_index": 1,
"start_column_index": 1, "end_column_index": 2,
},
}},
map[string]any{"sheet_id": "9", "merges": []any{
map[string]any{
"start_row_index": "2", "end_row_index": "3",
"start_column_index": "0", "end_column_index": "0",
},
}},
map[string]any{"sheet_id": "7"},
},
}})
}))
defer srv.Close()
c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
merges, err := c.sheetMerges(context.Background(), "sht_abc_0")
if err != nil {
t.Fatalf("sheetMerges: %v", err)
}
if gotPath != "/open-apis/sheets/v3/spreadsheets/sht_abc/sheets/query" {
t.Errorf("path = %q", gotPath)
}
if len(merges) != 1 ||
merges[0].StartRow != 0 || merges[0].EndRow != 1 ||
merges[0].StartCol != 1 || merges[0].EndCol != 2 {
t.Errorf("numeric merges = %+v", merges)
}
mergesStr, err := c.sheetMerges(context.Background(), "sht_abc_9")
if err != nil {
t.Fatalf("sheetMerges (string form): %v", err)
}
if len(mergesStr) != 1 || mergesStr[0].StartRow != 2 || mergesStr[0].EndCol != 0 {
t.Errorf("string merges = %+v", mergesStr)
}
mergesNone, err := c.sheetMerges(context.Background(), "sht_abc_7")
if err != nil {
t.Fatalf("sheetMerges (no merges field): %v", err)
}
if len(mergesNone) != 0 {
t.Errorf("expected no merges, got %+v", mergesNone)
}
}
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: 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))
}
}
// TestReadBitableRecords_RejectsRepeatedFieldPageToken guards the list-fields
// pagination against a vendor that answers every page with has_more=true and
// the same non-empty page_token: the second occurrence must fail loudly instead
// of re-reading (and re-appending) the same page until the task deadline.
// Same guard shape as the wiki space/node and drive file pagination.
func TestReadBitableRecords_RejectsRepeatedFieldPageToken(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++
if fieldCalls > 2 {
http.Error(w, "pagination should have stopped", http.StatusBadGateway)
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": true,
"page_token": "constant-token",
"items": []map[string]any{{"field_name": "col-a"}},
}})
}
}))
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()}
_, _, err := c.readBitableRecords(ctx, "bascabc_tblxyz")
if err == nil || !strings.Contains(err.Error(), "repeated page token") {
t.Fatalf("expected repeated-page-token error, got %v", err)
}
if fieldCalls != 2 {
t.Errorf("fields endpoint called %d times, want 2 (the repeated token must fail fast)", fieldCalls)
}
}
// TestReadBitableRecords_CapsFieldPages guards the size cap on the fields loop:
// a vendor handing out a fresh page_token on every page must stop at
// maxBitableFields with a warning, not grow the header without bound.
func TestReadBitableRecords_CapsFieldPages(t *testing.T) {
const fieldsPerPage = 2
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++
page := r.URL.Query().Get("page_token")
if page == "" {
page = "page-0"
}
n, err := strconv.Atoi(strings.TrimPrefix(page, "page-"))
if err != nil {
t.Errorf("unexpected page_token %q", page)
}
items := make([]map[string]any, 0, fieldsPerPage)
for i := 0; i < fieldsPerPage; i++ {
items = append(items, map[string]any{"field_name": fieldName(n*fieldsPerPage + i)})
}
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
"has_more": true,
"page_token": "page-" + strconv.Itoa(n+1),
"items": items,
}})
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()
var buf bytes.Buffer
logger.SetOutput(&buf)
defer logger.SetOutput(os.Stdout)
ctx, cancel := context.WithTimeout(context.Background(), 30*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("capped pagination must stop cleanly, got err: %v", err)
}
if len(rows) == 0 {
t.Fatal("expected a header row")
}
if got := len(rows[0]); got != maxBitableFields {
t.Errorf("header has %d fields, want the %d-field cap", got, maxBitableFields)
}
if want := maxBitableFields / fieldsPerPage; fieldCalls != want {
t.Errorf("fields endpoint called %d times, want %d (the cap must stop the loop)", fieldCalls, want)
}
if log := buf.String(); !strings.Contains(log, "exceeded") || !strings.Contains(log, "truncating") {
t.Errorf("hitting the cap must log a warning, log tail: %s", log)
}
}
@@ -0,0 +1,172 @@
package core
import (
"bytes"
"context"
"fmt"
"image"
"image/draw"
"image/jpeg"
"image/png"
"net/url"
)
// board.go covers the docx board block (block_type 43): whiteboards embedded in
// documents are exported to an image via the official download_as_image API and
// ride the parent document's embedded-image pipeline.
//
// API: GET /open-apis/board/v1/whiteboards/:whiteboard_id/download_as_image —
// responds with the raw image bytes (Content-Type image/png|jpeg|gif|svg+xml).
// The render covers the WHOLE board canvas, not the content bounding box, and
// editors routinely leave the canvas far larger than the drawing, so exports
// surface with large blank areas (mostly below the content). trimBoardImage
// crops those blank borders after download.
//
// Scope: board:whiteboard:node:read. 403 (code 2890005) means the app lacks
// read permission on the board; the caller degrades to a Markdown note rather
// than failing the document.
// blankTolerance is the per-channel delta under which a pixel counts as the
// background color — generous enough to absorb JPEG edge artifacts.
const blankTolerance = 14
// trimMargin keeps a visible white frame around the content bounding box —
// the border reads as the content's edge rather than a tight crop.
const trimMargin = 32
// maxTrimPixels bounds the decode/scan cost; larger images pass through
// untrimmed rather than risking a huge RGBA allocation.
const maxTrimPixels = 64 << 20
type boardPixel struct{ r, g, b, a uint8 }
// downloadBoardAsImage fetches a whiteboard's thumbnail image bytes and crops
// blank canvas borders. Transient failures (429/5xx/transport) retry via the
// shared downloadRawBytes policy; the 512 MB maxFeishuDownloadBytes cap
// applies too (a real whiteboard PNG is orders of magnitude smaller).
func (c *Client) downloadBoardAsImage(ctx context.Context, boardToken string) ([]byte, error) {
path := fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/download_as_image", url.PathEscape(boardToken))
data, err := c.downloadRawBytes(ctx, path)
if err != nil {
return nil, err
}
return trimBoardImage(data), nil
}
// trimBoardImage crops near-uniform blank borders from a board export (PNG or
// JPEG; anything undecodable or in another format returns unchanged). The
// background color is the majority of the four corner pixels (>=3 must
// agree); on a split vote content reaches the corners and the image passes
// through untrimmed. Border rows/columns entirely within blankTolerance of
// the background are trimmed, keeping trimMargin pixels around the content.
func trimBoardImage(data []byte) []byte {
// Read dimensions before decoding: compressed exports can describe a huge
// canvas even when their download fits within the byte limit.
cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil || (format != "png" && format != "jpeg") ||
cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > maxTrimPixels/cfg.Height {
return data
}
img, format, err := image.Decode(bytes.NewReader(data))
if err != nil || (format != "png" && format != "jpeg") {
return data
}
b := img.Bounds()
w, h := b.Dx(), b.Dy()
if w <= 0 || h <= 0 || w > maxTrimPixels/h {
return data
}
at := func(x, y int) boardPixel {
r, g, bl, a := img.At(x, y).RGBA()
return boardPixel{uint8(r >> 8), uint8(g >> 8), uint8(bl >> 8), uint8(a >> 8)}
}
withinTolerance := func(p, q boardPixel) bool {
d := func(a, c uint8) int {
diff := int(a) - int(c)
if diff < 0 {
return -diff
}
return diff
}
return d(p.r, q.r) <= blankTolerance && d(p.g, q.g) <= blankTolerance &&
d(p.b, q.b) <= blankTolerance && d(p.a, q.a) <= blankTolerance
}
// The background color must be unambiguous: require at least three of the
// four corners to agree on one color, else content reaches the corners and
// trimming could eat it (rows fully matching the seed would read as blank).
corners := [4]boardPixel{
at(b.Min.X, b.Min.Y), at(b.Max.X-1, b.Min.Y),
at(b.Min.X, b.Max.Y-1), at(b.Max.X-1, b.Max.Y-1),
}
bg, ok := boardPixel{}, false
for _, c := range corners {
n := 0
for _, d := range corners {
if withinTolerance(c, d) {
n++
}
}
if n >= 3 {
bg, ok = c, true
break
}
}
if !ok {
return data
}
rowBlank := func(y int) bool {
for x := b.Min.X; x < b.Max.X; x++ {
if !withinTolerance(at(x, y), bg) {
return false
}
}
return true
}
colBlank := func(x int) bool {
for y := b.Min.Y; y < b.Max.Y; y++ {
if !withinTolerance(at(x, y), bg) {
return false
}
}
return true
}
top, bottom := b.Min.Y, b.Max.Y-1
for top < bottom && rowBlank(top) {
top++
}
for bottom > top && rowBlank(bottom) {
bottom--
}
left, right := b.Min.X, b.Max.X-1
for left < right && colBlank(left) {
left++
}
for right > left && colBlank(right) {
right--
}
cw, ch := right-left+1, bottom-top+1
if cw <= 2 || ch <= 2 {
// Nothing but background (degenerate content box) — keep the original.
return data
}
if cw == w && ch == h {
return data
}
x0 := max(b.Min.X, left-trimMargin)
y0 := max(b.Min.Y, top-trimMargin)
x1 := min(b.Max.X, right+1+trimMargin)
y1 := min(b.Max.Y, bottom+1+trimMargin)
out := image.NewRGBA(image.Rect(0, 0, x1-x0, y1-y0))
draw.Draw(out, out.Bounds(), img, image.Point{X: x0, Y: y0}, draw.Src)
var buf bytes.Buffer
switch format {
case "jpeg":
err = jpeg.Encode(&buf, out, &jpeg.Options{Quality: 80})
case "png":
err = png.Encode(&buf, out)
}
if err != nil {
return data
}
return buf.Bytes()
}
@@ -0,0 +1,453 @@
package core
import (
"bytes"
"context"
"image"
"image/color"
"image/jpeg"
"image/png"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"academy/internal/types"
)
// P3 embedded-object pipeline tests: board blocks (block_type 43) exported via
// download_as_image, oversize attachments degraded inline, and the marker →
// image_map contract. These run against the real Client + Feishu-shaped fake
// endpoints, exercising FetchDocxWithBlocks end to end.
func fakeFeishuForBoard(t *testing.T, blocks []DocxBlock, boardStatus int, boardBody []byte) *httptest.Server {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, TokenResponse{
ApiResponse: ApiResponse{Code: 0},
TenantAccessToken: "fake-token", Expire: 7200,
})
})
mux.HandleFunc("/open-apis/docx/v1/documents/obj-board/blocks", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, DocxBlocksResponse{
ApiResponse: ApiResponse{Code: 0},
Data: DocxBlocksData{Items: blocks},
})
})
mux.HandleFunc("/open-apis/board/v1/whiteboards/brd-1/download_as_image",
func(w http.ResponseWriter, _ *http.Request) {
if boardStatus != http.StatusOK {
http.Error(w, string(boardBody), boardStatus)
return
}
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(boardBody)
})
ts := httptest.NewServer(mux)
t.Cleanup(ts.Close)
return ts
}
func boardBlocks() []DocxBlock {
return []DocxBlock{
{BlockID: "b1", BlockType: BlockTypePage},
{
BlockID: "b2", BlockType: BlockTypeText, Text: &BlockText{
Elements: []TextElement{{TextRun: &TextRun{Content: "见画板"}}},
},
},
{BlockID: "b3", BlockType: BlockTypeBoard, Board: &BlockBoard{Token: "brd-1"}},
}
}
func boardFetchInput() DocxFetchInput {
return DocxFetchInput{
DocToken: "nt-board",
ObjToken: "obj-board",
Title: "Board Doc",
URL: "https://example.feishu.cn/wiki/nt-board",
ResourceID: "space1:nt-board",
BaseMeta: map[string]string{"channel": types.ChannelFeishu},
}
}
func TestFetchDocxWithBlocks_BoardExportSuccess(t *testing.T) {
png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), MinAttachmentBytes)...)
ts := fakeFeishuForBoard(t, boardBlocks(), http.StatusOK, png)
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL, ParseMode: ParseModeBlocks})
items, err := FetchDocxWithBlocks(context.Background(), client, boardFetchInput())
if err != nil {
t.Fatalf("FetchDocxWithBlocks: %v", err)
}
// Orthodox flow: the board rides inline in the parent markdown as a
// base64 data URI — no image sub-item, no image_map.
if len(items) != 1 {
t.Fatalf("want 1 item (main only), got %d: %+v", len(items), items)
}
main := items[0]
if !strings.Contains(string(main.Content), "![图片](data:image/png;base64,") {
t.Errorf("board not inlined as base64 data URI:\n%s", main.Content)
}
if strings.Contains(string(main.Content), "academy-img://") {
t.Errorf("internal marker leaked into stored markdown:\n%s", main.Content)
}
if main.Metadata["image_map"] != "" {
t.Errorf("image_map must be gone, got %q", main.Metadata["image_map"])
}
if !strings.Contains(string(main.Content), "见画板") {
t.Errorf("main markdown lost body text:\n%s", main.Content)
}
}
func TestFetchDocxWithBlocks_BoardExportForbiddenDegrades(t *testing.T) {
// 403 = app lacks board:whiteboard:node:read. No board item, no failure:
// the marker degrades to an inline note and the document still syncs.
ts := fakeFeishuForBoard(t, boardBlocks(), http.StatusForbidden, []byte(`{"code":2890005,"msg":"forbidden"}`))
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL, ParseMode: ParseModeBlocks})
items, err := FetchDocxWithBlocks(context.Background(), client, boardFetchInput())
if err != nil {
t.Fatalf("board export failure must not fail the document: %v", err)
}
if len(items) != 1 {
t.Fatalf("want 1 item (main only), got %d: %+v", len(items), items)
}
main := items[0]
if !strings.Contains(string(main.Content), "![图片]()") {
t.Errorf("markdown missing board degrade note:\n%s", main.Content)
}
if strings.Contains(string(main.Content), "academy-img") {
t.Errorf("unresolved board marker left in markdown:\n%s", main.Content)
}
if main.Metadata["image_map"] != "" {
t.Errorf("failed board must not appear in image_map, got %q", main.Metadata["image_map"])
}
if !strings.Contains(string(main.Content), "见画板") {
t.Errorf("main markdown lost body text:\n%s", main.Content)
}
}
func TestFetchDocxWithBlocks_AttachmentOverCapDegrades(t *testing.T) {
// The fake declares a Content-Length above maxFeishuDownloadBytes with a
// tiny body: downloadRawBytes must reject early on the header, without
// needing to serve half a gigabyte.
bigPDF := bytes.Repeat([]byte("A"), 1024)
blocks := []DocxBlock{
{BlockID: "b1", BlockType: BlockTypePage},
{BlockID: "b2", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "ft-huge", Name: "report.pdf"}},
}
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, TokenResponse{
ApiResponse: ApiResponse{Code: 0},
TenantAccessToken: "fake-token", Expire: 7200,
})
})
mux.HandleFunc("/open-apis/docx/v1/documents/obj-board/blocks", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, DocxBlocksResponse{
ApiResponse: ApiResponse{Code: 0},
Data: DocxBlocksData{Items: blocks},
})
})
mux.HandleFunc("/open-apis/drive/v1/medias/ft-huge/download", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Length", strconv.FormatInt(maxFeishuDownloadBytes+1, 10))
_, _ = w.Write(bigPDF)
})
ts := httptest.NewServer(mux)
t.Cleanup(ts.Close)
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL, ParseMode: ParseModeBlocks})
in := boardFetchInput()
in.ObjToken = "obj-board"
items, err := FetchDocxWithBlocks(context.Background(), client, in)
if err != nil {
t.Fatalf("over-cap attachment must not fail the document: %v", err)
}
if len(items) != 1 {
t.Fatalf("want 1 item (main only), got %d: %+v", len(items), items)
}
main := items[0]
// The over-cap file degrades to an inline reference carrying the source link.
if !strings.Contains(string(main.Content), "> [附件: report.pdf](") {
t.Errorf("markdown missing over-cap attachment placeholder:\n%s", main.Content)
}
if strings.Contains(string(main.Content), "- report.pdf") {
t.Errorf("over-cap attachment must not stay in the file-name list:\n%s", main.Content)
}
if main.Metadata["attachment_ids"] != "" {
t.Errorf("over-cap attachment must not appear in attachment_ids, got %q", main.Metadata["attachment_ids"])
}
}
// Regression for the line-text patch bug: an earlier bullet that happens to
// carry the attachment's display name must survive the over-cap degrade, and
// the attachment's own marker line is the one replaced.
func TestFetchDocxWithBlocks_OverCapPatchHitsMarkerNotEarlierBullet(t *testing.T) {
bigPDF := bytes.Repeat([]byte("A"), 1024)
blocks := []DocxBlock{
{BlockID: "b1", BlockType: BlockTypePage},
{BlockID: "b3", BlockType: BlockTypeBullet, Bullet: &BlockText{Elements: []TextElement{
{TextRun: &TextRun{Content: "report.pdf"}},
}}},
{BlockID: "b4", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "ft-huge", Name: "report.pdf"}},
}
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, TokenResponse{
ApiResponse: ApiResponse{Code: 0},
TenantAccessToken: "fake-token", Expire: 7200,
})
})
mux.HandleFunc("/open-apis/docx/v1/documents/obj-board/blocks", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, DocxBlocksResponse{
ApiResponse: ApiResponse{Code: 0},
Data: DocxBlocksData{Items: blocks},
})
})
mux.HandleFunc("/open-apis/drive/v1/medias/ft-huge/download", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Length", strconv.FormatInt(maxFeishuDownloadBytes+1, 10))
_, _ = w.Write(bigPDF)
})
ts := httptest.NewServer(mux)
t.Cleanup(ts.Close)
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL, ParseMode: ParseModeBlocks})
in := boardFetchInput()
in.ObjToken = "obj-board"
items, err := FetchDocxWithBlocks(context.Background(), client, in)
if err != nil {
t.Fatalf("over-cap attachment must not fail the document: %v", err)
}
main := items[len(items)-1]
if n := strings.Count(string(main.Content), "- report.pdf"); n != 1 {
t.Errorf("earlier bullet must survive exactly once, got %d:\n%s", n, main.Content)
}
if !strings.Contains(string(main.Content), "> [附件: report.pdf]") {
t.Errorf("over-cap degrade note missing:\n%s", main.Content)
}
}
// TestSupportedImageExtSVG pins the svg recovery: Go's sniffer reports SVG
// markup as text/xml, but a board export carrying an <svg> document must be
// treated as an inlinable image, not degraded to a placeholder.
func TestSupportedImageExtSVG(t *testing.T) {
svg := []byte(`<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>`)
ext, ct, ok := SupportedImageExt(svg)
if !ok || ext != ".svg" || ct != "image/svg+xml" {
t.Fatalf("SupportedImageExt(svg) = %q %q %v, want .svg image/svg+xml true", ext, ct, ok)
}
if _, _, ok := SupportedImageExt([]byte("<?xml version=\"1.0\"?><not-svg/>")); ok {
t.Fatal("non-svg xml must not be treated as an image")
}
}
// trimBoardImage tests: the board API renders the whole canvas, so exports
// carry large blank borders (mostly below the content) — they must be cropped.
func encodeTestImage(t *testing.T, img image.Image, format string) []byte {
t.Helper()
var buf bytes.Buffer
var err error
if format == "jpeg" {
err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: 80})
} else {
err = png.Encode(&buf, img)
}
if err != nil {
t.Fatalf("encode %s: %v", format, err)
}
return buf.Bytes()
}
func TestTrimBoardImage_CropsBlankBottomAndRight(t *testing.T) {
for _, format := range []string{"png", "jpeg"} {
src := image.NewRGBA(image.Rect(0, 0, 120, 200))
content := color.RGBA{R: 30, G: 60, B: 200, A: 255}
for y := 0; y < 40; y++ {
for x := 0; x < 80; x++ {
src.Set(x, y, content)
}
}
trimmed := trimBoardImage(encodeTestImage(t, src, format))
out, gotFormat, err := image.Decode(bytes.NewReader(trimmed))
if err != nil {
t.Fatalf("%s: decode trimmed: %v", format, err)
}
if gotFormat != format {
t.Fatalf("%s: format changed to %s", format, gotFormat)
}
b := out.Bounds()
if b.Dx() > 80+2*trimMargin || b.Dy() > 40+2*trimMargin {
t.Fatalf("%s: blank canvas not trimmed, got %dx%d", format, b.Dx(), b.Dy())
}
if b.Dx() < 40 || b.Dy() < 20 {
t.Fatalf("%s: content lost, got %dx%d", format, b.Dx(), b.Dy())
}
if r, _, _, _ := out.At(b.Min.X+4, b.Min.Y+4).RGBA(); uint8(r>>8) != 30 {
t.Fatalf("%s: content pixel lost at margin", format)
}
}
}
func TestTrimBoardImage_NoBlankBorderReturnsOriginal(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 50, 50))
for y := 0; y < 50; y++ {
for x := 0; x < 50; x++ {
src.Set(x, y, color.RGBA{R: uint8(x * 5), G: uint8(y * 5), B: 90, A: 255})
}
}
data := encodeTestImage(t, src, "png")
if got := trimBoardImage(data); !bytes.Equal(got, data) {
t.Fatal("fully painted image must pass through byte-identical")
}
}
func TestTrimBoardImage_FullyBlankAndGarbagePassThrough(t *testing.T) {
blank := image.NewRGBA(image.Rect(0, 0, 60, 60))
data := encodeTestImage(t, blank, "png")
if got := trimBoardImage(data); !bytes.Equal(got, data) {
t.Fatal("fully blank export must pass through unchanged")
}
if got := trimBoardImage([]byte("not an image")); !bytes.Equal(got, []byte("not an image")) {
t.Fatal("undecodable bytes must pass through unchanged")
}
}
// Content spanning two opposite corners makes the corner vote 2:2 — trimming
// must bail entirely rather than trust either color as the background.
func TestTrimBoardImage_SplitCornerVoteSkipsTrimming(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 120, 200))
white := color.RGBA{R: 255, G: 255, B: 255, A: 255}
red := color.RGBA{R: 200, G: 30, B: 30, A: 255}
for y := 0; y < 200; y++ {
for x := 0; x < 120; x++ {
src.Set(x, y, white)
}
}
// Red band down the full left side: touches top-left and bottom-left.
for y := 0; y < 200; y++ {
for x := 0; x < 50; x++ {
src.Set(x, y, red)
}
}
data := encodeTestImage(t, src, "png")
if got := trimBoardImage(data); !bytes.Equal(got, data) {
t.Fatal("split corner vote (2:2) must pass through untrimmed")
}
}
// Content touching exactly one corner keeps the majority vote at 3 — the
// blank borders away from that corner are still trimmed.
func TestTrimBoardImage_ContentAtOneCornerStillTrims(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 120, 200))
white := color.RGBA{R: 255, G: 255, B: 255, A: 255}
red := color.RGBA{R: 200, G: 30, B: 30, A: 255}
for y := 0; y < 200; y++ {
for x := 0; x < 120; x++ {
src.Set(x, y, white)
}
}
// Content only in the top-left corner region.
for y := 0; y < 40; y++ {
for x := 0; x < 40; x++ {
src.Set(x, y, red)
}
}
trimmed := trimBoardImage(encodeTestImage(t, src, "png"))
out, _, err := image.Decode(bytes.NewReader(trimmed))
if err != nil {
t.Fatalf("decode trimmed: %v", err)
}
b := out.Bounds()
if b.Dy() > 40+2*trimMargin || b.Dx() > 40+2*trimMargin {
t.Fatalf("blank canvas not trimmed, got %dx%d", b.Dx(), b.Dy())
}
if r, _, _, _ := out.At(2, 2).RGBA(); uint8(r>>8) != 200 {
t.Fatal("corner-touching content must survive at its position")
}
}
// 云文档 mention links: FetchDocxWithBlocks backfills link text with the
// referenced document's title via the drive metadata batch API; unresolved
// refs (no permission, 403) degrade to the URL-as-text form.
func TestFetchDocxWithBlocks_MentionDocTitleBackfill(t *testing.T) {
blocks := []DocxBlock{
{BlockID: "r", BlockType: BlockTypePage},
{BlockID: "p", BlockType: BlockTypeText, Text: &BlockText{
Elements: []TextElement{{MentionDoc: &MentionDoc{
URL: "https://my.feishu.cn/docx/RefDoc001",
}}},
}},
}
run := func(metasStatus int, metasBody string, _ string) *types.FetchedItem {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, TokenResponse{
ApiResponse: ApiResponse{Code: 0},
TenantAccessToken: "fake-token", Expire: 7200,
})
})
mux.HandleFunc("/open-apis/docx/v1/documents/obj-doc/blocks", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, DocxBlocksResponse{
ApiResponse: ApiResponse{Code: 0},
Data: DocxBlocksData{Items: blocks},
})
})
mux.HandleFunc("/open-apis/drive/v1/metas/batch_query", func(w http.ResponseWriter, _ *http.Request) {
if metasStatus != http.StatusOK {
http.Error(w, metasBody, metasStatus)
return
}
_, _ = w.Write([]byte(metasBody))
})
ts := httptest.NewServer(mux)
t.Cleanup(ts.Close)
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL})
items, err := FetchDocxWithBlocks(context.Background(), client, DocxFetchInput{
DocToken: "nt-doc", ObjToken: "obj-doc", Title: "父文档",
URL: "https://my.feishu.cn/docx/obj-doc",
})
if err != nil {
t.Fatalf("fetch: %v", err)
}
return items[len(items)-1]
}
main := run(http.StatusOK,
`{"code":0,"data":{"metas":[{"doc_token":"RefDoc001","doc_type":"docx","title":"引用的文档"}]}}`,
"引用的文档")
if !strings.Contains(string(main.Content), "[引用的文档](https://my.feishu.cn/docx/RefDoc001)") {
t.Errorf("title not backfilled, got:\n%s", main.Content)
}
// Permission denied on the metadata API → falls back to URL-as-text.
main = run(http.StatusForbidden, `forbidden`, "")
if !strings.Contains(string(main.Content),
"[https://my.feishu.cn/docx/RefDoc001](https://my.feishu.cn/docx/RefDoc001)") {
t.Errorf("fallback form missing, got:\n%s", main.Content)
}
}
// A header can advertise dimensions far beyond the compressed download size.
// The sentinel codec proves that the full pixel decoder is never invoked.
func TestTrimBoardImageRejectsOversizeBeforeDecode(t *testing.T) {
const magic = "academy-oversized-board-test"
image.RegisterFormat("png", magic,
func(io.Reader) (image.Image, error) {
panic("oversized board reached pixel decoder")
},
func(io.Reader) (image.Config, error) {
return image.Config{Width: maxTrimPixels + 1, Height: 1}, nil
})
data := []byte(magic)
if got := trimBoardImage(data); !bytes.Equal(got, data) {
t.Fatal("oversized image must pass through unchanged")
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,303 @@
package core
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
// retryTestServer builds a server that always answers the auth-token call and
// routes the given target path to h, so tests can drive DoRequest's retry loop.
func retryTestServer(t *testing.T, target string, h http.HandlerFunc) (*httptest.Server, *Config) {
t.Helper()
resetFeishuRequestGates(t)
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, TokenResponse{
ApiResponse: ApiResponse{Code: 0},
TenantAccessToken: "fake-token",
Expire: 7200,
})
})
mux.HandleFunc(target, h)
ts := httptest.NewServer(mux)
return ts, &Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL}
}
func TestDoRequest_RetriesOn429ThenSucceeds(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
if attempts.Load() == 1 {
// "0" is coerced to a short delay inside the client so the test stays fast.
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = io.WriteString(w, `{"code":99991400,"msg":"rate limited"}`)
return
}
writeJSON(w, ApiResponse{Code: 0})
})
defer ts.Close()
c := NewClient(cfg)
var resp ApiResponse
if err := c.DoRequest(context.Background(), http.MethodGet, "/target", nil, &resp); err != nil {
t.Fatalf("expected success after retry, got %v", err)
}
if attempts.Load() < 2 {
t.Errorf("attempts = %d, want >= 2 (should retry after 429)", attempts.Load())
}
}
func TestDoRequest_429ExhaustsRetries(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = io.WriteString(w, `{"code":99991400,"msg":"rate limited"}`)
})
defer ts.Close()
c := NewClient(cfg)
err := c.DoRequest(context.Background(), http.MethodGet, "/target", nil, nil)
if err == nil {
t.Fatal("expected error when 429s exceed the retry budget")
}
if attempts.Load() != 4 { // initial + 3 retries
t.Errorf("attempts = %d, want 4 (1 + 3 retries)", attempts.Load())
}
}
func TestDoRequest_5xxRetriesOnce(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
w.WriteHeader(http.StatusInternalServerError)
_, _ = io.WriteString(w, `{"code":1,"msg":"internal error"}`)
})
defer ts.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c := NewClient(cfg)
if err := c.DoRequest(ctx, http.MethodGet, "/target", nil, nil); err == nil {
t.Fatal("expected error after 5xx exhaustion")
}
if attempts.Load() != 2 { // initial + 1 retry
t.Errorf("attempts = %d, want 2 (5xx retries exactly once)", attempts.Load())
}
}
func TestDoRequest_4xxNotRetried(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `{"code":1,"msg":"bad request"}`)
})
defer ts.Close()
c := NewClient(cfg)
if err := c.DoRequest(context.Background(), http.MethodGet, "/target", nil, nil); err == nil {
t.Fatal("expected error on 400")
}
if attempts.Load() != 1 {
t.Errorf("attempts = %d, want 1 (non-429/5xx 4xx must not retry)", attempts.Load())
}
}
func TestDownloadRawBytes_RetriesOn429ThenSucceeds(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/dl", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
if attempts.Load() == 1 {
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write([]byte("payload-bytes"))
})
defer ts.Close()
c := NewClient(cfg)
data, err := c.downloadRawBytes(context.Background(), "/dl")
if err != nil {
t.Fatalf("expected success after retry, got %v", err)
}
if string(data) != "payload-bytes" {
t.Errorf("data = %q, want %q", string(data), "payload-bytes")
}
if attempts.Load() < 2 {
t.Errorf("attempts = %d, want >= 2 (should retry download after 429)", attempts.Load())
}
}
func TestDownloadRawBytes_4xxNotRetried(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/dl", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
w.WriteHeader(http.StatusForbidden)
})
defer ts.Close()
c := NewClient(cfg)
if _, err := c.downloadRawBytes(context.Background(), "/dl"); err == nil {
t.Fatal("expected error on 403")
}
if attempts.Load() != 1 {
t.Errorf("attempts = %d, want 1 (403 must not retry)", attempts.Load())
}
}
func TestFeishuRateLimitWait(t *testing.T) {
now := time.Now().Truncate(time.Second)
tests := []struct {
reset string
retry string
want time.Duration
}{
{"", "", 10 * time.Second},
{"", "0", 100 * time.Millisecond},
{"", "-1", 100 * time.Millisecond},
{"3", "", 3 * time.Second},
{"3", "5", 5 * time.Second},
{"5", "3", 5 * time.Second},
{"abc", "2", 2 * time.Second},
{"", now.Add(4 * time.Second).UTC().Format(http.TimeFormat), 4 * time.Second},
{"NaN", "Inf", 10 * time.Second},
{"1e30", "abc", 10 * time.Second},
}
t.Setenv("FEISHU_RATE_LIMIT_RETRY_WAIT", "")
for _, tt := range tests {
headers := http.Header{}
headers.Set("x-ogw-ratelimit-reset", tt.reset)
headers.Set("Retry-After", tt.retry)
if got := feishuRateLimitWait(headers, now); got != tt.want {
t.Errorf("wait(reset=%q, retry=%q) = %v, want %v", tt.reset, tt.retry, got, tt.want)
}
}
}
func TestDoRequest_RejectsOversizedResponse(t *testing.T) {
var hits atomic.Int32
ts, cfg := retryTestServer(t, "/open-apis/docx/v1/documents", func(w http.ResponseWriter, _ *http.Request) {
hits.Add(1)
_, _ = w.Write(bytes.Repeat([]byte("a"), 1<<20+1))
})
defer ts.Close()
c := NewClient(cfg)
c.jsonLimit = 1 << 20
err := c.DoRequest(context.Background(), http.MethodGet, "/open-apis/docx/v1/documents", nil, &map[string]any{})
if err == nil {
t.Fatal("DoRequest accepted a response larger than the cap, want error")
}
if !strings.Contains(err.Error(), "exceeds maximum size") {
t.Fatalf("error = %v, want an explicit over-limit error", err)
}
// The same document is just as large on every attempt; retrying only burns
// the rate-limit budget and re-reads the full cap each time.
if got := hits.Load(); got != 1 {
t.Fatalf("server hit %d times, want 1 (oversized responses must not be retried)", got)
}
}
// The token response is decoded under tokenMu on every refresh and Ping, so it
// must honour the same cap as every other API response.
func TestGetTenantAccessToken_RejectsOversizedResponse(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
// Valid JSON, so only the size cap can reject it.
_, _ = io.WriteString(w, `{"code":0,"tenant_access_token":"fake-token","expire":7200,"pad":"`)
_, _ = w.Write(bytes.Repeat([]byte("a"), 1<<20))
_, _ = io.WriteString(w, `"}`)
})
ts := httptest.NewServer(mux)
defer ts.Close()
c := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL})
c.jsonLimit = 1 << 20
_, err := c.GetTenantAccessToken(context.Background())
if err == nil {
t.Fatal("GetTenantAccessToken accepted a response larger than the cap, want error")
}
if !strings.Contains(err.Error(), "exceeds maximum size") {
t.Fatalf("error = %v, want an explicit over-limit error", err)
}
}
// countingBody records how much of a response body the client consumed.
type countingBody struct {
io.ReadCloser
n *atomic.Int64
}
func (b countingBody) Read(p []byte) (int, error) {
n, err := b.ReadCloser.Read(p)
b.n.Add(int64(n))
return n, err
}
type countingTransport struct {
base http.RoundTripper
n *atomic.Int64
}
func (t countingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := t.base.RoundTrip(req)
if err == nil && strings.Contains(req.URL.Path, "/download") {
resp.Body = countingBody{ReadCloser: resp.Body, n: t.n}
}
return resp, err
}
// Download error bodies are only a diagnostic preview: they must be read with a
// small bound and never copied whole into the returned error.
func TestDownloadRawBytes_BoundsErrorBodies(t *testing.T) {
const bodySize = 1 << 20
for _, status := range []int{
http.StatusTooManyRequests, http.StatusBadRequest, http.StatusInternalServerError, http.StatusForbidden,
} {
t.Run(http.StatusText(status), func(t *testing.T) {
handler := func(w http.ResponseWriter, _ *http.Request) {
if status == http.StatusTooManyRequests {
w.Header().Set("Retry-After", "0")
}
w.WriteHeader(status)
_, _ = w.Write(bytes.Repeat([]byte("a"), bodySize))
}
ts, cfg := retryTestServer(t, "/open-apis/drive/v1/files/f/download", handler)
defer ts.Close()
c := NewClient(cfg)
var read atomic.Int64
hc := *c.httpClient
base := hc.Transport
if base == nil {
base = http.DefaultTransport
}
hc.Transport = countingTransport{base: base, n: &read}
c.httpClient = &hc
_, err := c.DownloadDriveFile(context.Background(), "f")
if err == nil {
t.Fatalf("status %d: want error", status)
}
if len(err.Error()) > 1024 {
t.Fatalf("error carries %d bytes of response body, want a short preview", len(err.Error()))
}
if got := read.Load(); got >= bodySize {
t.Fatalf("read %d bytes of error bodies, want a bounded preview per response", got)
}
})
}
}
@@ -0,0 +1,108 @@
package core
import (
"errors"
"strings"
"testing"
)
// feishuFailure classifies a raw connector/API error into a stable i18n code
// (+ optional numeric feishu code) and an English fallback message. The frontend
// localises by code; the raw status/body/log_id stays in the server logs and
// must never appear in the code, codeValue or fallback.
func TestFeishuFailure(t *testing.T) {
cases := []struct {
name string
err error
wantCode string
wantCodeValue string
fallbackHas []string
noLeak []string // must appear in neither code nor fallback
}{
{
name: "rate limited",
err: errors.New("feishu rate limited: status=429 body={\"code\":99991400,\"msg\":\"too many request\"}"),
wantCode: "feishu_rate_limited",
fallbackHas: []string{"retry"},
noLeak: []string{"body=", "{", "99991400"},
},
{
name: "server 5xx",
err: errors.New("feishu server error: status=500 body={\"code\":1663}"),
wantCode: "feishu_server_unavailable",
noLeak: []string{"body=", "{"},
},
{
name: "export timeout",
err: errors.New("export 季度报告 (docx): export task timed out after 60s (ticket=abc)"),
wantCode: "feishu_timeout",
noLeak: []string{"ticket=", "abc"},
},
{
name: "api error carries the feishu code as a param",
err: errors.New("feishu api error: status=500 body={\"code\":1663,\"msg\":\"internal error\",\"Error\":{\"log_id\":\"20260\"}}"),
wantCode: "feishu_api_error",
wantCodeValue: "1663",
noLeak: []string{"log_id", "body=", "{"},
},
{
name: "api error without a code is generic",
err: errors.New("feishu api error: status=502 body=bad gateway"),
wantCode: "feishu_api_error_generic",
},
{
name: "auth failure is actionable, not a retry",
err: errors.New("feishu auth error: code=99991663 msg=Invalid access token"),
wantCode: "feishu_auth_or_permission",
noLeak: []string{"Invalid access token", "99991663"},
},
{
name: "unknown error falls back to sync_failed",
err: errors.New("some totally unexpected failure"),
wantCode: "sync_failed",
noLeak: []string{"totally unexpected"},
},
{
// "decode"/"encode"/"unicode" all contain the substring "code" but
// are not Feishu API errors — they must not be classified as one.
name: "decode error is not a feishu api error",
err: errors.New("failed to decode response body"),
wantCode: "sync_failed",
},
{
// The failed item is retried on the next sync (the cursor is not
// advanced), which for a manual-only source is not automatic. The
// message must not promise an unconditional automatic retry.
name: "transient message promises retry on next sync, not automatic",
err: errors.New("feishu rate limited: status=429"),
wantCode: "feishu_rate_limited",
fallbackHas: []string{"next sync"},
noLeak: []string{"automatically"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
code, codeValue, fallback := feishuFailure(tc.err)
if code != tc.wantCode {
t.Errorf("code = %q, want %q", code, tc.wantCode)
}
if codeValue != tc.wantCodeValue {
t.Errorf("codeValue = %q, want %q", codeValue, tc.wantCodeValue)
}
if strings.TrimSpace(fallback) == "" {
t.Errorf("fallback message must not be empty")
}
for _, s := range tc.fallbackHas {
if !strings.Contains(strings.ToLower(fallback), s) {
t.Errorf("fallback %q missing %q", fallback, s)
}
}
for _, s := range tc.noLeak {
if strings.Contains(code, s) || strings.Contains(fallback, s) {
t.Errorf("raw detail %q leaked into code/fallback (code=%q fallback=%q)", s, code, fallback)
}
}
})
}
}
@@ -0,0 +1,289 @@
package core
import (
"context"
"fmt"
"time"
"academy/internal/datasource"
"academy/internal/logger"
"academy/internal/types"
)
// engine.go holds the single generic streaming sync engine shared by the wiki
// Connector and the Drive DriveConnector. The per-connector differences (node
// type, listing API, edit-time field, cursor wire format, fetch dispatch,
// log tag) are isolated behind the NodeOps adapter interface. FetchAll /
// FetchIncremental are thin wrappers over the same engine that collect Emits
// instead of streaming them.
//
// Behaviour note (deliberate, see ADR-0005 / design §2.4):
// - Resume/incremental fast-path: a node recorded at its current edit time
// is skipped, keeping the cursor entry.
// - A fetch failure does NOT advance the cursor: the prior edit time is
// retained so the node is retried next run instead of being permanently
// skipped on a transient export failure (Tencent/WeKnora#2136). This now
// also holds for the FetchIncremental path (previously it advanced the
// cursor before fetching, a latent #2136 bug).
// - Logs use the "stream progress/summary" wording uniformly; the
// FetchIncremental path additionally gains per-100 progress + tally
// summary logs it did not Emit before (log-only change).
// NodeOps adapts one connector's node type to the shared sync engine. Every
// method is a pure accessor or a thin wrapper - no engine logic lives here.
type NodeOps[N any] interface {
// List returns every syncable node under resourceID. A non-nil partial
// (with err == nil) signals a partial listing: nodes is still usable and
// the sync continues, but the caller surfaces the failed sub-trees via
// ListFailureItems. A non-nil err is fatal and aborts the sync.
List(ctx context.Context, client *Client, resourceID string) (nodes []N, partial error, err error)
Token(n N) string
Title(n N) string
ObjType(n N) string
// EditTime is an opaque change key stored in the cursor (time and/or path).
EditTime(n N) string
// fetch retrieves one node's content; (nil, nil) means an unsupported
// type that yields no item.
Fetch(ctx context.Context, client *Client, n N, resourceID string) ([]*types.FetchedItem, error)
// ListFailureItems converts a partial-listing error into error FetchedItems.
ListFailureItems(resourceID string, partial error) []types.FetchedItem
// ResourceNoun is the noun in user-visible error text: "nodes" / "files".
ResourceNoun() string
// EmptyResourceIDsError is the connector-specific message when no resource
// IDs are configured (wiki/drive text differs and is preserved verbatim).
EmptyResourceIDsError() string
// LogTag is the log prefix: "[Feishu]" / "[FeishuDrive]".
LogTag() string
// DecodeCursorTimes extracts the per-resource edit-time map from a
// persisted ConnectorCursor (nil-safe: returns nil when absent).
DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string
// EncodeCursor wraps the engine's internal times map into the connector's
// wire-format SyncCursor. JSON-marshals for snapshot isolation, mirroring
// the original FeishuCursor.toSyncCursor / FeishuDriveCursor.toSyncCursor.
EncodeCursor(times map[string]map[string]string, lastSync time.Time) *types.SyncCursor
}
// CollectHandler is the StreamHandler used by FetchAll / FetchIncremental to
// gather every Emitted item into a slice instead of streaming. Checkpoint is a
// no-op: those paths return a single cursor at the end.
type CollectHandler struct {
items []types.FetchedItem
}
func (h *CollectHandler) Emit(_ context.Context, item types.FetchedItem) error {
h.items = append(h.items, item)
return nil
}
func (h *CollectHandler) Checkpoint(_ context.Context, _ *types.SyncCursor) error { return nil }
// fullSyncPending is checkpoint-only state. A retried full pass must skip work
// completed before the checkpoint while keeping unseen deletion identities.
const fullSyncPending = "feishu_full_sync_pending"
// runSync is the single implementation behind FetchStream / FetchAll /
// FetchIncremental. With cursor == nil it fetches everything (full sync);
// with a cursor it skips nodes whose recorded edit time is unchanged
// (incremental + resume), unless forceFull is set. Full runs retain cursor
// identities for deletion tracking. resourceIDs comes from the caller: FetchStream /
// FetchIncremental pass config.ResourceIDs (after a non-empty check),
// FetchAll passes its own argument without one.
func runSync[N any](
ctx context.Context, client *Client, config *types.DataSourceConfig,
resourceIDs []string, cursor *types.SyncCursor, h datasource.StreamHandler,
ops NodeOps[N], forceFull bool,
) (*types.SyncCursor, error) {
var prevTimes map[string]map[string]string
if cursor != nil && cursor.ConnectorCursor != nil {
prevTimes = ops.DecodeCursorTimes(cursor.ConnectorCursor)
}
resumingFull := false
if cursor != nil {
resumingFull, _ = cursor.ConnectorCursor[fullSyncPending].(bool)
}
fullRun := forceFull || resumingFull
forceFull = forceFull && !resumingFull
// Keep unseen entries in checkpoints until a complete listing proves them
// deleted. This also preserves later resources if a run is interrupted.
newTimes := make(map[string]map[string]string)
for _, resourceID := range resourceIDs {
newTimes[resourceID] = make(map[string]string)
for token, edit := range prevTimes[resourceID] {
if forceFull {
// Invalidating the value (not the identity) makes failed full
// fetches retryable even if the source timestamp is unchanged.
edit = "!pending-full-fetch"
}
newTimes[resourceID][token] = edit
}
}
lastSync := time.Now()
processed := 0
lastCheckpoint := time.Now()
for _, resourceID := range resourceIDs {
nodes, partial, err := ops.List(ctx, client, resourceID)
if err != nil {
return nil, fmt.Errorf("list %s for resource %s: %w", ops.ResourceNoun(), resourceID, err)
}
if partial != nil {
for _, item := range ops.ListFailureItems(resourceID, partial) {
if eerr := h.Emit(ctx, item); eerr != nil {
return nil, eerr
}
}
}
currentNodes := make(map[string]bool)
tally := newFetchTally(len(nodes))
for i, node := range nodes {
tok := ops.Token(node)
currentNodes[tok] = true
editTimeStr := ops.EditTime(node)
var prevEdit string
var hadPrev bool
if prevTimes != nil {
if prev, ok := prevTimes[resourceID]; ok {
prevEdit, hadPrev = prev[tok]
}
}
// Resume/incremental fast-path: a node recorded at its current edit
// time is unchanged (or already synced this run) - keep the record
// and Skip re-fetching.
if !forceFull && hadPrev && prevEdit == editTimeStr {
newTimes[resourceID][tok] = editTimeStr
continue
}
items, ferr := ops.Fetch(ctx, client, node, resourceID)
if ferr != nil {
tally.fail()
// Do NOT advance the cursor: the content was never fetched.
// Retain the prior edit time (if any) so prev != current next
// run and the node is retried, instead of being permanently
// skipped on a transient export failure (Tencent/WeKnora#2136).
// The seeded entry keeps the prior key, or the invalidated
// full-fetch key, without losing its deletion identity.
if eerr := h.Emit(ctx, types.FetchedItem{
ExternalID: tok,
Title: ops.Title(node),
SourceResourceID: resourceID,
Metadata: FeishuErrorItemMeta(ferr, nil),
}); eerr != nil {
return nil, eerr
}
} else {
// Fetched, or an unsupported type (nothing to fetch): record
// the current edit time so the node is not re-processed next run.
newTimes[resourceID][tok] = editTimeStr
if len(items) > 0 {
tally.fetch()
for _, it := range items {
if eerr := h.Emit(ctx, *it); eerr != nil {
return nil, eerr
}
}
} else {
// Unsupported type (mindnote/slides/…): no item.
tally.Skip(ops.ObjType(node))
}
}
processed++
if processed%FeishuStreamCheckpointInterval == 0 || time.Since(lastCheckpoint) >= FeishuStreamCheckpointMaxInterval {
checkpoint := ops.EncodeCursor(newTimes, lastSync)
if fullRun {
checkpoint.ConnectorCursor[fullSyncPending] = true
}
if cerr := h.Checkpoint(ctx, checkpoint); cerr != nil {
logger.Warnf(ctx, "%s stream Checkpoint failed: %v", ops.LogTag(), cerr)
}
lastCheckpoint = time.Now()
}
if n := i + 1; n%100 == 0 {
logger.Infof(ctx, "%s stream progress resource=%s %d/%d (%s)",
ops.LogTag(), resourceID, n, len(nodes), tally.summary())
}
}
// Detect deleted nodes (only when the full tree was listed successfully).
// A partial listing did not enumerate the whole subtree, so deletion
// detection would false-positive.
if partial == nil && prevTimes != nil {
if prev, ok := prevTimes[resourceID]; ok {
for tok := range prev {
if !currentNodes[tok] {
if eerr := h.Emit(ctx, types.FetchedItem{
ExternalID: tok,
IsDeleted: true,
SourceResourceID: resourceID,
}); eerr != nil {
return nil, eerr
}
delete(newTimes[resourceID], tok)
}
}
}
}
logger.Infof(ctx, "%s stream summary resource=%s %s", ops.LogTag(), resourceID, tally.summary())
}
return ops.EncodeCursor(newTimes, lastSync), nil
}
// FetchStreamEngine runs the streaming sync. FetchStream / FetchIncremental
// shells differ only in whether they pass a cursor and how they collect
// results; both route here.
func FetchStreamEngine[N any](
ctx context.Context, client *Client, config *types.DataSourceConfig,
cursor *types.SyncCursor, h datasource.StreamHandler, ops NodeOps[N],
) (*types.SyncCursor, error) {
return runSync(ctx, client, config, config.ResourceIDs, cursor, h, ops, false)
}
// FetchFullStreamEngine refetches all nodes while retaining deletion identities.
func FetchFullStreamEngine[N any](
ctx context.Context, client *Client, config *types.DataSourceConfig,
cursor *types.SyncCursor, h datasource.StreamHandler, ops NodeOps[N],
) (*types.SyncCursor, error) {
return runSync(ctx, client, config, config.ResourceIDs, cursor, h, ops, true)
}
// FetchAllEngine runs a full sync, collecting every item into a slice. It
// passes the caller-supplied resourceIDs without a non-empty check (mirroring
// the original FetchAll which accepted an empty list and returned no items).
// On error any partially collected items are discarded, matching the original
// behaviour (a fatal list error dropped everything collected so far).
func FetchAllEngine[N any](
ctx context.Context, client *Client, config *types.DataSourceConfig,
resourceIDs []string, ops NodeOps[N],
) ([]types.FetchedItem, error) {
ch := &CollectHandler{}
if _, err := runSync(ctx, client, config, resourceIDs, nil, ch, ops, false); err != nil {
return nil, err
}
return ch.items, nil
}
// FetchIncrementalEngine runs an incremental sync against cursor, collecting
// items. resourceIDs come from config.ResourceIDs (non-empty check is the
// caller's responsibility).
func FetchIncrementalEngine[N any](
ctx context.Context, client *Client, config *types.DataSourceConfig,
cursor *types.SyncCursor, ops NodeOps[N],
) ([]types.FetchedItem, *types.SyncCursor, error) {
ch := &CollectHandler{}
next, err := runSync(ctx, client, config, config.ResourceIDs, cursor, ch, ops, false)
if err != nil {
return nil, nil, err
}
return ch.items, next, nil
}
@@ -0,0 +1,146 @@
package core
import (
"context"
"errors"
"fmt"
"testing"
"time"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
type fullSyncOps struct {
nodes map[string][]string
partial bool
fail map[string]bool
fetched []string
}
func (o *fullSyncOps) List(_ context.Context, _ *Client, resource string) ([]string, error, error) {
if o.partial {
return o.nodes[resource], errors.New("partial listing"), nil
}
return o.nodes[resource], nil, nil
}
func (*fullSyncOps) Token(n string) string { return n }
func (*fullSyncOps) Title(n string) string { return n }
func (*fullSyncOps) ObjType(string) string { return "file" }
func (*fullSyncOps) EditTime(string) string { return "100" }
func (o *fullSyncOps) Fetch(_ context.Context, _ *Client, n, resource string) ([]*types.FetchedItem, error) {
o.fetched = append(o.fetched, n)
if o.fail[n] {
return nil, errors.New("transient fetch failure")
}
return []*types.FetchedItem{{ExternalID: n, SourceResourceID: resource}}, nil
}
func (*fullSyncOps) ListFailureItems(string, error) []types.FetchedItem { return nil }
func (*fullSyncOps) ResourceNoun() string { return "nodes" }
func (*fullSyncOps) EmptyResourceIDsError() string { return "empty resources" }
func (*fullSyncOps) LogTag() string { return "[test]" }
func (*fullSyncOps) DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string {
return m["times"].(map[string]map[string]string)
}
func (*fullSyncOps) EncodeCursor(m map[string]map[string]string, _ time.Time) *types.SyncCursor {
snapshot := make(map[string]map[string]string)
for resource, times := range m {
snapshot[resource] = make(map[string]string)
for k, v := range times {
snapshot[resource][k] = v
}
}
return &types.SyncCursor{ConnectorCursor: map[string]interface{}{"times": snapshot}}
}
type fullSyncHandler struct {
CollectHandler
checkpoint *types.SyncCursor
stopAfterCheckpoint bool
}
func (h *fullSyncHandler) Emit(ctx context.Context, item types.FetchedItem) error {
if h.stopAfterCheckpoint && h.checkpoint != nil {
return errors.New("interrupted")
}
return h.CollectHandler.Emit(ctx, item)
}
func (h *fullSyncHandler) Checkpoint(_ context.Context, cur *types.SyncCursor) error {
h.checkpoint = cur
return nil
}
func TestFullSyncRefetchesAndReconcilesDeletions(t *testing.T) {
ops := &fullSyncOps{nodes: map[string][]string{"r": {"kept"}}}
cfg := &types.DataSourceConfig{ResourceIDs: []string{"r"}}
old := ops.EncodeCursor(map[string]map[string]string{"r": {"kept": "100", "gone": "100"}}, time.Now())
h := &fullSyncHandler{}
next, err := FetchFullStreamEngine(context.Background(), nil, cfg, old, h, ops)
require.NoError(t, err)
require.Equal(t, []string{"kept"}, ops.fetched)
require.Len(t, h.items, 2)
require.True(t, h.items[1].IsDeleted)
require.Equal(t, "gone", h.items[1].ExternalID)
require.Equal(t, map[string]string{"kept": "100"}, ops.DecodeCursorTimes(next.ConnectorCursor)["r"])
require.Contains(t, ops.DecodeCursorTimes(old.ConnectorCursor)["r"], "gone", "input baseline must remain immutable")
}
func TestFullSyncFailuresRetryWithoutLosingDeletionIdentity(t *testing.T) {
ops := &fullSyncOps{nodes: map[string][]string{"r": {"kept"}}, partial: true, fail: map[string]bool{"kept": true}}
cfg := &types.DataSourceConfig{ResourceIDs: []string{"r"}}
old := ops.EncodeCursor(map[string]map[string]string{"r": {"kept": "100", "unseen": "100"}}, time.Now())
h := &fullSyncHandler{}
next, err := FetchFullStreamEngine(context.Background(), nil, cfg, old, h, ops)
require.NoError(t, err)
require.Len(t, h.items, 1)
require.NotEmpty(t, h.items[0].Metadata["error"])
require.Contains(t, ops.DecodeCursorTimes(next.ConnectorCursor)["r"], "unseen")
ops.partial = false
ops.fail = nil
ops.fetched = nil
h = &fullSyncHandler{}
_, err = FetchStreamEngine(context.Background(), nil, cfg, next, h, ops)
require.NoError(t, err)
require.Equal(t, []string{"kept"}, ops.fetched,
"failed full fetch must retry despite an unchanged source timestamp")
require.Len(t, h.items, 2)
require.True(t, h.items[1].IsDeleted)
require.Equal(t, "unseen", h.items[1].ExternalID)
}
func TestFullSyncCheckpointRetainsUnseenDeletionBaseline(t *testing.T) {
ops := &fullSyncOps{nodes: map[string][]string{"first": {}}}
for i := 0; i < FeishuStreamCheckpointInterval+1; i++ {
ops.nodes["first"] = append(ops.nodes["first"], fmt.Sprintf("node%d", i))
}
cfg := &types.DataSourceConfig{ResourceIDs: []string{"first", "later"}}
old := ops.EncodeCursor(map[string]map[string]string{
"first": {"gone": "100"}, "later": {"gone-later": "100"},
}, time.Now())
h := &fullSyncHandler{stopAfterCheckpoint: true}
_, err := FetchFullStreamEngine(context.Background(), nil, cfg, old, h, ops)
require.Error(t, err)
require.NotNil(t, h.checkpoint)
require.Equal(t, true, h.checkpoint.ConnectorCursor[fullSyncPending])
ops.fetched = nil
resume := &fullSyncHandler{}
next, err := FetchFullStreamEngine(context.Background(), nil, cfg, h.checkpoint, resume, ops)
require.NoError(t, err)
deleted := []string{}
for _, item := range resume.items {
if item.IsDeleted {
deleted = append(deleted, item.ExternalID)
}
}
require.ElementsMatch(t, []string{"gone", "gone-later"}, deleted)
require.Equal(t, []string{fmt.Sprintf("node%d", FeishuStreamCheckpointInterval)}, ops.fetched,
"a retried full pass must not repeat successfully checkpointed fetches")
require.NotContains(t, next.ConnectorCursor, fullSyncPending)
ops.fetched = nil
_, err = FetchFullStreamEngine(context.Background(), nil, cfg, next, &fullSyncHandler{}, ops)
require.NoError(t, err)
require.Len(t, ops.fetched, len(ops.nodes["first"]),
"a later independent full sync must refetch everything")
}
@@ -0,0 +1,54 @@
package core
import (
"encoding/json"
"net/http"
"os"
"testing"
secutils "academy/internal/utils"
)
func TestMain(m *testing.M) {
os.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost,open.feishu.cn,open.larksuite.com")
secutils.ResetSSRFWhitelistForTest()
os.Exit(m.Run())
}
func writeJSON(w http.ResponseWriter, v interface{}) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(v)
}
// blk constructors mirroring wiki/connector_golden_test.go, for core-internal
// block-rendering tests (DocxBlock is same-package here, no core. prefix).
func sheetBlk(id, token string) DocxBlock {
return DocxBlock{BlockID: id, BlockType: BlockTypeSheet, Sheet: &BlockTokenRef{Token: token}}
}
func bitableBlk(id, token string) DocxBlock {
return DocxBlock{BlockID: id, BlockType: BlockTypeBitable, Bitable: &BlockTokenRef{Token: token}}
}
func imageBlk(id, token string) DocxBlock {
return DocxBlock{BlockID: id, BlockType: BlockTypeImage, Image: &BlockTokenRef{Token: token}}
}
func fileBlk(id, token, name string) DocxBlock {
return DocxBlock{BlockID: id, BlockType: BlockTypeFile, File: &BlockFileRef{Token: token, Name: name}}
}
func cellBlk(id string) DocxBlock {
return DocxBlock{BlockID: id, BlockType: BlockTypeTableCell, Children: []string{id + "_txt"}}
}
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 = &BlockTable{Cells: cellIDs}
b.Table.Property = &BlockTableProperty{ColumnSize: cols}
return b
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,33 @@
package core
import (
"math"
"testing"
"github.com/stretchr/testify/require"
)
func TestNativeTableBoundsUntrustedColumnCount(t *testing.T) {
block := DocxBlock{BlockType: BlockTypeTable, Table: &BlockTable{
Cells: []string{"cell"}, Property: &BlockTableProperty{ColumnSize: math.MaxInt},
}}
byID := map[string]DocxBlock{
"cell": {BlockID: "cell", Children: []string{"text"}},
"text": {BlockID: "text", BlockType: BlockTypeText, Text: txt("kept")},
}
require.NotPanics(t, func() { require.Contains(t, renderNativeTable(block, byID), "kept") })
block.Table.Cells = nil
require.NotPanics(t, func() { require.Empty(t, renderNativeTable(block, byID)) })
}
func TestNativeTableBoundsMergedRegions(t *testing.T) {
rows := [][]string{{"anchor", ""}, {""}, {"", ""}}
fillMergedCells(rows, 2, []BlockTableMergeInfo{{RowSpan: math.MaxInt, ColSpan: math.MaxInt}})
require.Equal(t, [][]string{{"anchor", "anchor"}, {"anchor"}, {"anchor", "anchor"}}, rows)
// A merge entry beyond the supplied cells cannot index or iterate an absent row.
fillMergedCells(rows, 2, []BlockTableMergeInfo{
{}, {}, {}, {}, {}, {}, {RowSpan: math.MaxInt, ColSpan: math.MaxInt},
})
require.Equal(t, "anchor", rows[0][0])
require.NotPanics(t, func() { fillMergedCells(rows, 0, []BlockTableMergeInfo{{RowSpan: 2, ColSpan: 2}}) })
}
@@ -0,0 +1,72 @@
package core
import (
"context"
"strings"
"testing"
)
func textBlk(id, text string, children ...string) DocxBlock {
return DocxBlock{BlockID: id, BlockType: BlockTypeText, Text: txt(text), Children: children}
}
// A table cell is a container: list or callout blocks nested in it are
// consumed by tableDescendants, so the cell must render their text.
func TestNativeTablePreservesNestedCellTextOnce(t *testing.T) {
blocks := []DocxBlock{
tableBlk("table", 1, "cell"),
{BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"callout", "after"}},
{BlockID: "callout", BlockType: BlockTypeCallout, Children: []string{"item"}},
{BlockID: "item", BlockType: BlockTypeBullet, Bullet: txt("初始化参数"), Children: []string{"nested"}},
textBlk("nested", "appKey 必填"),
textBlk("after", "最后启动"),
}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(md), "| 初始化参数 appKey 必填 最后启动 |") {
t.Fatalf("nested cell text missing or reordered:\n%s", md)
}
for _, text := range []string{"初始化参数", "appKey 必填", "最后启动"} {
if strings.Count(string(md), text) != 1 {
t.Fatalf("cell text %q duplicated:\n%s", text, md)
}
}
}
func TestNativeTableNestedCellTextHandlesRepeatedAndCyclicReferences(t *testing.T) {
blocks := []DocxBlock{
tableBlk("table", 1, "cell"),
{BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"container", "leaf", "missing"}},
{BlockID: "container", BlockType: BlockTypeCallout, Children: []string{"leaf", "cell", "container"}},
textBlk("leaf", "保留一次"),
}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatal(err)
}
if strings.Count(string(md), "保留一次") != 1 {
t.Fatalf("repeated or cyclic reference duplicated text:\n%s", md)
}
}
// Media keeps its own handling in the flat loop, and so does text nested
// under it; the cell must not render it a second time.
func TestNativeTableNestedCellTextSkipsMediaSubtrees(t *testing.T) {
for _, kind := range []int{BlockTypeFile, BlockTypeImage, BlockTypeBoard} {
blocks := []DocxBlock{
tableBlk("table", 1, "cell"),
{BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"media"}},
{BlockID: "media", BlockType: kind, Children: []string{"caption"}},
textBlk("caption", "媒体说明"),
}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(md), "| 媒体说明 |") {
t.Fatalf("media subtree rendered inside the cell for block type %d:\n%s", kind, md)
}
}
}
@@ -0,0 +1,130 @@
package core
import (
"bytes"
"context"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestContainerPreservesNestedListContent(t *testing.T) {
for _, kind := range []int{BlockTypeCallout, BlockTypeQuoteContainer, BlockTypeGrid, BlockTypeView} {
t.Run(blockNameForTest(kind), func(t *testing.T) {
blocks := []DocxBlock{
{BlockID: "container", BlockType: kind, Children: []string{"list"}},
{
BlockID: "list", ParentID: "container", BlockType: BlockTypeBullet,
Bullet: txt("parent"), Children: []string{"nested"},
},
{
BlockID: "nested", ParentID: "list", BlockType: BlockTypeOrdered,
Ordered: txt("nested"), Children: []string{"text", "image", "file"},
},
{BlockID: "text", ParentID: "nested", BlockType: BlockTypeText, Text: txt("important nested content")},
{BlockID: "image", ParentID: "nested", BlockType: BlockTypeImage, Image: &BlockTokenRef{Token: "img"}},
{
BlockID: "file", ParentID: "nested", BlockType: BlockTypeFile,
File: &BlockFileRef{Token: "pdf", Name: "report.pdf"},
},
}
if kind == BlockTypeGrid {
blocks[0].Children = []string{"column"}
blocks = append(blocks, DocxBlock{
BlockID: "column", BlockType: BlockTypeGridColumn, Children: []string{"list"},
})
}
md, atts, imgs, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
require.NoError(t, err)
for _, text := range []string{"parent", "nested content", "academy-att://pdf", "academy-img://"} {
require.Equal(t, 1, strings.Count(string(md), text), "content must appear exactly once: %s", md)
}
require.Len(t, atts, 1)
require.Len(t, imgs, 1)
require.Contains(t, string(md), " 1. nested")
})
}
}
func blockNameForTest(kind int) string {
switch kind {
case BlockTypeCallout:
return "callout"
case BlockTypeQuoteContainer:
return "quote"
case BlockTypeGrid:
return "grid"
default:
return "view"
}
}
func TestContainerNestedOrderedListKeepsParentSequence(t *testing.T) {
blocks := []DocxBlock{
{BlockID: "container", BlockType: BlockTypeView, Children: []string{"first", "second"}},
{
BlockID: "first", ParentID: "container", BlockType: BlockTypeOrdered,
Ordered: txt("parent one"), Children: []string{"nested"},
},
{BlockID: "nested", ParentID: "first", BlockType: BlockTypeOrdered, Ordered: txt("child one")},
{BlockID: "second", ParentID: "container", BlockType: BlockTypeOrdered, Ordered: txt("parent two")},
}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
require.NoError(t, err)
require.Contains(t, string(md), "1. parent one\n\n 1. child one\n2. parent two")
}
func TestBoardInNativeTableIsDownloaded(t *testing.T) {
for _, inContainer := range []bool{false, true} {
t.Run(map[bool]string{false: "table", true: "table in callout"}[inContainer], func(t *testing.T) {
blocks := []DocxBlock{
{
BlockID: "table", BlockType: BlockTypeTable, Children: []string{"cell"},
Table: &BlockTable{Cells: []string{"cell"}, Property: &BlockTableProperty{ColumnSize: 1}},
},
{BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"text", "board"}},
{BlockID: "text", BlockType: BlockTypeText, Text: txt("board caption")},
{BlockID: "board", BlockType: BlockTypeBoard, Board: &BlockBoard{Token: "brd-1"}},
}
if inContainer {
blocks = append([]DocxBlock{
{BlockID: "callout", BlockType: BlockTypeCallout, Children: []string{"table"}},
}, blocks...)
}
png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), MinAttachmentBytes)...)
server := fakeFeishuForBoard(t, blocks, http.StatusOK, png)
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: server.URL})
items, err := FetchDocxWithBlocks(context.Background(), client, boardFetchInput())
require.NoError(t, err)
require.Len(t, items, 1)
md := string(items[0].Content)
require.Equal(t, 1, strings.Count(md, "data:image/png;base64,"))
require.Equal(t, 1, strings.Count(md, "board caption"))
require.NotContains(t, md, "academy-img://")
})
}
}
func TestContainerPreservesMalformedTableChildren(t *testing.T) {
blocks := []DocxBlock{
{BlockID: "view", BlockType: BlockTypeView, Children: []string{"table"}},
{BlockID: "table", BlockType: BlockTypeTable, Children: []string{"cell"}},
{BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"text"}},
{BlockID: "text", BlockType: BlockTypeText, Text: txt("retained content")},
}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
require.NoError(t, err)
require.Equal(t, 1, strings.Count(string(md), "retained content"))
}
func TestContainerCyclicChildrenTerminate(t *testing.T) {
blocks := []DocxBlock{
{BlockID: "view", BlockType: BlockTypeView, Children: []string{"list"}},
{BlockID: "list", BlockType: BlockTypeBullet, Bullet: txt("cyclic content"), Children: []string{"list"}},
}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
require.NoError(t, err)
require.Equal(t, 1, strings.Count(string(md), "cyclic content"))
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,76 @@
package core
import (
"bytes"
"context"
"image"
"image/color"
"image/draw"
"image/png"
"net/http"
"strings"
"testing"
)
func TestTableViewKeepsFileAndBoard(t *testing.T) {
for _, kind := range []int{BlockTypeView, BlockTypeCallout, BlockTypeQuoteContainer, BlockTypeGrid} {
t.Run(blockNameForTest(kind), func(t *testing.T) {
blocks := []DocxBlock{
{
BlockID: "table", BlockType: BlockTypeTable, Children: []string{"cell"},
Table: &BlockTable{Cells: []string{"cell"}, Property: &BlockTableProperty{ColumnSize: 1}},
},
{BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"view"}},
{BlockID: "view", BlockType: kind, Children: []string{"file", "board"}},
{BlockID: "file", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "pdf", Name: "report.pdf"}},
{BlockID: "board", BlockType: BlockTypeBoard, Board: &BlockBoard{Token: "brd-1"}},
}
for _, outer := range []bool{false, true} {
if outer {
blocks = append([]DocxBlock{
{BlockID: "outer", BlockType: BlockTypeView, Children: []string{"table"}},
}, blocks...)
}
md, atts, imgs, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatal(err)
}
if len(atts) != 1 || len(imgs) != 1 {
t.Fatalf("table view media lost: attachments=%d images=%d markdown=%q", len(atts), len(imgs), md)
}
if strings.Count(string(md), "academy-att://pdf") != 1 ||
strings.Count(string(md), "academy-img://") != 1 {
t.Fatalf("media must render exactly once: %s", md)
}
}
})
}
}
func TestTrimmedBoardKeepsMeaningfulDiagram(t *testing.T) {
img := image.NewRGBA(image.Rect(0, 0, 1600, 1200))
draw.Draw(img, img.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
draw.Draw(img, image.Rect(400, 400, 700, 600), image.NewUniform(color.Black), image.Point{}, draw.Src)
var b bytes.Buffer
if err := png.Encode(&b, img); err != nil {
t.Fatal(err)
}
cropped := trimBoardImage(b.Bytes())
cfg, _, err := image.DecodeConfig(bytes.NewReader(cropped))
if err != nil {
t.Fatal(err)
}
if len(cropped) >= MinAttachmentBytes || cfg.Width < 64 || cfg.Height < 64 {
t.Fatalf("fixture must be a sub-2KB diagram with meaningful dimensions: bytes=%d dims=%dx%d",
len(cropped), cfg.Width, cfg.Height)
}
server := fakeFeishuForBoard(t, boardBlocks(), http.StatusOK, b.Bytes())
client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: server.URL})
items, err := FetchDocxWithBlocks(context.Background(), client, boardFetchInput())
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(items[len(items)-1].Content), "data:image/png;base64,") {
t.Fatalf("valid board disappeared: %s", items[len(items)-1].Content)
}
}
@@ -0,0 +1,180 @@
package core
import (
"context"
"net/http"
"strings"
"sync/atomic"
"testing"
)
// mentionBlk builds a text block whose only inline element is an @mention of
// the given OpenID.
func mentionBlk(id, openID string) DocxBlock {
return DocxBlock{
BlockID: id, BlockType: BlockTypeText,
Text: &BlockText{Elements: []TextElement{{MentionUser: &MentionUser{UserID: openID}}}},
}
}
// mentionUserCase renders blocks and asserts the resolved display names hit
// (named) and miss/403-degrade (generic @成员) paths.
func mentionUserCase(t *testing.T, name string, resolver func(string) string, blocks []DocxBlock, want []string) {
t.Helper()
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", resolver)
if err != nil {
t.Fatalf("%s: err: %v", name, err)
}
for _, w := range want {
if !strings.Contains(string(md), w) {
t.Errorf("%s: missing %q, got:\n%s", name, w, md)
}
}
}
func TestBlocksToMarkdown_MentionUserName(t *testing.T) {
// Hit: OpenID resolves to a real display name.
resolved := map[string]string{"ou_zhang": "张三", "ou_li": "李四"}
mentionUserCase(t, "hit", func(id string) string { return resolved[id] },
[]DocxBlock{
{BlockID: "p1", BlockType: BlockTypeText, Text: &BlockText{Elements: []TextElement{
{TextRun: &TextRun{Content: "请 "}},
{MentionUser: &MentionUser{UserID: "ou_zhang"}},
}}},
mentionBlk("p2", "ou_li"),
},
[]string{"@张三", "@李四"})
// Miss (unknown user / API failure): degrade to the generic marker, and
// the document still renders — the failure never surfaces as an error.
var calls int
mentionUserCase(t, "miss", func(_ string) string {
calls++
return ""
}, []DocxBlock{mentionBlk("p1", "ou_gone")},
[]string{"@成员"})
if calls != 1 {
t.Errorf("resolver calls = %d, want 1", calls)
}
}
func TestBlocksToMarkdown_MentionUserName_OncePerElement(t *testing.T) {
var calls int
resolver := func(_ string) string {
calls++
return "张三"
}
blocks := []DocxBlock{mentionBlk("p1", "ou_x"), mentionBlk("p2", "ou_x"), mentionBlk("p3", "ou_y")}
md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", resolver)
if err != nil {
t.Fatalf("err: %v", err)
}
// The renderer consults the resolver once per mention element; dedup
// caching lives in the userNameResolver closure (tested with real HTTP
// traffic in TestUserNameResolver_NegativeCache).
if calls != 3 {
t.Errorf("resolver calls = %d, want 3 (one per mention element)", calls)
}
if got := strings.Count(string(md), "@张三"); got != 3 {
t.Errorf("mentions rendered = %d, want 3, got:\n%s", got, md)
}
}
func TestBlocksToMarkdown_NoMention_ZeroResolverCalls(t *testing.T) {
var calls int
resolver := func(_ string) string {
calls++
return "张三"
}
blocks := []DocxBlock{
{BlockID: "p1", BlockType: BlockTypeText, Text: txt("没有提及的普通段落")},
{BlockID: "p2", BlockType: BlockTypeText, Text: txt("另一段")},
}
if _, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", resolver); err != nil {
t.Fatalf("err: %v", err)
}
if calls != 0 {
t.Errorf("resolver calls = %d, want 0 (no API traffic without mentions)", calls)
}
}
func TestUserName(t *testing.T) {
ts, cfg := retryTestServer(t, "/open-apis/contact/v3/users/ou_1", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("user_id_type") != "open_id" {
t.Errorf("user_id_type = %q, want open_id", r.URL.Query().Get("user_id_type"))
}
writeJSON(w, map[string]any{"code": 0, "data": map[string]any{
"user": map[string]any{"name": "张三"},
}})
})
defer ts.Close()
c := NewClient(cfg)
name, err := c.UserName(context.Background(), "ou_1")
if err != nil {
t.Fatalf("err: %v", err)
}
if name != "张三" {
t.Errorf("name = %q, want 张三", name)
}
// 403 (no contact scope): error, caller degrades.
ts403, cfg403 := retryTestServer(t, "/open-apis/contact/v3/users/ou_1",
func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"code":99991679,"msg":"permission denied"}`))
})
defer ts403.Close()
if _, err := NewClient(cfg403).UserName(context.Background(), "ou_1"); err == nil {
t.Error("403 must return an error for the caller to degrade")
}
// HTTP 200 but business error code: also an error.
tsCode, cfgCode := retryTestServer(t, "/open-apis/contact/v3/users/ou_1",
func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, map[string]any{"code": 99991672, "msg": "no permission"})
})
defer tsCode.Close()
if _, err := NewClient(cfgCode).UserName(context.Background(), "ou_1"); err == nil {
t.Error("non-zero body code must return an error")
}
}
func TestUserNameResolver_NegativeCache(t *testing.T) {
var hits atomic.Int64
ts, cfg := retryTestServer(t, "/open-apis/contact/v3/users/", func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
if strings.Contains(r.URL.Path, "ou_ok") {
writeJSON(w, map[string]any{"code": 0, "data": map[string]any{
"user": map[string]any{"name": "张三"},
}})
return
}
// No permission for the other user, forever.
w.WriteHeader(http.StatusForbidden)
})
defer ts.Close()
resolver := userNameResolver(context.Background(), NewClient(cfg))
// Same user three times: resolved once; failed user three times: one
// negative-cached attempt. Total HTTP traffic must be 2.
got := []string{
resolver("ou_ok"), resolver("ou_ok"), resolver("ou_ok"),
resolver("ou_bad"), resolver("ou_bad"), resolver("ou_bad"),
}
for i, g := range got {
want := "张三"
if i >= 3 {
want = ""
}
if g != want {
t.Errorf("resolver[%d] = %q, want %q", i, g, want)
}
}
if n := hits.Load(); n != 2 {
t.Errorf("contact API hits = %d, want 2 (per-user cache incl. negative)", n)
}
if _, err := NewClient(cfg).UserName(context.Background(), ""); err == nil {
t.Error("empty user id must be rejected without an API call")
}
}
@@ -0,0 +1,112 @@
package core
import (
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// parseModeConfig builds a minimal valid DataSourceConfig with the given
// Settings, enough for ParseFeishuConfig to succeed.
func parseModeConfig(settings map[string]interface{}) *types.DataSourceConfig {
return &types.DataSourceConfig{
Type: types.ConnectorTypeFeishu,
Credentials: map[string]interface{}{"app_id": "cli-x", "app_secret": "sec"},
ResourceIDs: []string{"space1"},
Settings: settings,
}
}
// ParseFeishuConfig resolves Settings["parse_mode"] into Config.ParseMode.
// The default is blocks since parse_mode moved to the data source (2026-09
// deep adaptation): unset and empty both mean blocks, an explicit export is
// preserved as the image-association escape hatch, and an unrecognized value
// falls back to blocks instead of failing the sync. The retired
// FEISHU_DOCX_PARSE_MODE env var is still honored as a deprecated fallback
// while the per-source setting is unset.
func TestParseFeishuConfig_ParseMode(t *testing.T) {
// Hermetic baseline: neutralize any ambient FEISHU_DOCX_PARSE_MODE so the
// default cases below never depend on the host environment.
t.Setenv("FEISHU_DOCX_PARSE_MODE", "")
t.Run("unset settings default to blocks", func(t *testing.T) {
cfg, err := ParseFeishuConfig(parseModeConfig(nil), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
t.Run("settings without parse_mode default to blocks", func(t *testing.T) {
cfg, err := ParseFeishuConfig(
parseModeConfig(map[string]interface{}{"timezone": "Asia/Shanghai"}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
t.Run("explicit blocks", func(t *testing.T) {
cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": "blocks"}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
t.Run("explicit export is preserved", func(t *testing.T) {
cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": "export"}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeExport, cfg.ParseMode)
})
t.Run("case and whitespace insensitive", func(t *testing.T) {
cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": " Export "}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeExport, cfg.ParseMode)
})
t.Run("invalid value falls back to blocks", func(t *testing.T) {
cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": "yaml"}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
t.Run("empty value falls back to blocks", func(t *testing.T) {
cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": " "}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
t.Run("deprecated env fallback honored while settings unset", func(t *testing.T) {
t.Setenv("FEISHU_DOCX_PARSE_MODE", "export")
cfg, err := ParseFeishuConfig(parseModeConfig(nil), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeExport, cfg.ParseMode)
})
t.Run("deprecated env fallback is case and whitespace insensitive", func(t *testing.T) {
t.Setenv("FEISHU_DOCX_PARSE_MODE", " Export ")
cfg, err := ParseFeishuConfig(
parseModeConfig(map[string]interface{}{"timezone": "Asia/Shanghai"}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeExport, cfg.ParseMode)
})
t.Run("per-source parse_mode overrides deprecated env", func(t *testing.T) {
t.Setenv("FEISHU_DOCX_PARSE_MODE", "export")
cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": "blocks"}), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
t.Run("invalid deprecated env value falls back to blocks", func(t *testing.T) {
t.Setenv("FEISHU_DOCX_PARSE_MODE", "yaml")
cfg, err := ParseFeishuConfig(parseModeConfig(nil), RegionFeishu)
require.NoError(t, err)
assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
})
}
// ParseMode threading: DocxFetchInput.ParseMode is the single transport
// (connector entry resolves it via ParseFeishuConfig and passes it through
// ops → fetchNodeContent → DocxFetchInput). Empty degrades to blocks inside
// FetchDocxWithBlocks; resolution itself is covered by
// TestParseFeishuConfig_ParseMode above, and the wiki/drive suites exercise
// the blocks default end-to-end with ops built without an explicit mode.
@@ -0,0 +1,81 @@
package core
import "academy/internal/types"
// Open Platform API origins. Feishu and Lark are the same product deployed on
// two isolated clouds; the wiki/docx/drive APIs this connector uses are
// identical, only the host differs.
const (
feishuOpenBaseURL = "https://open.feishu.cn"
larkOpenBaseURL = "https://open.larksuite.com"
)
// Web origins used to build human-facing links to wiki spaces and nodes. These
// are the end-user app hosts, not the API hosts.
const (
feishuWebBaseURL = "https://feishu.cn"
larkWebBaseURL = "https://larksuite.com"
)
// Region selects which cloud the connector syncs from. Apps, tenants, tokens
// and document tokens are scoped to a single cloud and are never valid on the
// other, so a Region is fixed per connector instance at registration.
type Region struct {
// ConnectorType is the types.ConnectorType* identifier this instance serves.
ConnectorType string
// OpenBaseURL is the Open Platform API origin, without a trailing slash.
// It is only the default: a data source may override it via base_url.
OpenBaseURL string
// WebBaseURL is the app origin used to build wiki links shown to users.
WebBaseURL string
// Label prefixes log lines so operators can tell the clouds apart.
Label string
}
var (
// RegionFeishu is the Chinese mainland cloud (飞书).
RegionFeishu = Region{
ConnectorType: types.ConnectorTypeFeishu,
OpenBaseURL: feishuOpenBaseURL,
WebBaseURL: feishuWebBaseURL,
Label: "Feishu",
}
// RegionLark is the international cloud (Lark).
RegionLark = Region{
ConnectorType: types.ConnectorTypeLark,
OpenBaseURL: larkOpenBaseURL,
WebBaseURL: larkWebBaseURL,
Label: "Lark",
}
// RegionFeishuDrive is the Chinese mainland cloud, Drive (云盘) mode.
// Shares the feishu connector package with RegionFeishu; only the connector
// type differs so the registry dispatches to the Drive connector.
RegionFeishuDrive = Region{
ConnectorType: types.ConnectorTypeFeishuDrive,
OpenBaseURL: feishuOpenBaseURL,
WebBaseURL: feishuWebBaseURL,
Label: "FeishuDrive",
}
// RegionLarkDrive is the international cloud, Drive mode.
RegionLarkDrive = Region{
ConnectorType: types.ConnectorTypeLarkDrive,
OpenBaseURL: larkOpenBaseURL,
WebBaseURL: larkWebBaseURL,
Label: "LarkDrive",
}
)
// WikiURL builds the user-facing link to a wiki space or node on this cloud.
// The token is either a space_id or a node_token; both live under /wiki/.
func (r Region) WikiURL(token string) string {
return r.WebBaseURL + "/wiki/" + token
}
// DriveFolderURL builds the user-facing link to a Drive folder on this cloud.
// A folder_token lives under /drive/folder/.
func (r Region) DriveFolderURL(folderToken string) string {
return r.WebBaseURL + "/drive/folder/" + folderToken
}
@@ -0,0 +1,76 @@
package core
import (
"strings"
"testing"
"academy/internal/types"
)
func TestRegions_AreDistinct(t *testing.T) {
if RegionFeishu.ConnectorType == RegionLark.ConnectorType {
t.Errorf("regions share ConnectorType %q", RegionFeishu.ConnectorType)
}
if RegionFeishu.OpenBaseURL == RegionLark.OpenBaseURL {
t.Errorf("regions share OpenBaseURL %q", RegionFeishu.OpenBaseURL)
}
if RegionFeishu.WebBaseURL == RegionLark.WebBaseURL {
t.Errorf("regions share WebBaseURL %q", RegionFeishu.WebBaseURL)
}
if RegionFeishu.ConnectorType != types.ConnectorTypeFeishu {
t.Errorf("RegionFeishu.ConnectorType = %q, want %q", RegionFeishu.ConnectorType, types.ConnectorTypeFeishu)
}
if RegionLark.ConnectorType != types.ConnectorTypeLark {
t.Errorf("RegionLark.ConnectorType = %q, want %q", RegionLark.ConnectorType, types.ConnectorTypeLark)
}
}
// TestConnectorType_FollowsRegion lives in package wiki (it exercises
// wiki.NewConnector); see wiki/connector_test.go TestConnectorType.
// The wiki link shown in the resource picker must point at the cloud the data
// actually lives on. Feishu's value is the pre-existing one and must not drift.
func TestRegion_WikiURL(t *testing.T) {
if got, want := RegionFeishu.WikiURL("spc123"), "https://feishu.cn/wiki/spc123"; got != want {
t.Errorf("Feishu WikiURL = %q, want %q", got, want)
}
if got, want := RegionLark.WikiURL("spc123"), "https://larksuite.com/wiki/spc123"; got != want {
t.Errorf("Lark WikiURL = %q, want %q", got, want)
}
// A Lark link must never point at the Feishu host — that was the bug.
if strings.Contains(RegionLark.WikiURL("x"), "feishu") {
t.Errorf("Lark WikiURL leaks the Feishu host: %q", RegionLark.WikiURL("x"))
}
}
// base_url stays an override so data sources created before the lark connector
// existed — a "feishu" connector pointed at open.larksuite.com — keep working.
func TestParseFeishuConfig_BaseURLDefaultsToRegion(t *testing.T) {
cases := []struct {
name string
region Region
baseURL string
want string
}{
{"feishu default", RegionFeishu, "", "https://open.feishu.cn"},
{"lark default", RegionLark, "", "https://open.larksuite.com"},
{"explicit override wins on feishu", RegionFeishu, "https://open.larksuite.com", "https://open.larksuite.com"},
{"explicit override wins on lark", RegionLark, "https://open.feishu.cn", "https://open.feishu.cn"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
creds := map[string]interface{}{"app_id": "cli_x", "app_secret": "s"}
if c.baseURL != "" {
creds["base_url"] = c.baseURL
}
cfg, err := ParseFeishuConfig(&types.DataSourceConfig{Credentials: creds}, c.region)
if err != nil {
t.Fatalf("ParseFeishuConfig: %v", err)
}
if got := cfg.GetBaseURL(); got != c.want {
t.Errorf("GetBaseURL() = %q, want %q", got, c.want)
}
})
}
}
@@ -0,0 +1,238 @@
package core
import (
"bytes"
"context"
"encoding/json"
"math"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
)
const (
defaultFeishuRequestsPerMinute = 80
defaultFeishuRateLimitWait = 10 * time.Second
defaultFeishuMaxCooldown = 5 * time.Minute
defaultFeishuExportMaxPolls = 30
defaultFeishuExportPollInterval = 2 * time.Second
)
// Feishu defines this code in its API protocol. Derive the prefilter from the
// same value used for the decoded response so the two checks cannot drift.
const feishuRateLimitCode = 99991400
var feishuRateLimitCodeBytes = []byte(strconv.Itoa(feishuRateLimitCode))
// Export APIs each allow 100 requests/minute. Reserve headroom and pace requests
// without bursts. Wiki listing has its own budget; other APIs have separate
// reactive cooldowns by API path template. The registry spans clients, data
// sources and task retries in this process. Different App IDs and API hosts
// have independent budgets.
var feishuRequestGates sync.Map
type feishuRequestGateKey struct {
baseURL string
appID string
api string
}
type feishuRequestGate struct {
api string
mu sync.Mutex
interval time.Duration
nextRequest time.Time
blockedUntil time.Time
}
func feishuRequestInterval() time.Duration {
rpm, err := strconv.Atoi(strings.TrimSpace(os.Getenv("FEISHU_API_REQUESTS_PER_MINUTE")))
if err != nil || rpm <= 0 || int64(rpm) > int64(time.Minute) {
rpm = defaultFeishuRequestsPerMinute
}
return time.Minute / time.Duration(rpm)
}
func feishuRequestAPI(method, path string) (string, bool) {
path, _, _ = strings.Cut(path, "?")
path = strings.TrimRight(path, "/")
if method == http.MethodPost && path == "/open-apis/drive/v1/export_tasks" {
return "export-create", true
}
if method == http.MethodGet && strings.HasPrefix(path, "/open-apis/drive/v1/export_tasks/") {
if strings.HasPrefix(path, "/open-apis/drive/v1/export_tasks/file/") && strings.HasSuffix(path, "/download") {
return "export-download", true
}
return "export-status", true
}
if method == http.MethodGet &&
strings.HasPrefix(path, "/open-apis/wiki/v2/spaces/") && strings.HasSuffix(path, "/nodes") {
return "wiki-node-list", true
}
// Normalize the connector's remaining API paths without retaining document
// tokens, sheet ranges or query parameters. Methods have independent quotas.
parts := strings.Split(path, "/")
for _, template := range []string{
"/open-apis/drive/v1/files/:token/download",
"/open-apis/drive/v1/medias/:token/download",
"/open-apis/drive/explorer/v2/folder/:token/meta",
"/open-apis/docx/v1/documents/:token/raw_content",
"/open-apis/docx/v1/documents/:token/blocks",
"/open-apis/sheets/v2/spreadsheets/:token/values/:range",
"/open-apis/bitable/v1/apps/:token/tables/:table/fields",
"/open-apis/bitable/v1/apps/:token/tables/:table/records/search",
"/open-apis/wiki/v2/spaces/get_node",
} {
pattern := strings.Split(template, "/")
if len(parts) != len(pattern) {
continue
}
match := true
for i, segment := range pattern {
if !strings.HasPrefix(segment, ":") && segment != parts[i] {
match = false
break
}
}
if match {
return method + " " + template, false
}
}
// Unknown endpoints share only their service/version/resource prefix, never
// a process-wide "other" gate or a gate per document token.
parts = strings.Split(strings.Trim(path, "/"), "/")
return method + " /" + strings.Join(parts[:min(4, len(parts))], "/"), false
}
func feishuConfiguredDuration(name string, fallback time.Duration) time.Duration {
configured, err := time.ParseDuration(strings.TrimSpace(os.Getenv(name)))
if err == nil && configured > 0 {
return configured
}
return fallback
}
func feishuExportMaxPolls() int {
configured, err := strconv.Atoi(strings.TrimSpace(os.Getenv("FEISHU_EXPORT_MAX_POLLS")))
if err == nil && configured > 0 {
return configured
}
return defaultFeishuExportMaxPolls
}
func (c *Client) requestGate(method, path string) *feishuRequestGate {
api, paced := feishuRequestAPI(method, path)
key := feishuRequestGateKey{strings.TrimRight(c.baseURL, "/"), c.appID, api}
if existing, ok := feishuRequestGates.Load(key); ok {
return existing.(*feishuRequestGate)
}
gate := &feishuRequestGate{api: api}
if paced {
gate.interval = feishuRequestInterval()
}
actual, _ := feishuRequestGates.LoadOrStore(key, gate)
return actual.(*feishuRequestGate)
}
// wait reserves the next free slot before sleeping, so callers are granted in
// arrival order instead of racing for each slot after a shared wake-up. A
// cooldown imposed while sleeping invalidates the reservation; the caller waits
// it out and reserves again. Cancelled reservations are not reused, which only
// errs towards sending fewer requests.
func (g *feishuRequestGate) wait(ctx context.Context) error {
for {
if err := ctx.Err(); err != nil {
return err
}
g.mu.Lock()
now := time.Now()
if blocked := g.blockedUntil.Sub(now); blocked > 0 {
g.mu.Unlock()
if err := sleepCtx(ctx, blocked); err != nil {
return err
}
continue
}
slot := now
if g.nextRequest.After(slot) {
slot = g.nextRequest
}
g.nextRequest = slot.Add(g.interval)
g.mu.Unlock()
if err := sleepCtx(ctx, slot.Sub(now)); err != nil {
return err
}
g.mu.Lock()
blocked := g.blockedUntil.After(time.Now())
g.mu.Unlock()
if !blocked {
return nil
}
}
}
// Even an exhausted retry delays the next document, rather than letting a long
// sync continue hammering an API which has already rejected this application.
func (g *feishuRequestGate) cooldown(wait time.Duration) {
wait = min(wait, feishuConfiguredDuration("FEISHU_RATE_LIMIT_MAX_WAIT", defaultFeishuMaxCooldown))
g.mu.Lock()
defer g.mu.Unlock()
until := time.Now().Add(wait)
if until.After(g.blockedUntil) {
g.blockedUntil = until
}
}
func isFeishuRateLimited(status int, body []byte) bool {
if status == http.StatusTooManyRequests {
return true
}
if status != http.StatusBadRequest && status != http.StatusOK {
return false
}
// Successful block/record responses can be large. Only JSON-decode the
// envelope when it could contain the legacy rate-limit code.
if !bytes.Contains(body, feishuRateLimitCodeBytes) {
return false
}
var response struct {
Code int `json:"code"`
}
return json.Unmarshal(body, &response) == nil && response.Code == feishuRateLimitCode
}
func feishuRateLimitWait(headers http.Header, now time.Time) time.Duration {
var wait time.Duration
valid := false
for _, name := range []string{"x-ogw-ratelimit-reset", "Retry-After"} {
value := strings.TrimSpace(headers.Get(name))
if value == "" {
continue
}
seconds, err := strconv.ParseFloat(value, 64)
if err != nil && name == "Retry-After" {
if date, dateErr := http.ParseTime(value); dateErr == nil {
seconds, err = date.Sub(now).Seconds(), nil
}
}
if err != nil || math.IsNaN(seconds) || math.IsInf(seconds, 0) ||
seconds >= float64(math.MaxInt64)/float64(time.Second) {
continue
}
valid = true
candidate := 100 * time.Millisecond
if seconds > 0 {
candidate = time.Duration(seconds * float64(time.Second))
}
if candidate > wait {
wait = candidate
}
}
if !valid {
wait = feishuConfiguredDuration("FEISHU_RATE_LIMIT_RETRY_WAIT", defaultFeishuRateLimitWait)
}
return min(wait, feishuConfiguredDuration("FEISHU_RATE_LIMIT_MAX_WAIT", defaultFeishuMaxCooldown))
}
@@ -0,0 +1,530 @@
package core
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"sort"
"strings"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
"time"
)
func TestFeishuRequestIntervalConfiguration(t *testing.T) {
for _, tt := range []struct {
value string
want time.Duration
}{
{"", 750 * time.Millisecond},
{"80", 750 * time.Millisecond},
{"60", time.Second},
{"0", 750 * time.Millisecond},
{"-1", 750 * time.Millisecond},
{"invalid", 750 * time.Millisecond},
} {
t.Setenv("FEISHU_API_REQUESTS_PER_MINUTE", tt.value)
if got := feishuRequestInterval(); got != tt.want {
t.Errorf("interval(%q)=%s, want %s", tt.value, got, tt.want)
}
}
t.Setenv("FEISHU_RATE_LIMIT_RETRY_WAIT", "7s")
if got := feishuRateLimitWait(http.Header{}, time.Now()); got != 7*time.Second {
t.Fatalf("configured fallback = %s", got)
}
}
func TestFeishuGatesShareAppAndAPIIndependentOfDocument(t *testing.T) {
resetFeishuRequestGates(t)
t.Setenv("FEISHU_API_REQUESTS_PER_MINUTE", "80")
first := NewClient(&Config{AppID: t.Name(), BaseURL: "http://limits-test"})
second := NewClient(&Config{AppID: t.Name(), BaseURL: "http://limits-test/"})
poll := first.requestGate(http.MethodGet, "/open-apis/drive/v1/export_tasks/ticket-one?token=one")
if poll != second.requestGate(http.MethodGet, "/open-apis/drive/v1/export_tasks/ticket-two?token=two") {
t.Fatal("ticket and query must not create independent rate budgets")
}
if poll.interval != 750*time.Millisecond {
t.Fatalf("default interval = %s", poll.interval)
}
create := first.requestGate(http.MethodPost, "/open-apis/drive/v1/export_tasks")
download := first.requestGate(http.MethodGet, "/open-apis/drive/v1/export_tasks/file/one/download")
if create == poll || create == download || poll == download {
t.Fatal("export APIs must have separate budgets")
}
if download != second.requestGate(http.MethodGet, "/open-apis/drive/v1/export_tasks/file/two/download") {
t.Fatal("download tokens must share one budget")
}
otherApp := NewClient(&Config{AppID: t.Name() + "-other", BaseURL: first.baseURL})
otherHost := NewClient(&Config{AppID: t.Name(), BaseURL: "http://other-host"})
if create == otherApp.requestGate(http.MethodPost, "/open-apis/drive/v1/export_tasks") ||
create == otherHost.requestGate(http.MethodPost, "/open-apis/drive/v1/export_tasks") {
t.Fatal("different applications and API hosts must not share a budget")
}
nodes := first.requestGate(http.MethodGet, "/open-apis/wiki/v2/spaces/one/nodes?parent_node_token=one")
if nodes != second.requestGate(http.MethodGet, "/open-apis/wiki/v2/spaces/two/nodes?parent_node_token=two") ||
nodes.interval != poll.interval {
t.Fatal("wiki list paths must share a paced budget")
}
}
func TestFeishuGatePacesConcurrentClients(t *testing.T) {
t.Setenv("FEISHU_API_REQUESTS_PER_MINUTE", "3000") // 20ms for a bounded test.
var mu sync.Mutex
var arrivals []time.Time
ts, cfg := retryTestServer(t, "/open-apis/drive/v1/export_tasks", func(w http.ResponseWriter, _ *http.Request) {
mu.Lock()
arrivals = append(arrivals, time.Now())
mu.Unlock()
writeJSON(w, ApiResponse{Code: 0})
})
defer ts.Close()
clients := []*Client{NewClient(cfg), NewClient(cfg)}
var wg sync.WaitGroup
for i := 0; i < 6; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
err := clients[i%2].DoRequest(context.Background(),
http.MethodPost, "/open-apis/drive/v1/export_tasks", nil, nil)
if err != nil {
t.Errorf("request: %v", err)
}
}(i)
}
wg.Wait()
sort.Slice(arrivals, func(i, j int) bool { return arrivals[i].Before(arrivals[j]) })
if len(arrivals) != 6 {
t.Fatalf("received %d requests", len(arrivals))
}
if elapsed := arrivals[5].Sub(arrivals[0]); elapsed < 90*time.Millisecond {
t.Fatalf("clients burst through shared budget: elapsed=%s", elapsed)
}
}
func TestFeishuLegacyRateLimitRetriesJSONAndDownload(t *testing.T) {
for _, tt := range []struct {
name string
download bool
status int
}{
{"json_400", false, http.StatusBadRequest},
{"json_200", false, http.StatusOK},
{"download_400", true, http.StatusBadRequest},
} {
t.Run(tt.name, func(t *testing.T) {
var attempts atomic.Int32
var firstAttempt atomic.Int64
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
if attempts.Add(1) == 1 {
firstAttempt.Store(time.Now().UnixNano())
w.Header().Set("x-ogw-ratelimit-reset", "0.05")
w.WriteHeader(tt.status)
_, _ = io.WriteString(w, `{"code":99991400,"msg":"request trigger frequency limit"}`)
return
}
if time.Since(time.Unix(0, firstAttempt.Load())) < 50*time.Millisecond {
t.Error("request retried before Feishu reset time")
}
if tt.download {
_, _ = io.WriteString(w, "file-content")
} else {
writeJSON(w, ApiResponse{Code: 0})
}
})
defer ts.Close()
c := NewClient(cfg)
if tt.download {
data, err := c.downloadRawBytes(context.Background(), "/target")
if err != nil || string(data) != "file-content" {
t.Fatalf("download=%q err=%v", data, err)
}
} else if err := c.DoRequest(context.Background(), http.MethodGet, "/target", nil, nil); err != nil {
t.Fatal(err)
}
if attempts.Load() != 2 {
t.Fatalf("attempts=%d, want 2", attempts.Load())
}
})
}
}
func TestFeishuCooldownBlocksOtherClientAndHonorsCancellation(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
w.Header().Set("x-ogw-ratelimit-reset", "0.2")
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `{"code":99991400}`)
})
defer ts.Close()
first := NewClient(cfg)
ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancel()
if err := first.DoRequest(ctx, http.MethodGet, "/target", nil, nil); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("wait should be cancellable: %v", err)
}
second := NewClient(cfg)
ctx2, cancel2 := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel2()
if err := second.DoRequest(ctx2, http.MethodGet, "/target", nil, nil); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("other client must inherit cooldown: %v", err)
}
if got := attempts.Load(); got != 1 {
t.Fatalf("cooldown allowed extra requests: %d", got)
}
}
func TestFeishuRateLimitExhaustionProtectsNextDocument(t *testing.T) {
var attempts atomic.Int32
ts, cfg := retryTestServer(t, "/target", func(w http.ResponseWriter, _ *http.Request) {
attempts.Add(1)
w.Header().Set("Retry-After", "0.05")
w.WriteHeader(http.StatusTooManyRequests)
})
defer ts.Close()
c := NewClient(cfg)
if err := c.DoRequest(context.Background(), http.MethodGet, "/target", nil, nil); err == nil {
t.Fatal("persistent rate limit must not report success")
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
err := NewClient(cfg).DoRequest(ctx, http.MethodGet, "/target", nil, nil)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("next document must wait after exhausted retries: %v", err)
}
if got := attempts.Load(); got != 4 {
t.Fatalf("attempts=%d, want bounded 4", got)
}
}
// Gate tests are serial (no t.Parallel): clear before and after each test so
// even a reused httptest port cannot inherit pacing or cooldown state.
func resetFeishuRequestGates(t *testing.T) {
t.Helper()
feishuRequestGates.Clear()
t.Cleanup(feishuRequestGates.Clear)
}
func TestFeishuRequestGateReset(t *testing.T) {
config := &Config{AppID: t.Name(), BaseURL: "http://reused-test-host"}
path := "/open-apis/drive/v1/export_tasks"
old := NewClient(config).requestGate(http.MethodPost, path)
old.cooldown(time.Minute)
t.Run("reset", func(t *testing.T) {
resetFeishuRequestGates(t)
fresh := NewClient(config).requestGate(http.MethodPost, path)
if fresh == old || !fresh.blockedUntil.IsZero() || !fresh.nextRequest.IsZero() {
t.Fatal("reused host/app/API inherited gate state")
}
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if err := fresh.wait(ctx); err != nil {
t.Fatalf("fresh gate still blocked: %v", err)
}
})
key := feishuRequestGateKey{config.BaseURL, config.AppID, "export-create"}
if _, exists := feishuRequestGates.Load(key); exists {
t.Fatal("test cleanup left a gate in the registry")
}
}
func TestFeishuCooldownConfigurationAndBounds(t *testing.T) {
t.Setenv("FEISHU_RATE_LIMIT_MAX_WAIT", "25ms")
t.Setenv("FEISHU_RATE_LIMIT_RETRY_WAIT", "1h")
if got := feishuRateLimitWait(http.Header{}, time.Now()); got != 25*time.Millisecond {
t.Fatalf("fallback escaped cap: %s", got)
}
headers := http.Header{"Retry-After": {"86400"}}
if got := feishuRateLimitWait(headers, time.Now()); got != 25*time.Millisecond {
t.Fatalf("header escaped configured cap: %s", got)
}
headers.Set("Retry-After", time.Now().Add(24*time.Hour).UTC().Format(http.TimeFormat))
if got := feishuRateLimitWait(headers, time.Now()); got != 25*time.Millisecond {
t.Fatalf("HTTP date escaped configured cap: %s", got)
}
gate := &feishuRequestGate{}
gate.cooldown(time.Hour)
// Check the remaining cooldown, excluding any time the test was descheduled
// before cooldown() ran. Scheduler latency must not look like an excessive cap.
if remaining := time.Until(gate.blockedUntil); remaining > 25*time.Millisecond {
t.Fatalf("shared gate escaped cap: %s", remaining)
}
for _, invalid := range []string{"", "0s", "-1s", "bad"} {
t.Setenv("FEISHU_RATE_LIMIT_MAX_WAIT", invalid)
if got := feishuRateLimitWait(headers, time.Now()); got != 5*time.Minute {
t.Fatalf("invalid cap %q: got %s", invalid, got)
}
}
}
func BenchmarkFeishuRateLimitSuccess(b *testing.B) {
body := append([]byte(`{"code":0,"data":"`), bytes.Repeat([]byte("x"), 16<<20)...)
body = append(body, []byte(`"}`)...)
b.SetBytes(int64(len(body)))
b.ResetTimer()
for b.Loop() {
if isFeishuRateLimited(http.StatusOK, body) {
b.Fatal("successful response classified as a rate limit")
}
}
}
func TestFeishuReactiveCooldownsArePerAPI(t *testing.T) {
resetFeishuRequestGates(t)
c := NewClient(&Config{AppID: t.Name(), BaseURL: "http://limits-test"})
pairs := [][2]string{
{"/open-apis/drive/v1/files/one/download", "/open-apis/drive/v1/files/two/download?x=y"},
{"/open-apis/drive/v1/medias/one/download", "/open-apis/drive/v1/medias/two/download"},
{"/open-apis/docx/v1/documents/one/blocks", "/open-apis/docx/v1/documents/two/blocks?page_token=x"},
{"/open-apis/docx/v1/documents/one/raw_content", "/open-apis/docx/v1/documents/two/raw_content"},
{"/open-apis/sheets/v2/spreadsheets/one/values/A1", "/open-apis/sheets/v2/spreadsheets/two/values/B2"},
{"/open-apis/bitable/v1/apps/one/tables/t1/fields", "/open-apis/bitable/v1/apps/two/tables/t2/fields"},
{
"/open-apis/bitable/v1/apps/one/tables/t1/records/search",
"/open-apis/bitable/v1/apps/two/tables/t2/records/search",
},
{"/open-apis/drive/explorer/v2/folder/one/meta", "/open-apis/drive/explorer/v2/folder/two/meta"},
{"/open-apis/wiki/v2/spaces/get_node?token=one", "/open-apis/wiki/v2/spaces/get_node?token=two"},
{"/open-apis/wiki/v2/spaces?page_token=one", "/open-apis/wiki/v2/spaces?page_token=two"},
}
seen := make(map[*feishuRequestGate]bool)
for _, pair := range pairs {
gate := c.requestGate(http.MethodGet, pair[0])
if gate != c.requestGate(http.MethodGet, pair[1]) || gate.interval != 0 {
t.Fatalf("reactive gate must normalize tokens and query: %v", pair)
}
if seen[gate] {
t.Fatalf("unrelated APIs share a cooldown: %v", pair)
}
seen[gate] = true
if gate == c.requestGate(http.MethodPost, pair[0]) {
t.Fatalf("HTTP methods share a cooldown: %v", pair)
}
}
media := c.requestGate(http.MethodGet, pairs[1][0])
media.cooldown(time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
if err := c.requestGate(http.MethodGet, pairs[2][0]).wait(ctx); err != nil {
t.Fatalf("media cooldown blocked docx: %v", err)
}
if err := media.wait(ctx); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("media did not retain its own cooldown: %v", err)
}
}
func TestFeishuRateLimitDetection(t *testing.T) {
for _, tt := range []struct {
status int
body string
want bool
}{
{http.StatusOK, `{"code":0,"data":{"text":"99991400"}}`, false},
{http.StatusOK, `{"code":99991400}`, true},
{http.StatusBadRequest, `{"code":99991400}`, true},
{http.StatusOK, `{"code":0}`, false},
{http.StatusOK, `invalid 99991400`, false},
{http.StatusForbidden, `{"code":99991400}`, false},
{http.StatusTooManyRequests, ``, true},
} {
if got := isFeishuRateLimited(tt.status, []byte(tt.body)); got != tt.want {
t.Errorf("rate limited(%d, %s) = %v, want %v", tt.status, tt.body, got, tt.want)
}
}
}
// Run HTTP handlers in process so synctest can advance time without real sockets.
type feishuHandlerTransport struct {
http.Handler
}
func (tr feishuHandlerTransport) RoundTrip(r *http.Request) (*http.Response, error) {
recorder := httptest.NewRecorder()
tr.ServeHTTP(recorder, r)
return recorder.Result(), nil
}
func TestFeishuExportPollingRetainsTicketAcrossCooldown(t *testing.T) {
t.Setenv("FEISHU_API_REQUESTS_PER_MINUTE", "80")
t.Setenv("FEISHU_RATE_LIMIT_RETRY_WAIT", "70s")
t.Setenv("FEISHU_RATE_LIMIT_MAX_WAIT", "5m")
t.Setenv("FEISHU_EXPORT_MAX_POLLS", "2")
t.Setenv("FEISHU_EXPORT_POLL_INTERVAL", "2s")
synctest.Test(t, func(t *testing.T) {
resetFeishuRequestGates(t)
var creates, polls, downloads int
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/drive/v1/export_tasks", func(w http.ResponseWriter, _ *http.Request) {
creates++
_, _ = io.WriteString(w, `{"code":0,"data":{"ticket":"same-ticket"}}`)
})
mux.HandleFunc("/open-apis/drive/v1/export_tasks/same-ticket", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("token") != "document" {
t.Error("poll did not retain the document token")
}
polls++
switch polls {
case 1:
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `{"code":99991400}`)
case 2:
_, _ = io.WriteString(w, `{"code":0,"data":{"result":{"job_status":2}}}`)
default:
_, _ = io.WriteString(w,
`{"code":0,"data":{"result":{"job_status":0,"file_token":"file","file_name":"doc.pdf"}}}`)
}
})
mux.HandleFunc("/open-apis/drive/v1/export_tasks/file/file/download",
func(w http.ResponseWriter, _ *http.Request) {
downloads++
_, _ = io.WriteString(w, "export-content")
})
cfg := &Config{AppID: t.Name(), BaseURL: "http://feishu-export.test"}
c := NewClient(cfg)
c.httpClient.Transport = feishuHandlerTransport{mux}
c.tokenCache, c.tokenExpAt = "cached-token", time.Now().Add(time.Hour)
// Both shared and in-poll cooldowns exceed the previous 60-second deadline.
started := time.Now()
other := NewClient(cfg)
other.requestGate(http.MethodGet, "/open-apis/drive/v1/export_tasks/other-ticket").cooldown(70 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
data, name, err := c.ExportAndDownload(ctx, "document", "docx")
if err != nil || name != "doc.pdf" || string(data) != "export-content" {
t.Fatalf("export across cooldown: data=%q name=%q err=%v", data, name, err)
}
if creates != 1 || polls != 3 || downloads != 1 {
t.Fatalf("create/poll/download=%d/%d/%d, want 1/3/1", creates, polls, downloads)
}
if elapsed := time.Since(started); elapsed < 140*time.Second {
t.Fatalf("export skipped the shared or in-poll cooldown: %s", elapsed)
}
})
}
func TestFeishuExportPollingIsBoundedAndCancellable(t *testing.T) {
for _, cancelWhileWaiting := range []bool{false, true} {
t.Run(fmt.Sprint(cancelWhileWaiting), func(t *testing.T) {
t.Setenv("FEISHU_EXPORT_MAX_POLLS", "3")
t.Setenv("FEISHU_EXPORT_POLL_INTERVAL", "1ms")
t.Setenv("FEISHU_API_REQUESTS_PER_MINUTE", "60000")
var creates, polls atomic.Int32
createHandler := func(w http.ResponseWriter, _ *http.Request) {
creates.Add(1)
_, _ = io.WriteString(w, `{"code":0,"data":{"ticket":"pending"}}`)
}
ts, cfg := retryTestServer(t, "/open-apis/drive/v1/export_tasks", createHandler)
defer ts.Close()
ts.Config.Handler.(*http.ServeMux).HandleFunc("/open-apis/drive/v1/export_tasks/pending",
func(w http.ResponseWriter, _ *http.Request) {
polls.Add(1)
_, _ = io.WriteString(w, `{"code":0,"data":{"result":{"job_status":2}}}`)
})
c := NewClient(cfg)
if cancelWhileWaiting {
c.requestGate(http.MethodGet, "/open-apis/drive/v1/export_tasks/pending").cooldown(time.Second)
}
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
_, _, err := c.ExportAndDownload(ctx, "document", "docx")
if cancelWhileWaiting {
if !errors.Is(err, context.DeadlineExceeded) || polls.Load() != 0 {
t.Fatalf("polling ignored cancellation: polls=%d err=%v", polls.Load(), err)
}
} else if err == nil || !strings.Contains(err.Error(), "after 3 polls") || polls.Load() != 3 {
t.Fatalf("polling is unbounded: polls=%d err=%v", polls.Load(), err)
}
// Exercise the same wrapping and metadata path used by the connectors.
metadata := FeishuErrorItemMeta(fmt.Errorf("export document: %w", err), nil)
if metadata["error_reason_code"] != "feishu_timeout" {
t.Fatalf("polling lost its timeout classification: %v", metadata)
}
if strings.Contains(metadata["error_reason"], "ticket=") {
t.Fatal("export ticket leaked into the user-facing failure reason")
}
if creates.Load() != 1 {
t.Fatalf("created %d tasks, want 1", creates.Load())
}
})
}
}
func TestFeishuRefreshesTokenAfterCooldown(t *testing.T) {
for _, download := range []bool{false, true} {
t.Run(fmt.Sprint(download), func(t *testing.T) {
resetFeishuRequestGates(t)
var auths, attempts atomic.Int32
var c *Client
mux := http.NewServeMux()
authHandler := func(w http.ResponseWriter, _ *http.Request) {
token := fmt.Sprintf("token-%d", auths.Add(1))
writeJSON(w, TokenResponse{TenantAccessToken: token, Expire: 7200})
}
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", authHandler)
mux.HandleFunc("/target", func(w http.ResponseWriter, r *http.Request) {
if attempts.Add(1) == 1 {
c.tokenMu.Lock()
c.tokenExpAt = time.Now().Add(5 * time.Millisecond)
c.tokenMu.Unlock()
w.Header().Set("Retry-After", "0.03")
w.WriteHeader(http.StatusTooManyRequests)
return
}
if r.Header.Get("Authorization") != "Bearer token-2" {
t.Error("request reused the token that expired during cooldown")
}
_, _ = io.WriteString(w, `{"code":0}`)
})
ts := httptest.NewServer(mux)
defer ts.Close()
c = NewClient(&Config{AppID: t.Name(), BaseURL: ts.URL})
var err error
if download {
_, err = c.downloadRawBytes(context.Background(), "/target")
} else {
err = c.DoRequest(context.Background(), http.MethodGet, "/target", nil, nil)
}
if err != nil || auths.Load() != 2 || attempts.Load() != 2 {
t.Fatalf("auth/attempts=%d/%d err=%v", auths.Load(), attempts.Load(), err)
}
})
}
}
func TestFeishuGateGrantsInArrivalOrder(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
gate := &feishuRequestGate{interval: time.Second}
start := time.Now()
var mu sync.Mutex
var order []int
var grants []time.Duration
var wg sync.WaitGroup
for i := range 5 {
wg.Add(1)
go func() {
defer wg.Done()
if err := gate.wait(context.Background()); err != nil {
t.Error(err)
return
}
mu.Lock()
order = append(order, i)
grants = append(grants, time.Since(start))
mu.Unlock()
}()
synctest.Wait()
}
wg.Wait()
for i := range 5 {
if order[i] != i || grants[i] != time.Duration(i)*time.Second {
t.Fatalf("grants out of arrival order or pace: order=%v grants=%v", order, grants)
}
}
})
}
@@ -0,0 +1,121 @@
package core
import (
"context"
"io"
"net/http"
"net/http/httptest"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
)
// Cached-token requests first check Err when entering gate.wait. Observe that
// boundary so the test expires the token only after every caller authenticated.
type feishuGateWaitContext struct {
context.Context
once sync.Once
entered chan<- struct{}
}
func (c *feishuGateWaitContext) Err() error {
c.once.Do(func() { c.entered <- struct{}{} })
return c.Context.Err()
}
func TestFeishuTokenRefreshPreservesPacingAndCooldown(t *testing.T) {
for _, mode := range []string{"json", "download"} {
t.Run(mode, func(t *testing.T) {
resetFeishuRequestGates(t)
t.Setenv("FEISHU_API_REQUESTS_PER_MINUTE", "600")
t.Setenv("FEISHU_RATE_LIMIT_MAX_WAIT", "5m")
const count = 4
const interval = 100 * time.Millisecond
var mu sync.Mutex
var arrivals []time.Time
var earliestRequest time.Time
var auths atomic.Int32
var gate *feishuRequestGate
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" {
auths.Add(1)
// Slow enough for every caller to pass the gate in the broken
// implementation and queue behind the refreshing caller's tokenMu.
time.Sleep(time.Duration(count+1) * interval)
mu.Lock()
earliestRequest = time.Now().Add(3 * interval)
mu.Unlock()
// A concurrent data source can extend this shared cooldown while
// our token is refreshing. All callers must honor the new delay.
gate.cooldown(3 * interval)
writeJSON(w, TokenResponse{TenantAccessToken: "fresh-token", Expire: 7200})
return
}
if r.Header.Get("Authorization") != "Bearer fresh-token" {
t.Error("request sent the token that expired while waiting")
}
mu.Lock()
arrivals = append(arrivals, time.Now())
mu.Unlock()
_, _ = io.WriteString(w, `{"code":0}`)
}))
defer server.Close()
c := NewClient(&Config{AppID: t.Name(), BaseURL: server.URL})
c.tokenCache = "cached-token"
c.tokenExpAt = time.Now().Add(time.Hour)
method, path := http.MethodPost, "/open-apis/drive/v1/export_tasks"
if mode == "download" {
method, path = http.MethodGet, "/open-apis/drive/v1/export_tasks/file/export-token/download"
}
gate = c.requestGate(method, path)
gate.cooldown(500 * time.Millisecond)
entered := make(chan struct{}, count)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var wg sync.WaitGroup
for range count {
wg.Add(1)
go func() {
defer wg.Done()
observed := &feishuGateWaitContext{Context: ctx, entered: entered}
var err error
if mode == "download" {
_, err = c.downloadRawBytes(observed, path)
} else {
err = c.DoRequest(observed, method, path, nil, nil)
}
if err != nil {
t.Errorf("request: %v", err)
}
}()
}
for range count {
select {
case <-entered:
case <-ctx.Done():
t.Fatal("requests failed to reach the gate")
}
}
c.tokenMu.Lock()
c.tokenExpAt = time.Now().Add(-time.Second)
c.tokenMu.Unlock()
wg.Wait()
mu.Lock()
defer mu.Unlock()
if len(arrivals) != count || auths.Load() != 1 {
t.Fatalf("requests/refreshes=%d/%d, want %d/1", len(arrivals), auths.Load(), count)
}
sort.Slice(arrivals, func(i, j int) bool { return arrivals[i].Before(arrivals[j]) })
if arrivals[0].Before(earliestRequest) {
t.Errorf("request ignored the cooldown imposed during token refresh")
}
for i := 1; i < len(arrivals); i++ {
if gap := arrivals[i].Sub(arrivals[i-1]); gap < interval/2 {
t.Errorf("requests burst after token refresh: gap=%s, interval=%s", gap, interval)
}
}
})
}
}
@@ -0,0 +1,720 @@
package core
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"academy/internal/datasource"
"academy/internal/logger"
"academy/internal/types"
)
const FeishuWikiNodeResourceSeparator = ":"
// shared.go holds the helpers used by BOTH the wiki Connector (connector.go)
// and the Drive DriveConnector (connector.go): error classification,
// config parsing, stream-Checkpoint tuning, the fetch tally, filename/time
// utilities, attachment rules, and the docx blocks fetch path. Anything that
// is specific to one connector stays in that connector's own file.
// FeishuStreamCheckpointInterval is how many processed nodes pass between
// cursor checkpoints during a streaming fetch. Small enough that a timed-out
// sync loses little work on resume, large enough that Checkpoint persistence
// (a DB write) does not dominate. Overridable in tests. See FetchStream.
var FeishuStreamCheckpointInterval = 50
// FeishuStreamCheckpointMaxInterval bounds checkpointing by wall-clock time as
// well as node count. Without it, a sync of fewer than
// FeishuStreamCheckpointInterval very slow (rate-limited) exports could reach
// the 2h task timeout having never checkpointed, and resume from scratch every
// retry — the #2136 "never fully syncs" case. Overridable in tests.
var FeishuStreamCheckpointMaxInterval = 30 * time.Second
// fetchTally accumulates the outcome of fetching a wiki node subtree so the
// connector can Emit a single actionable summary. Without it, unsupported nodes
// (mindnote/slides/etc.) vanish with no item, no error and no log, leaving users
// unable to explain why "13 documents synced only 3" (Tencent/WeKnora#2136).
type fetchTally struct {
discovered int
fetched int
failed int
skippedByType map[string]int
}
func newFetchTally(discovered int) *fetchTally {
return &fetchTally{discovered: discovered, skippedByType: map[string]int{}}
}
func (t *fetchTally) fetch() { t.fetched++ }
func (t *fetchTally) fail() { t.failed++ }
func (t *fetchTally) Skip(objType string) { t.skippedByType[objType]++ }
func (t *fetchTally) skipped() int {
n := 0
for _, c := range t.skippedByType {
n += c
}
return n
}
func (t *fetchTally) summary() string {
return fmt.Sprintf("discovered=%d fetched=%d failed=%d skipped_unsupported=%d by_type=%v",
t.discovered, t.fetched, t.failed, t.skipped(), t.skippedByType)
}
var reFeishuErrorCode = regexp.MustCompile(`code["\s]*[:=]\s*(\d+)`)
// feishuErrorCode extracts the numeric Feishu error code from a raw error string
// (e.g. `body={"code":1663,...}` or `code=1663`), best-effort.
func feishuErrorCode(raw string) string {
if m := reFeishuErrorCode.FindStringSubmatch(raw); len(m) == 2 {
return m[1]
}
return ""
}
// feishuFailure classifies a raw connector/API error into a stable i18n code
// (mapped to a localized string on the frontend), an optional numeric Feishu
// error code for interpolation, and an English fallback message for clients
// without the i18n key. The raw status/JSON body/log_id is never returned here —
// it stays in the server logs. Dumping it in the UI is the anti-pattern
// Airbyte/Fivetran/Onyx warn against. Transient errors are retried next sync
// (the cursor is retained); auth/permission errors point at the fix instead.
func feishuFailure(err error) (code, codeValue, fallback string) {
if err == nil {
return "sync_failed", "", "Sync failed; will retry on the next sync"
}
s := strings.ToLower(err.Error())
switch {
case strings.Contains(s, "auth error"),
strings.Contains(s, "invalid access token"),
strings.Contains(s, "permission"),
strings.Contains(s, "forbidden"),
strings.Contains(s, "status=403"):
return "feishu_auth_or_permission", "", "Authentication or permission error; check credentials and app scopes"
case strings.Contains(s, "rate limited"), strings.Contains(s, "status=429"):
return "feishu_rate_limited", "", "Feishu API rate limited; will retry on the next sync"
case errors.Is(err, errExportPollsExhausted),
strings.Contains(s, "timed out"),
strings.Contains(s, "timeout"),
strings.Contains(s, "deadline exceeded"):
return "feishu_timeout", "", "Export or request timed out; will retry on the next sync"
case strings.Contains(s, "server error"):
return "feishu_server_unavailable", "", "Feishu service temporarily unavailable; will retry on the next sync"
case strings.Contains(s, "api error"),
strings.Contains(s, "export task failed"),
strings.Contains(s, "download failed"):
if v := feishuErrorCode(err.Error()); v != "" {
return "feishu_api_error", v, fmt.Sprintf("Feishu API error (code=%s); will retry on the next sync", v)
}
return "feishu_api_error_generic", "", "Feishu API error; will retry on the next sync"
default:
return "sync_failed", "", "Sync failed; will retry on the next sync"
}
}
// FeishuErrorItemMeta builds the metadata for a failed item: the raw error (for
// server logs) plus the classified i18n code / param / fallback (for a
// localisable SyncItemError in the UI), merged with any caller-supplied extras.
func FeishuErrorItemMeta(err error, extra map[string]string) map[string]string {
code, codeValue, fallback := feishuFailure(err)
m := map[string]string{
"error": err.Error(),
"error_reason_code": code,
"error_reason": fallback,
}
if codeValue != "" {
m["error_reason_code_value"] = codeValue
}
maps.Copy(m, extra)
return m
}
// parseableAttachmentExts are attachment extensions worth ingesting as their
// own knowledge entries. This is the shared contract list (pdf/md/markdown/
// xlsx/xls/csv/doc/docx/ppt/pptx); everything else — images (which ride the
// embedded-image pipeline instead), videos, archives — degrades to an inline
// Markdown reference. markdown.go's attachment rendering reads this same map,
// so the inline `- 文件名` list and the produced sub-items can never disagree.
var parseableAttachmentExts = map[string]bool{
".pdf": true, ".md": true, ".markdown": true,
".xlsx": true, ".xls": true, ".csv": true,
".doc": true, ".docx": true, ".ppt": true, ".pptx": true,
}
// MinAttachmentBytes filters out decorative micro-files.
const MinAttachmentBytes = 2 * 1024
// maxInlineImageBytes caps a single image inlined as a base64 data URI. It
// mirrors the document-processing image resolver's per-image budget
// (docparser maxRemoteImageSize): anything larger would be downloaded,
// base64-expanded ~1.37x into the markdown, then silently skipped by the
// resolver — a permanent raw-base64 blob in stored content.
const maxInlineImageBytes = 10 * 1024 * 1024
// SupportedImageExt sniffs image bytes and returns the filename extension and
// content type Academy 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:
// Go's sniffer reports SVG markup as text/xml; recover the real type
// when the payload is an <svg> document (board download_as_image may
// return SVG), and the platform resolver stores .svg natively.
if strings.HasPrefix(ct, "text/xml") && bytes.Contains(data[:min(len(data), 512)], []byte("<svg")) {
return ".svg", "image/svg+xml", true
}
return "", ct, false
}
}
// ParseFeishuConfig extracts and validates Feishu/Lark-specific configuration.
//
// base_url stays an explicit override so existing data sources that pointed a
// "feishu" connector at open.larksuite.com keep working; when it is unset the
// region's own host is filled in, making the resolved Config.BaseURL concrete
// for everything downstream.
func ParseFeishuConfig(config *types.DataSourceConfig, region Region) (*Config, error) {
if config == nil {
return nil, fmt.Errorf("config is nil")
}
credBytes, err := json.Marshal(config.Credentials)
if err != nil {
return nil, fmt.Errorf("marshal credentials: %w", err)
}
var feishuConfig Config
if err := json.Unmarshal(credBytes, &feishuConfig); err != nil {
return nil, fmt.Errorf("parse %s credentials: %w", region.ConnectorType, err)
}
if feishuConfig.AppID == "" || feishuConfig.AppSecret == "" {
return nil, fmt.Errorf("%s app_id and app_secret are required", region.ConnectorType)
}
if feishuConfig.BaseURL == "" {
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)
}
}
// parse_mode is likewise a per-data-source display setting, read from
// Settings (set on the data source edit form). When the per-source setting
// is unset, the deprecated FEISHU_DOCX_PARSE_MODE env var is still honored
// for one release (with a warning) so deployments that pinned "export"
// keep their behavior across the upgrade. Everything unset (or
// unrecognized) resolves to blocks — the default; an unrecognized value
// falls back to blocks with a warning rather than failing the whole sync.
parseMode := ""
if config.Settings != nil {
if pm, ok := config.Settings["parse_mode"].(string); ok {
parseMode = strings.ToLower(strings.TrimSpace(pm))
}
}
if parseMode == "" {
if legacy := strings.TrimSpace(os.Getenv("FEISHU_DOCX_PARSE_MODE")); legacy != "" {
logger.Warnf(context.Background(),
"[Feishu] FEISHU_DOCX_PARSE_MODE=%q is deprecated and will be removed; "+
"set parse_mode on the data source edit form instead",
legacy)
parseMode = strings.ToLower(legacy)
}
}
switch parseMode {
case "", ParseModeBlocks:
feishuConfig.ParseMode = ParseModeBlocks
case ParseModeExport:
// keep the explicit export selection
feishuConfig.ParseMode = ParseModeExport
default:
logger.Warnf(context.Background(),
"[Feishu] invalid parse_mode %q, falling back to %q",
parseMode, ParseModeBlocks)
feishuConfig.ParseMode = ParseModeBlocks
}
if err := datasource.ValidateConnectorBaseURL(feishuConfig.GetBaseURL()); err != nil {
return nil, err
}
return &feishuConfig, nil
}
// DocxChangeKey invalidates cached docx content when its effective parser changes.
// Other file types do not depend on the docx parser setting.
func DocxChangeKey(editTime, objType, parseMode string) string {
if objType != "docx" {
return editTime
}
if parseMode == "" {
parseMode = ParseModeBlocks
}
return editTime + ":parse=" + parseMode
}
// IsSupportedDocType checks if a Feishu document type can be synced.
// mindnote and slides have no content read API and are skipped.
func IsSupportedDocType(objType string) bool {
switch objType {
case "docx", "doc", "sheet", "bitable", "file":
return true
default:
// mindnote, slides — no content retrieval API available
return false
}
}
// ParseFeishuTimestamp parses a Feishu unix timestamp string (seconds) into time.Time.
func ParseFeishuTimestamp(ts string) time.Time {
if ts == "" {
return time.Time{}
}
sec, err := strconv.ParseInt(ts, 10, 64)
if err != nil {
return time.Time{}
}
return time.Unix(sec, 0)
}
// SanitizeFileName removes characters that are invalid in filenames and
// 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"
}
replacer := strings.NewReplacer(
"/", "_", "\\", "_", ":", "_", "*", "_",
"?", "_", "\"", "_", "<", "_", ">", "_", "|", "_",
)
result := replacer.Replace(name)
const maxBytes = 200
if len(result) <= maxBytes {
return result
}
ext := filepath.Ext(result)
if len(ext) >= maxBytes {
// pathological: extension alone overflows the budget → drop it
ext = ""
}
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
}
// userNameResolver returns a per-document @mention display-name resolver for
// the contact API. The cache (OpenID → name) means each user costs at most one
// contact call per document; failures and empty names negative-cache too, so a
// user without contact permission renders every later mention of themselves as
// the generic @成员 without re-hitting the API. Errors never propagate — they
// only log at debug level; ingestion is never blocked or failed by this.
func userNameResolver(ctx context.Context, client *Client) func(string) string {
var cache sync.Map // OpenID → display name ("" = lookup failed)
return func(userID string) string {
if userID == "" {
return ""
}
if v, ok := cache.Load(userID); ok {
return v.(string)
}
name, err := client.UserName(ctx, userID)
if err != nil {
logger.Debugf(ctx, "[Feishu] resolve mention user %s: %v (degrading to @成员)", userID, err)
name = ""
}
cache.Store(userID, name)
return name
}
}
// DocxFetchInput is the unified description of one docx document from either
// source (wiki node or Drive file) that FetchDocxWithBlocks needs.
type DocxFetchInput struct {
// Academy external_id: wiki=node.NodeToken, drive=file.Token
DocToken string
// Feishu docx document token
ObjToken string
Title string
URL string
ResourceID string
EditTime time.Time
// CreateTime is the document creation time in Feishu; zero when unknown.
CreateTime time.Time
BaseMeta map[string]string
// ParseMode selects the docx parsing path ("blocks" | "export"), resolved
// from Settings["parse_mode"] by ParseFeishuConfig and threaded from the
// connector entry points. Empty means blocks (the default).
ParseMode string
}
// FetchDocxWithBlocks retrieves a docx document via the blocks API, converts
// it to Markdown, and returns the main item with attachment sub-items. Image
// and board blocks render as nonce-tagged markers that this function patches
// in place with inline base64 data URIs (placeholders on failure); the
// document-processing image resolver stores them later. Falls back to the
// export API if the blocks API errors or renders empty. Shared by the wiki
// Connector and the Drive DriveConnector.
func FetchDocxWithBlocks(ctx context.Context, client *Client, in DocxFetchInput) ([]*types.FetchedItem, error) {
// The parse mode comes from the data source's Settings["parse_mode"],
// resolved by ParseFeishuConfig and threaded in via DocxFetchInput.ParseMode.
// The blocks path (default) inlines images/boards into the parent
// Markdown as base64 data URIs (via academy-img://N markers) and fans
// attachments out into sub-items wired to the parent via attachment_ids
// metadata. The export path yields a .docx that docreader
// parses inline, so images are bound to the parent document via
// parent_chunk_id (same as a regular docx upload) — kept as the per-data-
// source escape hatch.
parsingMode := in.ParseMode
if parsingMode == "" {
parsingMode = ParseModeBlocks
}
if strings.EqualFold(parsingMode, ParseModeExport) {
item, err := exportDocxFallback(ctx, client, in)
if err != nil {
return nil, err
}
return []*types.FetchedItem{item}, nil
}
blocks, err := client.listDocumentBlocks(ctx, in.ObjToken)
if err != nil {
logger.Warnf(ctx, "[Feishu] blocks API failed for %s (%s), falling back to export: %v",
in.Title, in.ObjToken, err)
item, ferr := exportDocxFallback(ctx, client, in)
if ferr != nil {
return nil, ferr
}
// Do NOT set ReplacesSubtree here (see the wiki history: a transient
// blocks failure must not sweep good attachment children from the prior
// blocks-path sync with nothing to replace them).
return []*types.FetchedItem{item}, nil
}
// Images/boards ride the marker pipeline: the renderer numbers them in
// document order, and the patches below inline each image's bytes as a
// base64 data URI (or a plain placeholder on failure) in a single pass.
mdBytes, atts, imgs, docNames, err := blocksToMarkdown(ctx, client, blocks, in.URL, userNameResolver(ctx, client))
if err != nil {
return nil, fmt.Errorf("convert blocks %s: %w", in.Title, err)
}
md := string(mdBytes)
// Export image-heavy documents before downloading any media or attachments.
// The native document parser carries images as ImageRefs, which do not use
// the Markdown data-URI count budget. Never silently leave excess base64
// in persisted Markdown, and do not raise the shared parser's resource cap.
var exported *types.FetchedItem
if len(imgs) > types.MaxInlineDocumentImages {
logger.Infof(ctx, "[Feishu] doc %s has %d images; falling back to export", in.ObjToken, len(imgs))
item, ferr := exportDocxFallback(ctx, client, in)
if ferr != nil {
return nil, ferr
}
exported = item
}
if len(strings.TrimSpace(md)) == 0 {
logger.Infof(ctx, "[Feishu] doc %s (%s): blocks rendered empty Markdown, falling back to export",
in.Title, in.ObjToken)
item, ferr := exportDocxFallback(ctx, client, in)
if ferr != nil {
return nil, ferr
}
return []*types.FetchedItem{item}, nil
}
// Attachments stay sub-items (they are documents in their own right and
// are emitted BEFORE the parent so SubtreeKeep/sweep semantics hold).
var children []*types.FetchedItem
keep := make([]string, 0, len(atts))
attachmentIDs := make([]string, 0, len(atts))
childMeta := func() map[string]string {
m := maps.Clone(in.BaseMeta)
m["parent_node_token"] = in.DocToken
m["parent_doc_id"] = in.DocToken
m["attachment"] = "true"
return m
}
// patchMarker swaps one numbered image marker in the rendered Markdown for
// its final form: an inline base64 data URI on success, a plain
// ![图片]() placeholder or a degrade note on failure. Markers are unique
// per N, and N is assigned once per image/board block.
patchMarker := func(n int, replacement string) {
needle := fmt.Sprintf("![图片](academy-img://%d-%s)", n, imageMarkerNonce(in.URL))
md = strings.Replace(md, needle, replacement, 1)
}
// ── file attachments ──
for _, a := range atts {
childID := types.SubtreeChildID(in.DocToken, "file", a.FileToken)
keep = append(keep, childID) // present in the doc → never sweep as stale
// The renderer emitted the unique line "- academy-att://<token>" for
// this attachment; patch that exact line so an identical earlier
// bullet can never be replaced by mistake. Anchoring on the token's
// end (newline or end of markdown) keeps a token that is a strict
// prefix of another attachment's token from matching inside it.
patchAtt := func(line string) {
needle := "- academy-att://" + a.FileToken
if anchored := needle + "\n"; strings.Contains(md, anchored) {
md = strings.Replace(md, anchored, line+"\n", 1)
return
}
if strings.HasSuffix(md, needle) {
md = md[:len(md)-len(needle)] + line
}
}
// The renderer only collects whitelisted extensions into atts, so
// non-whitelisted/video files never reach this loop (their inline
// `> [附件: …]` reference is already in the Markdown).
data, derr := client.downloadMediaFile(ctx, a.FileToken)
if derr != nil {
if errors.Is(derr, ErrDownloadTooLarge) {
// The file is fine, just over the sync cap: degrade inline
// instead of failing or error-iteming the document.
logger.Warnf(ctx,
"[Feishu] doc %s: attachment %q (token=%s) over download cap, degrading to placeholder",
in.ObjToken, a.Name, a.FileToken)
displayName := a.Name
if displayName == "" {
displayName = a.FileToken
}
note := "> [附件: " + displayName + "]"
if in.URL != "" {
note = "> [附件: " + displayName + "](" + escapeURL(in.URL) + ")"
}
patchAtt(note)
continue
}
logger.Warnf(ctx, "[Feishu] doc %s: attachment %q (token=%s) download failed: %v",
in.ObjToken, a.Name, a.FileToken, derr)
patchAtt("- " + a.Name)
children = append(children, &types.FetchedItem{
ExternalID: childID,
Title: a.Name,
SourceResourceID: in.ResourceID,
Metadata: FeishuErrorItemMeta(derr, childMeta()),
})
continue
}
if len(data) < MinAttachmentBytes {
logger.Infof(ctx, "[Feishu] doc %s: skipping tiny attachment %q (token=%s, %d bytes < %d)",
in.ObjToken, a.Name, a.FileToken, len(data), MinAttachmentBytes)
patchAtt("- " + a.Name)
continue
}
patchAtt("- " + a.Name)
children = append(children, &types.FetchedItem{
ExternalID: childID,
Title: a.Name,
Content: data,
ContentType: "application/octet-stream",
FileName: SanitizeFileName(a.Name),
URL: in.URL,
UpdatedAt: in.EditTime,
CreatedAt: in.CreateTime,
SourceResourceID: in.ResourceID,
Metadata: childMeta(),
})
attachmentIDs = append(attachmentIDs, childID)
}
if exported != nil {
// A successful blocks listing still provides authoritative attachments.
// Preserve those children even though the parent's images use native
// export parsing; ordinary export alone omits file block attachments.
exported.ReplacesSubtree = true
exported.SubtreeKeep = keep
if len(attachmentIDs) > 0 {
if exported.Metadata == nil {
exported.Metadata = make(map[string]string)
}
ids, _ := json.Marshal(attachmentIDs)
exported.Metadata["attachment_ids"] = string(ids)
}
return append(children, exported), nil
}
// ── 云文档 mention links: backfill document titles ──
// The renderer emits "[academy-docname://<token>](<url>)" placeholders; the
// drive metadata batch API resolves every title in one call. Refs that
// cannot be resolved (no permission, deleted, unsupported type) keep the
// URL as the link text — exactly the form rendered before this backfill.
if len(docNames) > 0 {
titles := client.DocTitles(ctx, docNames)
for _, dn := range docNames {
needle := "[academy-docname://" + dn.Token + "](" + escapeURL(dn.URL) + ")"
repl := "[" + dn.URL + "](" + escapeURL(dn.URL) + ")"
if title := titles[dn.Token]; title != "" {
clean := strings.NewReplacer("[", "[", "]", "]", "\n", " ", "\r", "").Replace(title)
repl = "[" + clean + "](" + escapeURL(dn.URL) + ")"
} else {
logger.Warnf(ctx, "[Feishu] doc %s: no metadata for referenced doc %s (%s), keeping URL as link text",
in.Title, dn.Token, dn.DocType)
}
md = strings.ReplaceAll(md, needle, repl)
}
}
// ── embedded images and whiteboard blocks (block_type 43) ──
// Orthodox platform flow (same as the docparser for parsed PDFs/Word):
// the image bytes ride INSIDE the parent markdown as a base64 data URI;
// the document-processing pipeline's image resolver stores them on the
// tenant file service, swaps in the persistent provider:// URL and (when
// a VLM is configured) produces OCR/caption child chunks. No image
// knowledge rows are created.
for _, pi := range imgs {
if pi.Token == "" {
// Malformed block: degrade the marker to a plain placeholder.
patchMarker(pi.N, "![图片]()")
continue
}
var (
data []byte
derr error
)
if pi.Kind == "board" {
data, derr = client.downloadBoardAsImage(ctx, pi.Token)
} else {
data, derr = client.downloadMediaFile(ctx, pi.Token)
}
if derr != nil {
// 403 (no board:whiteboard:node:read for boards) or transient
// failure: degrade inline, never fail the document.
logger.Warnf(ctx, "[Feishu] doc %s: %s %s download failed: %v",
in.ObjToken, pi.Kind, pi.Token, derr)
patchMarker(pi.N, "![图片]()")
continue
}
ext, contentType, ok := SupportedImageExt(data)
if !ok {
// Reject non-images here. The image resolver filters icons by
// dimensions; compressed diagrams can be well below 2 KB.
logger.Infof(ctx, "[Feishu] doc %s: %s %s not a usable image (type=%q bytes=%d)",
in.ObjToken, pi.Kind, pi.Token, contentType, len(data))
patchMarker(pi.N, "![图片]()")
continue
}
if len(data) > maxInlineImageBytes {
// The document-processing image resolver skips data URIs over its
// 10 MB budget (image_resolver maxRemoteImageSize); inlining one
// would leave a raw base64 blob in the stored markdown forever.
// Degrade here instead — same handling as an oversized attachment.
logger.Warnf(ctx, "[Feishu] doc %s: %s %s (%d bytes) over inline image cap, degrading to placeholder",
in.ObjToken, pi.Kind, pi.Token, len(data))
patchMarker(pi.N, "![图片]()")
continue
}
dataURI := "data:" + contentType + ";base64," + base64.StdEncoding.EncodeToString(data)
patchMarker(pi.N, "![图片]("+dataURI+")")
_ = ext // ext is implied by contentType in the data URI
}
meta := maps.Clone(in.BaseMeta)
if len(attachmentIDs) > 0 {
if b, merr := json.Marshal(attachmentIDs); merr == nil {
meta["attachment_ids"] = string(b)
}
}
main := &types.FetchedItem{
ExternalID: in.DocToken,
Title: in.Title,
Content: []byte(md),
ContentType: "text/markdown",
FileName: SanitizeFileName(in.Title) + ".md",
URL: in.URL,
UpdatedAt: in.EditTime,
CreatedAt: in.CreateTime,
SourceResourceID: in.ResourceID,
Metadata: meta,
ReplacesSubtree: true, // sweep stale attachment sub-items on re-sync
}
main.SubtreeKeep = keep
return append(children, main), nil
}
// exportDocxFallback exports a docx document via the async export API and
// returns a single FetchedItem containing the exported .docx binary. Used by
// FetchDocxWithBlocks when the blocks API is unavailable or renders empty.
func exportDocxFallback(ctx context.Context, client *Client, in DocxFetchInput) (*types.FetchedItem, error) {
data, fileName, err := client.ExportAndDownload(ctx, in.ObjToken, "docx")
if err != nil {
return nil, fmt.Errorf("export %s (docx): %w", in.Title, err)
}
ext := ExportFileExtToSuffix[ObjTypeToExportFileExtension["docx"]]
if fileName == "" {
fileName = SanitizeFileName(in.Title) + ext
} else if !strings.HasSuffix(strings.ToLower(fileName), ext) {
fileName = SanitizeFileName(fileName) + ext
}
return &types.FetchedItem{
ExternalID: in.DocToken,
Title: in.Title,
Content: data,
ContentType: "application/octet-stream",
FileName: fileName,
URL: in.URL,
UpdatedAt: in.EditTime,
CreatedAt: in.CreateTime,
SourceResourceID: in.ResourceID,
Metadata: in.BaseMeta,
}, nil
}
@@ -0,0 +1,45 @@
package core
import (
"strings"
"testing"
)
func TestFetchTally_CountsAndSummary(t *testing.T) {
tally := newFetchTally(13)
tally.fetch()
tally.fetch()
tally.fetch()
tally.Skip("mindnote")
tally.Skip("mindnote")
tally.Skip("slides")
tally.fail()
if got := tally.skipped(); got != 3 {
t.Errorf("skipped() = %d, want 3", got)
}
summary := tally.summary()
for _, want := range []string{
"discovered=13",
"fetched=3",
"failed=1",
"skipped_unsupported=3",
"mindnote:2",
"slides:1",
} {
if !strings.Contains(summary, want) {
t.Errorf("summary() = %q, missing %q", summary, want)
}
}
}
func TestFetchTally_EmptyHasNoSkips(t *testing.T) {
tally := newFetchTally(0)
if got := tally.skipped(); got != 0 {
t.Errorf("skipped() = %d, want 0", got)
}
if !strings.Contains(tally.summary(), "skipped_unsupported=0") {
t.Errorf("summary() = %q, want skipped_unsupported=0", tally.summary())
}
}
@@ -0,0 +1,60 @@
package core
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/types"
"github.com/sirupsen/logrus"
)
func TestTenantAccessTokenNeverAppearsInLogs(t *testing.T) {
for _, token := range []string{"synthetic-access-value-for-logging-test", "xyz"} {
t.Run(token, func(t *testing.T) {
var logs bytes.Buffer
recorder := logrus.New()
recorder.SetOutput(&logs)
recorder.SetLevel(logrus.DebugLevel)
ctx := context.WithValue(context.Background(), types.LoggerContextKey, logrus.NewEntry(recorder))
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
if r.URL.Path != "/open-apis/auth/v3/tenant_access_token/internal" || r.Method != http.MethodPost {
t.Errorf("unexpected token request")
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": token, "expire": 7200})
}))
defer server.Close()
client := &Client{
baseURL: server.URL,
appID: "test-app",
appSecret: "synthetic-credential",
httpClient: server.Client(),
}
for i := 0; i < 2; i++ {
got, err := client.GetTenantAccessToken(ctx)
if err != nil || got != token {
t.Fatalf("token retrieval or cache failed: %v", err)
}
}
if calls != 1 {
t.Errorf("cached token should avoid a second request; got %d", calls)
}
prefix, suffix := token[:min(8, len(token))], token[max(0, len(token)-4):]
for _, secret := range []string{token, prefix, suffix, "synthetic-credential"} {
if strings.Contains(logs.String(), secret) {
t.Error("authentication secret or fragment was logged")
}
}
if !strings.Contains(logs.String(), "expire=7200s") {
t.Error("safe token expiry diagnostics must remain")
}
})
}
}
@@ -0,0 +1,39 @@
package core
import (
"strings"
"testing"
"unicode/utf8"
)
// truncate caps a connector error preview with a plain byte slice. Connector error
// text is often Chinese, so the cut can land inside a multi-byte rune; these
// previews reach sync_logs and data_sources through the sync error message, and
// PostgreSQL rejects the invalid UTF-8 that a partial rune produces.
func TestTruncateKeepsValidUTF8AcrossCaps(t *testing.T) {
body := strings.Repeat("错", 400)
for _, maxLen := range []int{499, 500, 501, 1000, 1} {
got := truncate(body, maxLen)
if !utf8.ValidString(got) {
t.Fatalf("%s(%d): preview is not valid UTF-8", "truncate", maxLen)
}
if len(got) > maxLen+len("...") {
t.Fatalf("%s(%d): preview is %d bytes", "truncate", maxLen, len(got))
}
if !strings.HasPrefix(body, strings.TrimSuffix(got, "...")) {
t.Fatalf("%s(%d): preview is not a prefix of the input", "truncate", maxLen)
}
}
}
func TestTruncateLeavesShortAndASCIIInputAlone(t *testing.T) {
for _, s := range []string{"", "ok", "服务返回 500", "短"} {
if got := truncate(s, 500); got != s {
t.Fatalf("%s(%q, 500) = %q, want the input unchanged", "truncate", s, got)
}
}
if got := truncate("abcdef", 3); got != "abc..." {
t.Fatalf("truncate keeps the ASCII cut: %q", got)
}
}
@@ -0,0 +1,376 @@
// Package feishu implements the Feishu (飞书/Lark) data source connector for Academy.
//
// It syncs documents from Feishu Wiki spaces and cloud documents into Academy knowledge bases.
//
// Feishu API docs:
// - Wiki spaces: https://open.feishu.cn/document/server-docs/docs/wiki-v2/space/list
// - Wiki nodes: https://open.feishu.cn/document/server-docs/docs/wiki-v2/space-node/list
// - Export tasks: https://open.feishu.cn/document/server-docs/docs/drive-v1/export_task/export-user-guide
// - File download: https://open.feishu.cn/document/server-docs/docs/drive-v1/file/download
// - Auth: https://open.feishu.cn/document/server-docs/authentication-management/access-token/tenant_access_token_internal
package core
import (
"strings"
"time"
)
// Config holds Feishu-specific configuration for the data source connector.
// Uses the self-built app (企业自建应用) authentication model.
type Config struct {
// App ID from Feishu developer console
AppID string `json:"app_id"`
// App Secret from Feishu developer console
AppSecret string `json:"app_secret"`
// 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"`
// ParseMode selects the docx parsing path: "blocks" (default) renders the
// blocks API into Markdown with attachment sub-items; "export" exports
// a .docx binary that docreader parses inline, keeping image↔document
// association via parent_chunk_id. Parsed from Settings["parse_mode"] by
// ParseFeishuConfig and threaded via DocxFetchInput.ParseMode; see
// FetchDocxWithBlocks.
ParseMode string `json:"parse_mode,omitempty"`
}
// Docx parse modes (Config.ParseMode, from Settings["parse_mode"]).
const (
// ParseModeBlocks renders docx via the blocks API into Markdown (default).
ParseModeBlocks = "blocks"
// ParseModeExport exports docx as a binary and lets docreader parse it
// inline — the escape hatch when image↔document association matters.
ParseModeExport = "export"
)
// 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.
const defaultBaseURL = "https://open.feishu.cn"
// larkBaseURL is the Lark (international) API base URL.
const larkBaseURL = "https://open.larksuite.com"
// GetBaseURL returns the effective base URL, defaulting to Feishu if not set.
func (c *Config) GetBaseURL() string {
if c.BaseURL != "" {
return c.BaseURL
}
return defaultBaseURL
}
// --- Export format constants ---
// Used by the export task API: POST /drive/v1/export_tasks
const (
// ExportTypeDocx exports Feishu documents to .docx format.
ExportTypeDocx = "docx"
// ExportTypeXlsx exports spreadsheets / bitable to .xlsx format.
ExportTypeXlsx = "xlsx"
// ExportTypePDF exports documents to .pdf format (fallback).
ExportTypePDF = "pdf"
)
// ObjTypeToExportFileExtension maps Feishu obj_type to the best export file_extension.
var ObjTypeToExportFileExtension = map[string]string{
"docx": ExportTypeDocx,
"doc": ExportTypeDocx,
"sheet": ExportTypeXlsx,
"bitable": ExportTypeXlsx,
}
// ObjTypeToExportType maps Feishu obj_type to the export API "type" parameter.
// See: https://open.feishu.cn/document/server-docs/docs/drive-v1/export_task/create
var ObjTypeToExportType = map[string]string{
"docx": "docx",
"doc": "doc",
"sheet": "sheet",
"bitable": "bitable",
}
// ExportFileExtToSuffix maps export file_extension to the file suffix for FileName.
var ExportFileExtToSuffix = map[string]string{
ExportTypeDocx: ".docx",
ExportTypeXlsx: ".xlsx",
ExportTypePDF: ".pdf",
}
// --- Feishu API response structures ---
// ApiResponse is the common Feishu API response wrapper.
type ApiResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
// TokenResponse is the response for tenant_access_token API.
type TokenResponse struct {
ApiResponse
TenantAccessToken string `json:"tenant_access_token"`
Expire int `json:"expire"` // seconds
}
// WikiSpaceListData is the data payload of WikiSpaceListResponse.
type WikiSpaceListData struct {
Items []WikiSpace `json:"items"`
HasMore bool `json:"has_more"`
PageToken string `json:"page_token"`
}
// WikiSpaceListResponse is the response for GET /open-apis/wiki/v2/spaces.
type WikiSpaceListResponse struct {
ApiResponse
Data WikiSpaceListData `json:"data"`
}
// WikiSpace represents a Feishu Wiki space.
type WikiSpace struct {
SpaceID string `json:"space_id"`
Name string `json:"name"`
Description string `json:"description"`
Visibility string `json:"visibility"` // "public" or "private"
}
// WikiNodeListData is the data payload of WikiNodeListResponse.
type WikiNodeListData struct {
Items []WikiNode `json:"items"`
HasMore bool `json:"has_more"`
PageToken string `json:"page_token"`
}
// WikiNodeListResponse is the response for GET /open-apis/wiki/v2/spaces/:space_id/nodes.
type WikiNodeListResponse struct {
ApiResponse
Data WikiNodeListData `json:"data"`
}
// WikiNode represents a node (document or folder) in a Feishu Wiki space.
type WikiNode struct {
SpaceID string `json:"space_id"`
NodeToken string `json:"node_token"`
ObjToken string `json:"obj_token"` // document token
ObjType string `json:"obj_type"` // "doc", "sheet", "mindnote", "bitable", "file", "docx", "slides"
ParentNodeID string `json:"parent_node_token"`
NodeType string `json:"node_type"` // "origin" or "shortcut"
OriginNodeID string `json:"origin_node_token"`
OriginSpaceID string `json:"origin_space_id"`
HasChild bool `json:"has_child"`
Title string `json:"title"`
Creator string `json:"creator"`
Owner string `json:"owner"`
ObjCreateTime string `json:"obj_create_time"` // document creation time (unix timestamp string)
ObjEditTime string `json:"obj_edit_time"` // document last edit time (unix timestamp string) — tracks content changes
NodeCreateTime string `json:"node_create_time"` // node creation time (unix timestamp string)
NodeEditTime string `json:"node_edit_time"` // node edit time (unix timestamp string) — only tracks node attribute changes
}
// WikiNodeInfoData is the data payload of WikiNodeInfoResponse.
type WikiNodeInfoData struct {
Node WikiNode `json:"node"`
}
// WikiNodeInfoResponse is the response for GET /open-apis/wiki/v2/spaces/get_node.
type WikiNodeInfoResponse struct {
ApiResponse
Data WikiNodeInfoData `json:"data"`
}
// --- Export task API responses ---
// docRawContentData is the data payload of docRawContentResponse.
type docRawContentData struct {
Content string `json:"content"`
}
// docRawContentResponse is the response for GET /open-apis/docx/v1/documents/:document_id/raw_content.
// Deprecated: prefer export API for full-fidelity document export.
type docRawContentResponse struct {
ApiResponse
Data docRawContentData `json:"data"`
}
// ExportTaskCreateData is the data payload of ExportTaskCreateResponse.
type ExportTaskCreateData struct {
Ticket string `json:"ticket"`
}
// ExportTaskCreateResponse is the response for POST /drive/v1/export_tasks.
type ExportTaskCreateResponse struct {
ApiResponse
Data ExportTaskCreateData `json:"data"`
}
// ExportTaskResult is the per-task result inside ExportTaskStatusData.
type ExportTaskResult struct {
FileToken string `json:"file_token"`
FileSize int64 `json:"file_size"`
// JobStatus: 0=success, 1=initializing, 2=processing
JobStatus int `json:"job_status"`
JobErrorMsg string `json:"job_error_msg"`
FileName string `json:"file_name"`
}
// ExportTaskStatusData is the data payload of ExportTaskStatusResponse.
type ExportTaskStatusData struct {
Result ExportTaskResult `json:"result"`
}
// ExportTaskStatusResponse is the response for GET /drive/v1/export_tasks/{ticket}.
type ExportTaskStatusResponse struct {
ApiResponse
Data ExportTaskStatusData `json:"data"`
}
// --- File download response ---
// driveFileMeta is one entry of driveFileMetaData.Metas.
type driveFileMeta struct {
DocToken string `json:"doc_token"`
DocType string `json:"doc_type"`
Title string `json:"title"`
}
// driveFileMetaData is the data payload of driveFileMetaResponse.
type driveFileMetaData struct {
Metas []driveFileMeta `json:"metas"`
}
// driveFileMetaResponse is the response for GET /drive/v1/metas for file type nodes.
type driveFileMetaResponse struct {
ApiResponse
Data driveFileMetaData `json:"data"`
}
// FeishuCursor stores incremental sync state for Feishu.
type FeishuCursor struct {
// LastSyncTime is the timestamp of the last successful sync.
LastSyncTime time.Time `json:"last_sync_time"`
// SpaceNodeTimes maps space_id -> node_token -> last known edit time.
// Used to detect which nodes have changed since last sync.
SpaceNodeTimes map[string]map[string]string `json:"space_node_times,omitempty"`
}
// --- Drive (云盘) file listing types (feishu_drive / lark_drive connectors) ---
// Added by feat/datasource-feishu-drive. These are independent of the wiki
// types above and do not affect the wiki connector.
// DriveFile represents a file/folder in Feishu Drive (云空间). Returned by
// GET /open-apis/drive/v1/files?folder_token=xxx. The list API returns
// modified_time directly (verified), so no batch_query/metas call is needed for
// incremental detection - see ADR-0002.
type DriveFile struct {
Token string `json:"token"`
Name string `json:"name"`
Type string `json:"type"` // doc/docx/sheet/bitable/file/folder/shortcut/mindnote/slides/board
ParentToken string `json:"parent_token"`
URL string `json:"url"`
CreatedTime string `json:"created_time"` // unix seconds string
ModifiedTime string `json:"modified_time"` // unix seconds string - 等价知识库 obj_edit_time
OwnerID string `json:"owner_id"`
// ShortcutInfo is populated only for type=="shortcut". target_type can only
// be doc/sheet/mindnote/bitable/file/docx (Feishu does not allow shortcuts to
// folders, verified) - see ADR-0002 / glossary shortcut entry.
ShortcutInfo *driveShortcutInfo `json:"shortcut_info,omitempty"`
}
// driveShortcutInfo is the target metadata of a Drive shortcut.
type driveShortcutInfo struct {
TargetToken string `json:"target_token"`
TargetType string `json:"target_type"`
}
// DriveFileListData is the data payload of DriveFileListResponse.
type DriveFileListData struct {
Files []DriveFile `json:"files"`
HasMore bool `json:"has_more"`
NextPageToken string `json:"next_page_token"`
}
// DriveFileListResponse is the response for GET /open-apis/drive/v1/files.
type DriveFileListResponse struct {
ApiResponse
Data DriveFileListData `json:"data"`
}
// driveFolderMetaData is the data payload of driveFolderMetaResponse.
type driveFolderMetaData struct {
ID string `json:"id"`
Name string `json:"name"`
Token string `json:"token"`
CreateUid string `json:"createUid"`
EditUid string `json:"editUid"`
ParentID string `json:"parentId"`
OwnUid string `json:"ownUid"`
}
// driveFolderMetaResponse is the response for GET /open-apis/drive/explorer/v2/folder/:folderToken/meta.
// Used to resolve a root folder's human-readable name (the list API only returns
// the folder's children, not the folder itself).
type driveFolderMetaResponse struct {
ApiResponse
Data driveFolderMetaData `json:"data"`
}
// DriveFileListFailure records a single sub-folder listing that failed during a
// recursive walk. Mirrors WikiNodeListFailure.
type DriveFileListFailure struct {
FolderToken string
Err error
}
// PartialDriveFileListError aggregates per-folder listing failures so the walk
// can continue and the caller can still surface the partial result. Mirrors
// PartialWikiNodeListError.
type PartialDriveFileListError struct {
Failures []DriveFileListFailure
}
func (e *PartialDriveFileListError) Error() string {
if e == nil || len(e.Failures) == 0 {
return "partial drive file listing failed"
}
parts := make([]string, 0, len(e.Failures))
for _, failure := range e.Failures {
parts = append(parts, failure.Err.Error())
}
return strings.Join(parts, "; ")
}
// FeishuDriveCursor stores incremental sync state for Feishu Drive (云盘).
// Structurally symmetric with FeishuCursor: outer key = resourceID
// ("folderToken" or "folderToken:fileToken"), inner key = file_token,
// value = modified_time. See ADR-0001.
type FeishuDriveCursor struct {
// LastSyncTime is the timestamp of the last successful sync.
LastSyncTime time.Time `json:"last_sync_time"`
// FileTimes maps resourceID -> file_token -> last known modified_time.
// Used to detect which files have changed since last sync.
FileTimes map[string]map[string]string `json:"file_times,omitempty"`
}
@@ -0,0 +1,145 @@
package core
import (
"context"
"errors"
"fmt"
"academy/internal/logger"
)
// ListWikiNodesWithShortcuts supplements the existing traversal with descendants
// of shortcuts. The original traversal and its partial failures are preserved.
func (c *Client) ListWikiNodesWithShortcuts(ctx context.Context, spaceID, nodeToken string) ([]WikiNode, error) {
nodes, err := c.ListWikiNodesRecursiveFrom(ctx, spaceID, nodeToken)
var failures []WikiNodeListFailure
if err != nil {
var partial *PartialWikiNodeListError
if !errors.As(err, &partial) {
return nodes, err
}
failures = append(failures, partial.Failures...)
}
return c.expandWikiShortcuts(ctx, spaceID, nodes, failures)
}
func (c *Client) expandWikiShortcuts(
ctx context.Context, spaceID string, nodes []WikiNode, failures []WikiNodeListFailure,
) ([]WikiNode, error) {
if err := ctx.Err(); err != nil {
return nodes, err
}
// Existing nodes have already been emitted. The original traversal handles
// ordinary nodes and shortcuts reporting children; only unexpanded shortcuts
// need processing in this extension.
seen := make(map[string]bool)
processed := make(map[string]bool)
expanded := make(map[string]bool)
origins := make(map[string]WikiNode)
var shortcuts []WikiNode
for _, node := range nodes {
if node.SpaceID == "" {
node.SpaceID = spaceID
}
key := node.SpaceID + ":" + node.NodeToken
seen[key] = true
origins[key] = node
if node.NodeType == "shortcut" && !node.HasChild {
shortcuts = append(shortcuts, node)
} else {
processed[key] = true
// Failed listings remain partial failures rather than being retried
// through another alias during the same sync.
if node.HasChild {
expanded[key] = true
}
}
}
var walk func(string, []WikiNode) error
walk = func(parentSpace string, children []WikiNode) error {
for _, node := range children {
if err := ctx.Err(); err != nil {
return err
}
if node.SpaceID == "" {
node.SpaceID = parentSpace
}
key := node.SpaceID + ":" + node.NodeToken
if processed[key] {
continue
}
processed[key] = true
if !seen[key] {
seen[key] = true
nodes = append(nodes, node)
}
target, err := c.resolveWikiShortcut(ctx, node, origins)
if err == nil && target.HasChild {
key = target.SpaceID + ":" + target.NodeToken
if expanded[key] {
continue
}
expanded[key] = true
var descendants []WikiNode
descendants, err = c.ListWikiNodes(ctx, target.SpaceID, target.NodeToken)
if err == nil {
if node.NodeType == "shortcut" {
// Keep the discovered subtree under the selected shortcut
// for directory mapping, while retaining source space IDs.
for i := range descendants {
descendants[i].ParentNodeID = node.NodeToken
}
}
if err := walk(target.SpaceID, descendants); err != nil {
return err
}
}
}
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
wrapped := fmt.Errorf("list children of %s: %w", node.NodeToken, err)
failures = append(failures, WikiNodeListFailure{Node: node, Err: wrapped})
logger.Warnf(ctx, "[Feishu] partial wiki node listing failure: space=%s node=%s err=%v",
node.SpaceID, node.NodeToken, wrapped)
}
}
return nil
}
if err := walk(spaceID, shortcuts); err != nil {
return nodes, err
}
if len(failures) > 0 {
return nodes, &PartialWikiNodeListError{Failures: failures}
}
return nodes, nil
}
func (c *Client) resolveWikiShortcut(ctx context.Context, node WikiNode, cache map[string]WikiNode) (WikiNode, error) {
visited := make(map[string]bool)
for node.NodeType == "shortcut" {
key := node.SpaceID + ":" + node.NodeToken
if visited[key] {
return WikiNode{}, fmt.Errorf("wiki shortcut cycle at %s", node.NodeToken)
}
visited[key] = true
if node.OriginNodeID == "" || node.OriginSpaceID == "" {
return WikiNode{}, fmt.Errorf("wiki shortcut %s is missing its original node or space", node.NodeToken)
}
key = node.OriginSpaceID + ":" + node.OriginNodeID
original, ok := cache[key]
if !ok {
var err error
original, err = c.GetWikiNode(ctx, node.OriginSpaceID, node.OriginNodeID)
if err != nil {
return WikiNode{}, fmt.Errorf("resolve wiki shortcut %s: %w", node.NodeToken, err)
}
cache[key] = original
}
node = original
}
return node, nil
}
@@ -0,0 +1,615 @@
package drive
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"academy/internal/datasource"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/logger"
"academy/internal/types"
)
// DriveConnector implements the datasource.Connector (and StreamingConnector)
// interface for Feishu/Lark Drive (云盘) mode. It shares core.Client/core.Config/core.Region
// and the export/download logic with the wiki Connector; only resource
// enumeration and Fetch dispatch differ. See 飞书云盘数据源设计.md and
// ADR-0001..0004.
type DriveConnector struct {
region core.Region
}
// NewDriveConnector creates a Drive connector for the given region
// (RegionFeishuDrive or RegionLarkDrive).
func NewDriveConnector(region core.Region) *DriveConnector {
return &DriveConnector{region: region}
}
// Drive supports resumable streaming sync; the service prefers FetchStream over
// FetchAll/FetchIncremental when a connector implements StreamingConnector.
var _ datasource.StreamingConnector = (*DriveConnector)(nil)
var _ datasource.FullStreamingConnector = (*DriveConnector)(nil)
// Type returns the connector type identifier.
func (c *DriveConnector) Type() string {
return c.region.ConnectorType
}
// Validate verifies that the Drive configuration is valid by testing
// connectivity. It does not validate folder_token here - that is done in
// ListResources when the user loads the tree root. Mirrors the wiki Connector.
func (c *DriveConnector) Validate(ctx context.Context, config *types.DataSourceConfig) error {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return err
}
client := core.NewClient(feishuConfig)
if err := client.Ping(ctx); err != nil {
return fmt.Errorf("%s connection failed: %w", c.region.Label, err)
}
return nil
}
// ListResources lists Feishu Drive resources for selection, loading the tree
// lazily one level at a time. Mirrors the wiki Connector.ListResources shape
// but with the Drive difference that the root is user-supplied (config.
// ResourceIDs[0]) rather than enumerated via ListWikiSpaces.
//
// - parentID == "" -> return the user-supplied root
// folder (from config.ResourceIDs[0]) as the single root resource
// (HasChildren=true). Drive has no "space list" API, so the root is
// user-supplied. folder_token == "" is rejected (ADR-0004).
// - parentID == folderToken -> ListDriveFiles(folderToken)
// returns the direct children.
// - parentID == "folderToken:subFolderToken" -> ListDriveFiles(subFolderToken)
// returns that sub-folder's direct children.
//
// Each core.DriveFile becomes a Resource: folder HasChildren=true, others false.
// resourceID encoding: root = folderToken; child = folderToken + ":" + fileToken
// (reuses core.FeishuWikiNodeResourceSeparator). See ADR-0001 §3.4.
func (c *DriveConnector) ListResources(
ctx context.Context, config *types.DataSourceConfig, parentID string,
) ([]types.Resource, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
if parentID == "" {
// Root load: read the user-supplied folder_token from config.ResourceIDs.
rootFolderToken := driveRootFolderToken(config)
if rootFolderToken == "" {
return nil, fmt.Errorf("folder_token is required; specify a Drive folder token")
}
// Validate access by listing the root's direct children (also lazy-loads
// the first level for the picker). Reuse the list call rather than a
// separate ping.
files, err := client.ListDriveFilesAllPages(ctx, rootFolderToken)
if err != nil {
return nil, fmt.Errorf("list feishu drive folder %s: %w", rootFolderToken, err)
}
_ = files // children returned via the parentID == rootFolderToken branch below
// Resolve the root folder's human-readable name via the folder meta API.
// Best-effort: on failure (no permission / not found) fall back to the
// folder_token so the picker still renders something usable.
folderName := rootFolderToken
if meta, mErr := client.GetDriveFolderMeta(ctx, rootFolderToken); mErr != nil {
logger.Warnf(ctx, "[FeishuDrive] resolve root folder name failed: %v (falling back to token)", mErr)
} else if meta.Data.Name != "" {
folderName = meta.Data.Name
}
return []types.Resource{c.driveFolderToResource(rootFolderToken, "", rootFolderToken, folderName)}, nil
}
// Lazy load: list only the direct children of the given folder.
rootFolderToken, folderToken := parseDriveResourceID(parentID)
if folderToken == "" {
// parentID is a bare root folder token -> list its children.
folderToken = rootFolderToken
}
files, err := client.ListDriveFilesAllPages(ctx, folderToken)
if err != nil {
return nil, fmt.Errorf("list feishu drive files under %s: %w", parentID, err)
}
resources := make([]types.Resource, 0, len(files))
for _, f := range files {
resources = append(resources, c.driveFileToResource(rootFolderToken, f))
}
return resources, nil
}
// ResolveResourceAncestors returns the resource IDs of every parent folder that
// has to be expanded so the lazily-loaded picker can reveal each selection.
//
// The wiki connector walks up via GetWikiNode (parent_node_token) in O(depth)
// single-node queries. Drive has no single-file parent query API (verified -
// metas/batch_query does not return parent), so we walk top-down from the root
// folder with ListDriveFiles and share the traversal across all selections in
// the same root. Best-effort: a broken path just stays collapsed. See ADR-0003.
func (c *DriveConnector) ResolveResourceAncestors(
ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,
) ([]string, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
seen := make(map[string]bool)
ancestors := make([]string, 0)
add := func(id string) {
if id != "" && !seen[id] {
seen[id] = true
ancestors = append(ancestors, id)
}
}
// Group selections by root folder so one shared traversal covers them all.
type selection struct {
fileToken string
}
rootSelections := make(map[string][]selection)
for _, rid := range resourceIDs {
rootFolderToken, fileToken := parseDriveResourceID(rid)
if fileToken == "" {
// A root-level selection is already a top-level node; nothing to reveal.
continue
}
add(rootFolderToken)
rootSelections[rootFolderToken] = append(rootSelections[rootFolderToken], selection{fileToken})
}
// For each root, BFS from the root: at each folder, ListDriveFiles and check
// which selections are direct children (record their parent chain) and which
// sub-folders may still contain selections (enqueue). Shared traversal means
// selections in the same subtree reuse list calls.
for rootFolderToken, sels := range rootSelections {
remaining := make(map[string]bool, len(sels))
for _, s := range sels {
remaining[s.fileToken] = true
}
// parentChain[fileToken] = resourceID of its parent folder
parentChain := make(map[string]string)
queue := []string{rootFolderToken}
for len(queue) > 0 && len(remaining) > 0 {
cur := queue[0]
queue = queue[1:]
files, err := client.ListDriveFilesAllPages(ctx, cur)
if err != nil {
logger.Warnf(ctx, "[FeishuDrive] resolve ancestors: list %s: %v", cur, err)
break // best-effort: stop this root's traversal
}
for _, f := range files {
if remaining[f.Token] {
delete(remaining, f.Token)
// Record the parent chain from root down to this file's parent.
chain := buildDriveAncestorChain(rootFolderToken, cur, parentChain)
for _, a := range chain {
add(a)
}
}
if f.Type == "folder" {
parentChain[f.Token] = makeDriveResourceID(rootFolderToken, cur)
queue = append(queue, f.Token)
}
}
}
}
return ancestors, nil
}
// buildDriveAncestorChain walks the parentChain map from cur up to root,
// returning the resourceIDs (root, ... , cur's parent) in root-first order.
func buildDriveAncestorChain(rootFolderToken, cur string, parentChain map[string]string) []string {
var chain []string
node := cur
for node != "" && node != rootFolderToken {
parent, ok := parentChain[node]
if !ok {
break
}
chain = append([]string{parent}, chain...)
_, parentFolderToken := parseDriveResourceID(parent)
node = parentFolderToken
}
return chain
}
// FetchAll performs a full sync of all documents from the selected Drive
// folders. Defensive fallback path - the service prefers FetchStream when the
// connector implements StreamingConnector.
func (c *DriveConnector) FetchAll(
ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,
) ([]types.FetchedItem, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
return core.FetchAllEngine(ctx, client, config, resourceIDs,
&driveOps{region: c.region, parseMode: feishuConfig.ParseMode})
}
// FetchIncremental performs an incremental sync by comparing file modified_time
// against the previously recorded state. Defensive fallback path - the service
// prefers FetchStream. Routed through the same engine as FetchStream, so the
// #2136 failure-doesn't-advance-cursor semantics apply here too.
func (c *DriveConnector) FetchIncremental(
ctx context.Context, config *types.DataSourceConfig, cursor *types.SyncCursor,
) ([]types.FetchedItem, *types.SyncCursor, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, nil, err
}
client := core.NewClient(feishuConfig)
ops := &driveOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchIncrementalEngine(ctx, client, config, cursor, ops)
}
// FetchStream performs a resumable, memory-bounded sync. It unifies the full
// and incremental paths: with cursor == nil it fetches everything, and with a
// cursor it skips files whose recorded modified_time is unchanged - the same
// mechanism that lets a sync which timed out mid-traversal resume from the last
// checkpoint instead of restarting (Tencent/WeKnora#2136).
//
// The per-node loop lives in the shared engine (engine.go); this shell only
// wires the Drive NodeOps adapter.
func (c *DriveConnector) FetchStream(
ctx context.Context, config *types.DataSourceConfig,
cursor *types.SyncCursor, h datasource.StreamHandler,
) (*types.SyncCursor, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
ops := &driveOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchStreamEngine(ctx, client, config, cursor, h, ops)
}
// FetchFullStream refetches content without discarding the deletion baseline.
func (c *DriveConnector) FetchFullStream(
ctx context.Context, config *types.DataSourceConfig,
cursor *types.SyncCursor, h datasource.StreamHandler,
) (*types.SyncCursor, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
ops := &driveOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchFullStreamEngine(ctx, client, config, cursor, h, ops)
}
// driveOps adapts the Drive DriveConnector to the generic sync engine. It
// carries the region (for channel + URL), encodes/decodes the Drive cursor
// wire format (core.FeishuDriveCursor / file_times), and holds the per-run
// directory mapping state (P1): folderNames caches resolved folder display
// names, dirPaths maps folder token → cleaned directory path for the resource
// being synced. List builds the state; Fetch reads it. runSync processes one
// resource at a time, so the mutation is race-free.
type driveOps struct {
region core.Region
parseMode string
folderNames map[string]string
dirPaths map[string]string
rootEntries map[string][]core.DriveFile // successful shallow listings, per run
}
func (o *driveOps) List(ctx context.Context, client *core.Client, resourceID string) ([]core.DriveFile, error, error) {
files, err := o.listDriveFilesForResource(ctx, client, resourceID)
if err == nil {
return files, nil, nil
}
var partial *core.PartialDriveFileListError
if errors.As(err, &partial) {
return files, err, nil
}
return files, nil, err
}
func (o *driveOps) Token(n core.DriveFile) string { return n.Token }
func (o *driveOps) Title(n core.DriveFile) string { return n.Name }
func (o *driveOps) ObjType(n core.DriveFile) string { return n.Type }
func (o *driveOps) EditTime(n core.DriveFile) string {
return core.DocxChangeKey(n.ModifiedTime, n.Type, o.parseMode)
}
func (o *driveOps) Fetch(
ctx context.Context, client *core.Client, n core.DriveFile, resourceID string,
) ([]*types.FetchedItem, error) {
items, err := fetchDriveFileContent(ctx, client, n, resourceID, o.region, o.parseMode)
if err != nil {
return nil, err
}
// P1 directory mapping: prefix the FileName with the containing folder's
// cleaned directory path so ingestion derives the KB folder_path from it.
qualifyItemFileNames(items, o.dirPaths[n.ParentToken])
return items, nil
}
func (o *driveOps) ListFailureItems(resourceID string, partial error) []types.FetchedItem {
var pe *core.PartialDriveFileListError
if errors.As(partial, &pe) {
return appendDriveFileListFailureItems(nil, resourceID, o.channel(), pe.Failures)
}
return nil
}
func (o *driveOps) channel() string {
if o.region.ConnectorType == types.ConnectorTypeLarkDrive {
return types.ChannelLarkDrive
}
return types.ChannelFeishuDrive
}
func (o *driveOps) ResourceNoun() string { return "files" }
func (o *driveOps) EmptyResourceIDsError() string {
return "no resource IDs (Drive folder tokens) configured"
}
func (o *driveOps) LogTag() string { return "[FeishuDrive]" }
func (o *driveOps) DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string {
var prev core.FeishuDriveCursor
b, _ := json.Marshal(m)
_ = json.Unmarshal(b, &prev)
return prev.FileTimes
}
func (o *driveOps) EncodeCursor(times map[string]map[string]string, lastSync time.Time) *types.SyncCursor {
fc := core.FeishuDriveCursor{LastSyncTime: lastSync, FileTimes: times}
m := make(map[string]interface{})
b, _ := json.Marshal(fc)
_ = json.Unmarshal(b, &m)
return &types.SyncCursor{LastSyncTime: lastSync, ConnectorCursor: m}
}
// fetchDriveFileContent fetches the content of a single Drive file and converts
// it to FetchedItems. Dispatches by file.Type, mirroring the wiki
// fetchNodeContent. Shortcuts have already been expanded to their target by
// walkDriveTree, so this only sees the target type.
//
// - docx -> blocks API (Markdown) with export fallback; may return attachments/images
// - doc/sheet/bitable -> ExportAndDownload -> docx/xlsx
// - file -> DownloadDriveFile -> original file
// - mindnote/slides/board -> Skip (no API), returns (nil, nil)
func fetchDriveFileContent(
ctx context.Context, client *core.Client, file core.DriveFile,
resourceID string, region core.Region, parseMode string,
) ([]*types.FetchedItem, error) {
if !core.IsSupportedDocType(file.Type) {
return nil, nil
}
editTime := core.ParseFeishuTimestamp(file.ModifiedTime)
createTime := core.ParseFeishuTimestamp(file.CreatedTime)
// Channel marks the knowledge "source" label. Drive uses its own channel
// (feishu_drive / lark_drive) so Drive docs show "飞书云盘" / "Lark 云盘"
// distinct from the wiki connector's "飞书".
channel := types.ChannelFeishuDrive
if region.ConnectorType == types.ConnectorTypeLarkDrive {
channel = types.ChannelLarkDrive
}
baseMeta := map[string]string{
"obj_token": file.Token,
"obj_type": file.Type,
"file_token": file.Token,
"folder_token": file.ParentToken,
"channel": channel,
}
switch file.Type {
case "docx":
return core.FetchDocxWithBlocks(ctx, client, core.DocxFetchInput{
DocToken: file.Token,
ObjToken: file.Token,
Title: file.Name,
URL: file.URL,
ResourceID: resourceID,
EditTime: editTime,
CreateTime: createTime,
ParseMode: parseMode,
BaseMeta: baseMeta,
})
case "doc", "sheet", "bitable":
data, fileName, err := client.ExportAndDownload(ctx, file.Token, file.Type)
if err != nil {
return nil, fmt.Errorf("export %s (%s): %w", file.Name, file.Type, err)
}
ext := core.ExportFileExtToSuffix[core.ObjTypeToExportFileExtension[file.Type]]
if fileName == "" {
fileName = core.SanitizeFileName(file.Name) + ext
} else if !strings.HasSuffix(strings.ToLower(fileName), ext) {
fileName = core.SanitizeFileName(fileName) + ext
}
return []*types.FetchedItem{{
ExternalID: file.Token,
Title: file.Name,
Content: data,
ContentType: "application/octet-stream",
FileName: fileName,
URL: file.URL,
UpdatedAt: editTime,
CreatedAt: createTime,
SourceResourceID: resourceID,
Metadata: baseMeta,
}}, nil
case "file":
data, err := client.DownloadDriveFile(ctx, file.Token)
if err != nil {
return nil, fmt.Errorf("download file %s (%s): %w", file.Name, file.Token, err)
}
fileName := core.SanitizeFileName(file.Name)
if fileName == "" {
fileName = file.Token
}
return []*types.FetchedItem{{
ExternalID: file.Token,
Title: file.Name,
Content: data,
ContentType: "application/octet-stream",
FileName: fileName,
URL: file.URL,
UpdatedAt: editTime,
CreatedAt: createTime,
SourceResourceID: resourceID,
Metadata: baseMeta,
}}, nil
default:
return nil, nil
}
}
// --- Helpers ---
// makeDriveResourceID encodes a Drive ResourceID: "folderToken" (root) or
// "folderToken:fileToken" (child). Reuses core.FeishuWikiNodeResourceSeparator.
func makeDriveResourceID(rootFolderToken, fileToken string) string {
if fileToken == "" {
return rootFolderToken
}
return rootFolderToken + core.FeishuWikiNodeResourceSeparator + fileToken
}
// parseDriveResourceID splits a Drive resourceID into (rootFolderToken, fileToken).
// Mirrors parseWikiResourceID.
func parseDriveResourceID(resourceID string) (rootFolderToken, fileToken string) {
rootFolderToken, fileToken, _ = strings.Cut(resourceID, core.FeishuWikiNodeResourceSeparator)
return rootFolderToken, fileToken
}
// isDriveNotFolderError reports whether err indicates the token was not a
// folder (1061002 params error from the list API when a file token is passed).
func isDriveNotFolderError(err error) bool {
s := strings.ToLower(err.Error())
return strings.Contains(s, "1061002") || strings.Contains(s, "params error")
}
// filterDriveFileByToken returns only the entries whose Token matches token.
func filterDriveFileByToken(files []core.DriveFile, token string) []core.DriveFile {
var out []core.DriveFile
for _, f := range files {
if f.Token == token {
out = append(out, f)
}
}
return out
}
// driveRootFolderToken extracts the user-supplied root folder_token from the
// data source config (ResourceIDs[0]).
func driveRootFolderToken(config *types.DataSourceConfig) string {
if config == nil || len(config.ResourceIDs) == 0 {
return ""
}
root, _ := parseDriveResourceID(config.ResourceIDs[0])
return root
}
// driveFolderToResource builds the root Resource for a Drive folder. The root
// folder's name is resolved via GetDriveFolderMeta by the caller (best-effort,
// falling back to the token). For sub-folders, use driveFileToResource instead -
// the list API returns each child folder's Name.
//
// The root folder's ExternalID is the bare rootFolderToken (no ":fileToken"
// suffix) so it matches the resource_id the user saved in
// form.config.resource_ids = [folderToken]. A "token:token" encoding would
// break selection matching on edit.
func (c *DriveConnector) driveFolderToResource(rootFolderToken, parentToken, folderToken, name string) types.Resource {
if name == "" {
name = folderToken
}
return types.Resource{
ExternalID: rootFolderToken,
Name: name,
Type: "drive_folder",
URL: c.region.DriveFolderURL(folderToken),
HasChildren: true,
Metadata: map[string]interface{}{
"folder_token": folderToken,
},
}
}
// driveFileToResource converts a core.DriveFile (list result) into a picker Resource.
// The ParentID must match the parent folder's ExternalID: the root folder's
// ExternalID is the bare rootFolderToken (see driveFolderToResource), while any
// sub-folder's ExternalID is "rootFolderToken:folderToken". Direct children of
// the root have file.ParentToken == rootFolderToken, so their ParentID is the
// bare rootFolderToken; deeper descendants use the encoded form.
func (c *DriveConnector) driveFileToResource(rootFolderToken string, file core.DriveFile) types.Resource {
name := file.Name
if name == "" {
name = file.Token
}
modifiedAt := core.ParseFeishuTimestamp(file.ModifiedTime)
parentID := makeDriveResourceID(rootFolderToken, file.ParentToken)
if file.ParentToken == rootFolderToken || file.ParentToken == "" {
// Direct child of the root folder: parent is the root, whose
// ExternalID is the bare rootFolderToken (no ":token" suffix).
parentID = rootFolderToken
}
return types.Resource{
ExternalID: makeDriveResourceID(rootFolderToken, file.Token),
Name: name,
Type: file.Type,
URL: file.URL,
ParentID: parentID,
HasChildren: file.Type == "folder",
ModifiedAt: modifiedAt,
Metadata: map[string]interface{}{
"file_token": file.Token,
"obj_type": file.Type,
"folder_token": file.ParentToken,
},
}
}
// appendDriveFileListFailureItems converts Drive listing failures into error
// FetchedItems so the sync log surfaces which sub-folders could not be listed.
// Mirrors appendWikiNodeListFailureItems.
func appendDriveFileListFailureItems(items []types.FetchedItem, resourceID, channel string, failures []core.DriveFileListFailure) []types.FetchedItem {
for _, failure := range failures {
items = append(items, types.FetchedItem{
ExternalID: failure.FolderToken,
Title: failure.FolderToken,
SourceResourceID: resourceID,
Metadata: core.FeishuErrorItemMeta(failure.Err, map[string]string{
"channel": channel,
"folder_token": failure.FolderToken,
"failure_stage": "list_children",
}),
})
}
return items
}
@@ -0,0 +1,428 @@
package drive
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/types"
)
// ──────────────────────────────────────────────────────────────────────
// P1 directory mapping tests for the Drive connector: path-qualified
// FileName, deletion mirroring, partial-listing suppression, move following.
// ──────────────────────────────────────────────────────────────────────
// fakeDriveTree serves a mutable Drive folder tree keyed by folder_token.
// folders maps folder token → direct children (folders recurse, files sync);
// failing folders return HTTP 500 to model a partial listing; metaNames maps
// folder token → display name for the folder meta endpoint (absent = error).
type fakeDriveTree struct {
folders map[string][]core.DriveFile
failing map[string]bool
metaNames map[string]string
// listCalls / metaCalls count API hits per token, so tests can assert a
// file token is never probed with folder APIs.
listCalls map[string]int
metaCalls map[string]int
ts *httptest.Server
cfg *core.Config
}
func newFakeDriveTree(t *testing.T, folders map[string][]core.DriveFile) *fakeDriveTree {
t.Helper()
f := &fakeDriveTree{
folders: folders, failing: map[string]bool{},
listCalls: map[string]int{}, metaCalls: map[string]int{},
}
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal",
func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, core.TokenResponse{
ApiResponse: core.ApiResponse{Code: 0},
TenantAccessToken: "fake-token", Expire: 7200,
})
})
// Folder listing (paged endpoint, exact path) and file download (subtree).
mux.HandleFunc("/open-apis/drive/v1/files", func(w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("folder_token")
f.listCalls[token]++
if f.failing[token] {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"code":1663,"msg":"internal error"}`))
return
}
writeJSON(w, core.DriveFileListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DriveFileListData{Files: f.folders[token]},
})
})
mux.HandleFunc("/open-apis/drive/v1/files/", func(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, "/download") {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write([]byte("fake-drive-file-content"))
})
mux.HandleFunc("/open-apis/drive/explorer/v2/folder/", func(w http.ResponseWriter, r *http.Request) {
// path: /open-apis/drive/explorer/v2/folder/<token>/meta
p := strings.TrimPrefix(r.URL.Path, "/open-apis/drive/explorer/v2/folder/")
token := strings.TrimSuffix(p, "/meta")
f.metaCalls[token]++
name, ok := f.metaNames[token]
if !ok {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"code":1061004,"msg":"not found"}`))
return
}
writeJSON(w, map[string]interface{}{
"code": 0,
"data": map[string]interface{}{"name": name},
})
})
f.ts = httptest.NewServer(mux)
t.Cleanup(f.ts.Close)
f.cfg = &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: f.ts.URL}
return f
}
// driveFile builds a regular file entry; folder builds a folder entry.
func driveFile(token, name, parent string, modified string) core.DriveFile {
return core.DriveFile{Token: token, Name: name, Type: "file", ParentToken: parent, ModifiedTime: modified}
}
func driveFolder(token, name, parent string) core.DriveFile {
return core.DriveFile{Token: token, Name: name, Type: "folder", ParentToken: parent}
}
// fetchedByToken indexes emitted non-deleted items by external_id.
func fetchedByToken(items []types.FetchedItem) map[string]types.FetchedItem {
m := make(map[string]types.FetchedItem, len(items))
for _, it := range items {
if !it.IsDeleted {
m[it.ExternalID] = it
}
}
return m
}
func deletedIDs(items []types.FetchedItem) []string {
var ids []string
for _, it := range items {
if it.IsDeleted {
ids = append(ids, it.ExternalID)
}
}
return ids
}
// TestDriveFetchIncremental_PathQualifiedMultiLevel anchors the directory
// mapping: the selected root folder mirrors as a top-level KB folder named
// after it, so paths are <根名>/<子目录...>/<文件名>, Chinese names kept,
// "/" in a folder name sanitised to "_", multi-level nesting resolved from
// the same walk.
func TestDriveFetchIncremental_PathQualifiedMultiLevel(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"fold-root": {
driveFolder("fold-spec", "规格", "fold-root"),
driveFolder("fold-bad", "a/b", "fold-root"), // "/" in the name → "_"
driveFile("f-root", "说明.pdf", "fold-root", "100"),
},
"fold-spec": {driveFile("f-spec", "详细.pdf", "fold-spec", "200")},
"fold-bad": {driveFile("f-bad", "child.pdf", "fold-bad", "300")},
})
f.metaNames = map[string]string{"fold-root": "团队资料"}
c := NewDriveConnector(core.RegionFeishuDrive)
items, _, err := c.FetchIncremental(context.Background(), makeDriveConfig(f.cfg, []string{"fold-root"}), nil)
if err != nil {
t.Fatalf("FetchIncremental() error: %v", err)
}
want := map[string]string{
// The selected root folder mirrors as a top-level KB folder ("团队资料"
// via the meta mock): every item's path starts with the root name,
// deeper ones then carry the sub-directory path.
"f-root": "团队资料/说明.pdf",
"f-spec": "团队资料/规格/详细.pdf",
"f-bad": "团队资料/a_b/child.pdf",
}
got := fetchedByToken(items)
if len(got) != len(want) {
t.Fatalf("got %d items (%v), want %d", len(got), got, len(want))
}
for id, wantPath := range want {
if got[id].FileName != wantPath {
t.Errorf("FileName for %s = %q, want %q", id, got[id].FileName, wantPath)
}
}
}
// TestDriveFetchIncremental_DeletionMirror anchors the deletion engine: a
// second full listing that misses a previously synced token emits exactly one
// IsDeleted item for it; the first sync (no cursor) emits none.
func TestDriveFetchIncremental_DeletionMirror(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"fold-root": {
driveFile("f-a", "a.pdf", "fold-root", "100"),
driveFile("f-b", "b.pdf", "fold-root", "200"),
},
})
f.metaNames = map[string]string{"fold-root": "团队资料"}
c := NewDriveConnector(core.RegionFeishuDrive)
cfg := makeDriveConfig(f.cfg, []string{"fold-root"})
items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first sync error: %v", err)
}
if ids := deletedIDs(items1); len(ids) != 0 {
t.Errorf("first sync emitted IsDeleted items %v — deletion must be suppressed without a prior cursor", ids)
}
// f-a disappears from the tree.
f.folders["fold-root"] = []core.DriveFile{driveFile("f-b", "b.pdf", "fold-root", "200")}
items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("second sync error: %v", err)
}
ids := deletedIDs(items2)
if len(ids) != 1 || ids[0] != "f-a" {
t.Errorf("second sync deleted ids = %v, want [f-a]", ids)
}
}
// TestDriveFetchIncremental_PartialListingDoesNotDelete anchors the partial
// safety: when a sub-folder cannot be listed, deletion detection is suppressed
// even though a previously seen token is missing from the (incomplete) listing.
func TestDriveFetchIncremental_PartialListingDoesNotDelete(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"fold-root": {
driveFolder("fold-doomed", "doomed", "fold-root"),
driveFile("f-a", "a.pdf", "fold-root", "100"),
},
"fold-doomed": {driveFile("f-deep", "deep.pdf", "fold-doomed", "300")},
})
f.metaNames = map[string]string{"fold-root": "团队资料"}
f.failing["fold-doomed"] = true
c := NewDriveConnector(core.RegionFeishuDrive)
cfg := makeDriveConfig(f.cfg, []string{"fold-root"})
items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first sync error: %v", err)
}
if _, ok := fetchedByToken(items1)["f-a"]; !ok {
t.Fatalf("first sync missing f-a: %+v", items1)
}
// f-a disappears while the sub-folder listing stays broken: the listing is
// partial, so the missing token must NOT be reported as deleted.
f.folders["fold-root"] = []core.DriveFile{driveFolder("fold-doomed", "doomed", "fold-root")}
items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("second sync error: %v", err)
}
if ids := deletedIDs(items2); len(ids) != 0 {
t.Errorf("partial listing emitted IsDeleted items %v — deletion must be suppressed on a partial listing", ids)
}
}
// TestDriveFetchIncremental_MoveFollowsNewPath anchors the move story at the
// connector level: the same external_id re-fetched after being moved between
// folders comes back with the NEW path-qualified FileName (ingestion's
// update=delete+recreate then lands it in the new folder_path).
func TestDriveFetchIncremental_MoveFollowsNewPath(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"fold-root": {
driveFolder("fold-a", "目录A", "fold-root"),
},
"fold-a": {driveFile("f-doc", "文档.pdf", "fold-a", "100")},
})
f.metaNames = map[string]string{"fold-root": "团队资料"}
c := NewDriveConnector(core.RegionFeishuDrive)
cfg := makeDriveConfig(f.cfg, []string{"fold-root"})
items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first sync error: %v", err)
}
if got := fetchedByToken(items1)["f-doc"].FileName; got != "团队资料/目录A/文档.pdf" {
t.Fatalf("first sync f-doc FileName = %q, want 团队资料/目录A/文档.pdf", got)
}
// Move f-doc to a new folder 目录B and bump its modified time.
f.folders["fold-root"] = []core.DriveFile{
driveFolder("fold-a", "目录A", "fold-root"),
driveFolder("fold-b", "目录B", "fold-root"),
}
f.folders["fold-b"] = []core.DriveFile{driveFile("f-doc", "文档.pdf", "fold-b", "200")}
items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("second sync error: %v", err)
}
moved, ok := fetchedByToken(items2)["f-doc"]
if !ok {
t.Fatalf("moved file not re-fetched on second sync: %+v", items2)
}
if moved.FileName != "团队资料/目录B/文档.pdf" {
t.Errorf("moved file FileName = %q, want 团队资料/目录B/文档.pdf (same external_id, new folder)", moved.FileName)
}
}
// TestDriveFetchIncremental_SingleFileSelectionSkipsFolderProbes anchors the
// sub-selection fix: a selected file's kind is read off the root subtree
// listing, so no folder meta/list API is ever called with the file token —
// probing used to fail with 91202/1061002 and log API errors on every sync.
func TestDriveFetchIncremental_SingleFileSelectionSkipsFolderProbes(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"fold-root": {driveFile("f-doc", "文档.docx", "fold-root", "100")},
})
c := NewDriveConnector(core.RegionFeishuDrive)
items, _, err := c.FetchIncremental(context.Background(), makeDriveConfig(f.cfg, []string{"fold-root:f-doc"}), nil)
if err != nil {
t.Fatalf("FetchIncremental() error: %v", err)
}
got := fetchedByToken(items)
if len(got) != 1 || got["f-doc"].FileName != "文档.docx" {
t.Fatalf("got %d items (%v), want exactly f-doc with its own name", len(got), got)
}
if f.listCalls["f-doc"] != 0 {
t.Errorf("folder list probed the file token %d time(s)", f.listCalls["f-doc"])
}
if f.metaCalls["f-doc"] != 0 {
t.Errorf("folder meta probed the file token %d time(s)", f.metaCalls["f-doc"])
}
}
// TestDriveFetchIncremental_SubFolderSelection pins the sub-folder semantics:
// only the selected subtree syncs, prefixed with the sub-folder's own name.
func TestDriveFetchIncremental_SubFolderSelection(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"fold-root": {
driveFolder("fold-spec", "规格", "fold-root"),
driveFile("f-root", "说明.pdf", "fold-root", "100"),
},
"fold-spec": {driveFile("f-spec", "详细.pdf", "fold-spec", "200")},
})
f.metaNames = map[string]string{"fold-spec": "规格"}
c := NewDriveConnector(core.RegionFeishuDrive)
items, _, err := c.FetchIncremental(
context.Background(), makeDriveConfig(f.cfg, []string{"fold-root:fold-spec"}), nil)
if err != nil {
t.Fatalf("FetchIncremental() error: %v", err)
}
got := fetchedByToken(items)
if len(got) != 1 {
t.Fatalf("got %d items (%v), want only the selected subtree", len(got), got)
}
if got["f-spec"].FileName != "规格/详细.pdf" {
t.Errorf("FileName for f-spec = %q, want %q", got["f-spec"].FileName, "规格/详细.pdf")
}
}
func TestDriveSubfolderDoesNotWalkUnselectedSiblings(t *testing.T) {
for _, nested := range []bool{false, true} {
t.Run(map[bool]string{false: "direct", true: "nested"}[nested], func(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"root": {
driveFolder("selected", "Selected", "root"), driveFolder("unselected", "Unselected", "root"),
},
"selected": {driveFile("doc", "doc.pdf", "selected", "100")},
})
if nested {
f.folders["root"] = []core.DriveFile{driveFolder("unselected", "Unselected", "root")}
}
f.metaNames = map[string]string{"root": "Root", "selected": "Selected"}
// A failure in an unrelated folder must not add retries or partial errors.
f.failing["unselected"] = true
conn := NewDriveConnector(core.RegionFeishuDrive)
cfg := makeDriveConfig(f.cfg, []string{"root:selected"})
items, cursor, err := conn.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatal(err)
}
if len(items) != 1 || items[0].FileName != "Root/Selected/doc.pdf" {
t.Fatalf("unexpected items: %+v", items)
}
if f.listCalls["unselected"] != 0 || f.listCalls["selected"] != 1 {
t.Fatalf("unexpected list calls: %v", f.listCalls)
}
f.folders["selected"] = nil
items, _, err = conn.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatal(err)
}
if ids := deletedIDs(items); len(ids) != 1 || ids[0] != "doc" {
t.Fatalf("selected deletion lost: %+v", items)
}
})
}
}
func TestDriveSelectionsShareShallowRootListing(t *testing.T) {
f := newFakeDriveTree(t, map[string][]core.DriveFile{
"root": {
driveFolder("a", "A", "root"), driveFolder("b", "B", "root"), driveFile("doc", "root.pdf", "root", "100"),
},
"a": {driveFile("doc-a", "a.pdf", "a", "100")},
"b": {driveFile("doc-b", "b.pdf", "b", "100")},
})
f.metaNames = map[string]string{"root": "Root"}
conn := NewDriveConnector(core.RegionFeishuDrive)
cfg := makeDriveConfig(f.cfg, []string{"root:a", "root:b", "root:doc"})
items, _, err := conn.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatal(err)
}
if len(items) != 3 {
t.Fatalf("items=%+v", items)
}
if f.listCalls["root"] != 1 || f.listCalls["a"] != 1 || f.listCalls["b"] != 1 || f.listCalls["doc"] != 0 {
t.Fatalf("unexpected calls: %v", f.listCalls)
}
}
func TestDriveSelectedShortcutKeepsDisplayNameAndTarget(t *testing.T) {
for _, selected := range []string{"shortcut", "target"} {
t.Run(selected, func(t *testing.T) {
var shortcut core.DriveFile
raw := `{"token":"shortcut","type":"shortcut","name":"reference.pdf","modified_time":"100",
"shortcut_info":{"target_token":"target","target_type":"file"}}`
if err := json.Unmarshal([]byte(raw), &shortcut); err != nil {
t.Fatal(err)
}
f := newFakeDriveTree(t, map[string][]core.DriveFile{"root": {shortcut}})
f.metaNames = map[string]string{"root": "Root"}
conn := NewDriveConnector(core.RegionFeishuDrive)
cfg := makeDriveConfig(f.cfg, []string{"root:" + selected})
items, _, err := conn.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatal(err)
}
if len(items) != 1 || items[0].ExternalID != "target" || items[0].FileName != "Root/reference.pdf" {
t.Fatalf("unexpected shortcut item: %+v", items)
}
if f.listCalls["target"] != 0 || f.listCalls["shortcut"] != 0 || f.listCalls["root"] != 1 {
t.Fatalf("shortcut must not trigger folder probes: %v", f.listCalls)
}
})
}
}
@@ -0,0 +1,42 @@
package drive
import (
"testing"
"time"
"academy/internal/datasource/connector/feishu/core"
)
// TestDriveCursorRoundTrip verifies driveOps.EncodeCursor/DecodeCursorTimes
// survive a JSON marshal/unmarshal cycle (snapshot isolation), mirroring the
// wiki TestFeishuCursorRoundTrip. Design §3.2: driveOps is new code that
// previously had no direct test.
func TestDriveCursorRoundTrip(t *testing.T) {
ops := driveOps{region: core.RegionFeishuDrive}
times := map[string]map[string]string{
"folder1": {"fdoc1": "100", "fdoc2": "200"},
"folder1:fdoc1": {"fdoc1": "100"},
"folder2:subA": {"fdoc3": "300"},
}
cur := ops.EncodeCursor(times, time.Unix(1000, 0))
if cur == nil {
t.Fatal("EncodeCursor returned nil")
}
got := ops.DecodeCursorTimes(cur.ConnectorCursor)
if len(got) != len(times) {
t.Fatalf("decoded %d resources, want %d", len(got), len(times))
}
for rid, files := range times {
gotFiles, ok := got[rid]
if !ok {
t.Errorf("resource %q missing from decoded cursor", rid)
continue
}
for tok, mt := range files {
if gotFiles[tok] != mt {
t.Errorf("decoded[%q][%q] = %q, want %q", rid, tok, gotFiles[tok], mt)
}
}
}
}
@@ -0,0 +1,417 @@
package drive
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync/atomic"
"testing"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/types"
)
// makeDriveConfig builds a DataSourceConfig for the Drive connector, mirroring
// makeConfig but with the drive connector type.
func makeDriveConfig(cfg *core.Config, resourceIDs []string) *types.DataSourceConfig {
c := makeConfig(cfg, resourceIDs)
c.Type = types.ConnectorTypeFeishuDrive
return c
}
// fakeFeishuDriveDocx serves the Drive list endpoint plus the docx blocks /
// media / export endpoints. blocksMode controls the blocks API behaviour:
// - "ok": serve the given blocks
// - "fail": HTTP 500 (missing scope) → exercises the export fallback
// - "empty": serve only a page block → empty Markdown → export fallback
//
// The export trio is always registered so both fallback modes can complete.
func fakeFeishuDriveDocx(t *testing.T, files []core.DriveFile, docToken string,
blocks []core.DocxBlock, blocksMode string, mediaContent []byte,
) (*httptest.Server, *core.Config) {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, core.TokenResponse{ApiResponse: core.ApiResponse{Code: 0}, TenantAccessToken: "fake-token", Expire: 7200})
})
// Drive file listing (single page).
mux.HandleFunc("/open-apis/drive/v1/files", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, core.DriveFileListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DriveFileListData{Files: files},
})
})
// Blocks API for the given docx document.
blocksPath := "/open-apis/docx/v1/documents/" + docToken + "/blocks"
switch blocksMode {
case "fail":
mux.HandleFunc(blocksPath, func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"code":99991400,"msg":"insufficient scope"}`))
})
case "empty":
mux.HandleFunc(blocksPath, func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.DocxBlocksResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DocxBlocksData{Items: []core.DocxBlock{{BlockID: "b1", BlockType: core.BlockTypePage}}},
})
})
default: // "ok"
mux.HandleFunc(blocksPath, func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.DocxBlocksResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DocxBlocksData{Items: blocks},
})
})
}
// Media download for File/Image block tokens.
mux.HandleFunc("/open-apis/drive/v1/medias/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/download") {
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write(mediaContent)
return
}
http.NotFound(w, r)
})
// Export trio for the fallback path.
mux.HandleFunc("/open-apis/drive/v1/export_tasks", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.ExportTaskCreateResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.ExportTaskCreateData{Ticket: "ticket-drv"},
})
})
mux.HandleFunc("/open-apis/drive/v1/export_tasks/ticket-drv", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.ExportTaskStatusResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.ExportTaskStatusData{
Result: core.ExportTaskResult{FileToken: "ft-export-drv", FileSize: 512, JobStatus: 0, FileName: "drive-fallback.docx"},
},
})
})
mux.HandleFunc("/open-apis/drive/v1/export_tasks/file/ft-export-drv/download", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write([]byte("fake-drive-export-binary"))
})
ts := httptest.NewServer(mux)
t.Cleanup(ts.Close)
return ts, &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL}
}
func driveDocxBlocks(attToken, attName string) []core.DocxBlock {
return []core.DocxBlock{
{BlockID: "b1", BlockType: core.BlockTypePage},
{BlockID: "b2", BlockType: core.BlockTypeText, Text: &core.BlockText{
Elements: []core.TextElement{{TextRun: &core.TextRun{Content: "Hello drive"}}},
}},
{BlockID: "b3", BlockType: core.BlockTypeFile, File: &core.BlockFileRef{Token: attToken, Name: attName}},
}
}
const driveDocxFileToken = "fdoc1"
func driveDocxFile() core.DriveFile {
return core.DriveFile{
Token: driveDocxFileToken,
Type: "docx",
Name: "Drive Doc",
ModifiedTime: "500",
ParentToken: "folder1",
URL: "https://example.feishu.cn/file/" + driveDocxFileToken,
}
}
// A drive docx goes through the blocks path: main Markdown item (external_id =
// file token, channel = feishu_drive) plus the attachment sub-item.
func TestDriveFetchStream_DocxBlocksMultiItem(t *testing.T) {
const (
attToken = "ft-drv-att"
attName = "report.pdf"
)
attContent := bytes.Repeat([]byte("x"), core.MinAttachmentBytes+1)
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken,
driveDocxBlocks(attToken, attName), "ok", attContent)
c := NewDriveConnector(core.RegionFeishuDrive)
h := &recordingHandler{}
_, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.emitted) != 2 {
t.Fatalf("expected 2 emitted items (attachment + main doc), got %d: %+v", len(h.emitted), h.emitted)
}
// P3 contract: sub-items are emitted BEFORE the parent document.
att := h.emitted[0]
wantAttID := driveDocxFileToken + "#file#" + attToken
if att.ExternalID != wantAttID {
t.Errorf("items[0].ExternalID = %q, want %q", att.ExternalID, wantAttID)
}
if att.Metadata["attachment"] != "true" {
t.Errorf("items[0].Metadata[attachment] = %q, want \"true\"", att.Metadata["attachment"])
}
if att.Metadata["parent_doc_id"] != driveDocxFileToken {
t.Errorf("items[0].Metadata[parent_doc_id] = %q, want %q", att.Metadata["parent_doc_id"], driveDocxFileToken)
}
main := h.emitted[1]
if main.ExternalID != driveDocxFileToken {
t.Errorf("items[1].ExternalID = %q, want %q", main.ExternalID, driveDocxFileToken)
}
if main.ContentType != "text/markdown" {
t.Errorf("items[1].ContentType = %q, want text/markdown", main.ContentType)
}
if !main.ReplacesSubtree {
t.Errorf("items[1].ReplacesSubtree = false, want true")
}
if main.Metadata["channel"] != types.ChannelFeishuDrive {
t.Errorf("items[1].Metadata[channel] = %q, want %q", main.Metadata["channel"], types.ChannelFeishuDrive)
}
if main.URL != "https://example.feishu.cn/file/"+driveDocxFileToken {
t.Errorf("items[1].URL = %q, want drive file URL passthrough", main.URL)
}
if !strings.Contains(string(main.Content), "Hello drive") {
t.Errorf("items[1].Content missing expected text; got %q", string(main.Content))
}
}
// Blocks API failure falls back to export: exactly one octet-stream item, no
// ReplacesSubtree (must not sweep good prior children on a transient failure).
func TestDriveFetchStream_DocxBlocksFailFallsBackToExport(t *testing.T) {
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, nil, "fail", nil)
c := NewDriveConnector(core.RegionFeishuDrive)
h := &recordingHandler{}
_, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.emitted) != 1 {
t.Fatalf("expected 1 emitted item (export fallback), got %d: %+v", len(h.emitted), h.emitted)
}
item := h.emitted[0]
if item.ExternalID != driveDocxFileToken {
t.Errorf("item.ExternalID = %q, want %q", item.ExternalID, driveDocxFileToken)
}
if item.ContentType != "application/octet-stream" {
t.Errorf("item.ContentType = %q, want application/octet-stream", item.ContentType)
}
if !strings.HasSuffix(item.FileName, ".docx") {
t.Errorf("item.FileName = %q, want .docx suffix", item.FileName)
}
if item.ReplacesSubtree {
t.Error("export-fallback item must not set ReplacesSubtree")
}
}
// Blocks rendering to empty Markdown also falls back to export (a blank page
// would otherwise ingest as a login-gated URL core.Fetch and fail).
func TestDriveFetchStream_DocxBlocksEmptyFallsBackToExport(t *testing.T) {
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, nil, "empty", nil)
c := NewDriveConnector(core.RegionFeishuDrive)
h := &recordingHandler{}
_, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.emitted) != 1 {
t.Fatalf("expected 1 emitted item (export fallback), got %d: %+v", len(h.emitted), h.emitted)
}
item := h.emitted[0]
if item.ContentType != "application/octet-stream" {
t.Errorf("item.ContentType = %q, want application/octet-stream", item.ContentType)
}
if item.ReplacesSubtree {
t.Error("export-fallback item must not set ReplacesSubtree")
}
}
// Image items are unconditional (not gated by the KB multimodal switch): the
// download produces a PNG sub-item, the parent's Markdown carries the numbered
// marker, and the external_id stays in SubtreeKeep.
func TestDriveFetchStream_DocxImageEmitted(t *testing.T) {
const imgToken = "img-drv-1"
blocks := []core.DocxBlock{
{BlockID: "b1", BlockType: core.BlockTypePage},
{BlockID: "b2", BlockType: core.BlockTypeText, Text: &core.BlockText{
Elements: []core.TextElement{{TextRun: &core.TextRun{Content: "has image"}}},
}},
{BlockID: "b3", BlockType: core.BlockTypeImage, Image: &core.BlockTokenRef{Token: imgToken}},
}
png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), core.MinAttachmentBytes)...)
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, blocks, "ok", png)
c := NewDriveConnector(core.RegionFeishuDrive)
h := &recordingHandler{}
_, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
// Orthodox flow: the image rides inline in the parent markdown as a base64
// data URI — one emitted item, no image sub-item, no image_map.
if len(h.emitted) != 1 {
t.Fatalf("expected 1 emitted item (main only), got %d: %+v", len(h.emitted), h.emitted)
}
main := h.emitted[0]
if main.ExternalID != driveDocxFileToken {
t.Errorf("main ExternalID = %q, want %q", main.ExternalID, driveDocxFileToken)
}
wantURI := "![图片](data:image/png;base64," + base64.StdEncoding.EncodeToString(png) + ")"
if !strings.Contains(string(main.Content), wantURI) {
t.Errorf("image not inlined as base64 data URI:\n%s", main.Content)
}
if main.Metadata["image_map"] != "" {
t.Errorf("image_map must be gone, got %q", main.Metadata["image_map"])
}
}
func TestDriveParseModeChangeRefetchesExistingDocument(t *testing.T) {
ts, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken,
driveDocxBlocks("", ""), "ok", nil)
defer ts.Close()
conf := makeDriveConfig(cfg, []string{"folder1"})
conf.Settings = map[string]interface{}{"parse_mode": "export"}
c := NewDriveConnector(core.RegionFeishu)
items, cursor, err := c.FetchIncremental(context.Background(), conf, nil)
if err != nil {
t.Fatal(err)
}
if len(items) != 1 {
t.Fatalf("initial sync: %d items", len(items))
}
for _, mode := range []string{"blocks", "export"} {
conf.Settings["parse_mode"] = mode
items, cursor, err = c.FetchIncremental(context.Background(), conf, cursor)
if err != nil {
t.Fatal(err)
}
if len(items) != 1 {
t.Fatalf("mode %s: want one refreshed document, got %d", mode, len(items))
}
items, _, err = c.FetchIncremental(context.Background(), conf, cursor)
if err != nil {
t.Fatal(err)
}
if len(items) != 0 {
t.Fatalf("unchanged mode %s unexpectedly refetched", mode)
}
}
}
// Image-heavy documents must take the native export path, whose ImageRefs do
// not have the Markdown data-URI count limit. In particular, no excess base64
// may be persisted as searchable document text.
func TestDriveImageBudgetFallsBackToNativeExport(t *testing.T) {
for _, count := range []int{types.MaxInlineDocumentImages, types.MaxInlineDocumentImages + 1, 61} {
t.Run(strconv.Itoa(count), func(t *testing.T) {
blocks := []core.DocxBlock{{BlockID: "page", BlockType: core.BlockTypePage}}
for i := 0; i < count; i++ {
blocks = append(blocks, core.DocxBlock{
BlockID: fmt.Sprintf("img%d", i), BlockType: core.BlockTypeImage,
Image: &core.BlockTokenRef{Token: "img"},
})
}
data := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), core.MinAttachmentBytes)...)
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, blocks, "ok", data)
items, err := core.FetchDocxWithBlocks(context.Background(), core.NewClient(cfg), core.DocxFetchInput{
DocToken: driveDocxFileToken, ObjToken: driveDocxFileToken, Title: "Images",
BaseMeta: map[string]string{}, ParseMode: core.ParseModeBlocks,
})
if err != nil {
t.Fatal(err)
}
if len(items) != 1 {
t.Fatalf("want one document, got %d", len(items))
}
if count <= types.MaxInlineDocumentImages {
if n := strings.Count(string(items[0].Content), "data:image/png;base64,"); n != count {
t.Fatalf("inline images=%d, want %d", n, count)
}
} else {
if !strings.HasSuffix(items[0].FileName, ".docx") ||
string(items[0].Content) != "fake-drive-export-binary" {
t.Fatalf("image-heavy document was not exported: %s", items[0].FileName)
}
if !items[0].ReplacesSubtree {
t.Fatal("complete blocks listing must retain attachment reconciliation")
}
}
})
}
}
func TestDriveImageBudgetPreservesAttachmentsAndExportFailures(t *testing.T) {
for _, failExport := range []bool{false, true} {
t.Run(strconv.FormatBool(failExport), func(t *testing.T) {
blocks := driveDocxBlocks("attachment", "report.pdf")
for i := 0; i < 61; i++ {
blocks = append(blocks, core.DocxBlock{
BlockID: fmt.Sprintf("img%d", i), BlockType: core.BlockTypeImage,
Image: &core.BlockTokenRef{Token: "img"},
})
}
ts, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken,
blocks, "ok", bytes.Repeat([]byte("pdf"), 1024))
handler := ts.Config.Handler
var mediaDownloads atomic.Int32
ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/medias/") {
mediaDownloads.Add(1)
}
if failExport && r.URL.Path == "/open-apis/drive/v1/export_tasks" {
writeJSON(w, core.ApiResponse{Code: 1, Msg: "export unavailable"})
return
}
handler.ServeHTTP(w, r)
})
items, err := core.FetchDocxWithBlocks(context.Background(), core.NewClient(cfg), core.DocxFetchInput{
DocToken: driveDocxFileToken, ObjToken: driveDocxFileToken, Title: "Images",
BaseMeta: map[string]string{}, ParseMode: core.ParseModeBlocks,
})
if failExport {
if err == nil || len(items) != 0 {
t.Fatalf("failed export must remain retryable: err=%v items=%d", err, len(items))
}
if mediaDownloads.Load() != 0 {
t.Fatal("media downloaded despite failed parent export")
}
return
}
if err != nil {
t.Fatal(err)
}
if len(items) != 2 {
t.Fatalf("want attachment and exported parent, got %d", len(items))
}
parent := items[1]
childID := types.SubtreeChildID(driveDocxFileToken, "file", "attachment")
if items[0].ExternalID != childID || items[0].Metadata["parent_doc_id"] != parent.ExternalID {
t.Fatal("lost attachment association")
}
if !parent.ReplacesSubtree || len(parent.SubtreeKeep) != 1 || parent.SubtreeKeep[0] != childID ||
!strings.Contains(parent.Metadata["attachment_ids"], childID) {
t.Fatalf("lost attachment keep list: %+v", parent)
}
if mediaDownloads.Load() != 1 {
t.Fatalf("want only attachment download, got %d", mediaDownloads.Load())
}
})
}
}
@@ -0,0 +1,61 @@
package drive
import (
"context"
"encoding/json"
"net/http"
"os"
"testing"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/types"
secutils "academy/internal/utils"
)
func TestMain(m *testing.M) {
os.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
secutils.ResetSSRFWhitelistForTest()
os.Exit(m.Run())
}
func writeJSON(w http.ResponseWriter, v interface{}) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(v)
}
func makeConfig(cfg *core.Config, resourceIDs []string) *types.DataSourceConfig {
creds := map[string]interface{}{
"app_id": cfg.AppID,
"app_secret": cfg.AppSecret,
"base_url": cfg.BaseURL,
}
return &types.DataSourceConfig{
Type: types.ConnectorTypeFeishu,
Credentials: creds,
ResourceIDs: resourceIDs,
}
}
type recordingHandler struct {
emitted []types.FetchedItem
checkpoints []core.FeishuDriveCursor
emitErr func(item types.FetchedItem) error
}
func (h *recordingHandler) Emit(_ context.Context, item types.FetchedItem) error {
if h.emitErr != nil {
if err := h.emitErr(item); err != nil {
return err
}
}
h.emitted = append(h.emitted, item)
return nil
}
func (h *recordingHandler) Checkpoint(_ context.Context, cursor *types.SyncCursor) error {
var fc core.FeishuDriveCursor
b, _ := json.Marshal(cursor.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
h.checkpoints = append(h.checkpoints, fc)
return nil
}
@@ -0,0 +1,145 @@
package drive
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"sync/atomic"
"testing"
"time"
"academy/internal/datasource/connector/feishu/core"
)
// TestClientDriveListFilesPagination is the Drive (云盘) counterpart of the wiki
// test added in #3645 (TestClientWikiPaginationRejectsRepeatedPageToken):
// ListDriveFilesAllPages used to stop only on an empty next_page_token, so a
// repeated token (or has_more=false with a stale token) made it re-request the
// same page forever. Each case runs under a short deadline so a regression
// fails fast instead of hanging the suite.
func TestClientDriveListFilesPagination(t *testing.T) {
tests := []struct {
name string
response func(page int) core.DriveFileListResponse
wantErr string
wantRequests int
wantFiles []string
}{
{
// Feishu can hand back has_more=true with a token it already
// returned; that is exactly what #3645 hit on the wiki endpoints.
name: "repeated page token",
response: func(page int) core.DriveFileListResponse {
return core.DriveFileListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DriveFileListData{
Files: []core.DriveFile{{Token: fmt.Sprintf("file-%d", page)}},
HasMore: true,
NextPageToken: "repeated-token",
},
}
},
wantErr: "repeated page token",
wantRequests: 2,
},
{
// has_more=false is the authoritative stop signal: a residual
// non-empty token must not trigger another round trip.
name: "has_more false with stale token",
response: func(int) core.DriveFileListResponse {
return core.DriveFileListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DriveFileListData{
Files: []core.DriveFile{{Token: "file-1"}},
HasMore: false,
NextPageToken: "stale-token",
},
}
},
wantRequests: 1,
wantFiles: []string{"file-1"},
},
{
// The guard must not truncate a genuinely paginated folder.
name: "two real pages are still merged",
response: func(page int) core.DriveFileListResponse {
if page == 1 {
return core.DriveFileListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DriveFileListData{
Files: []core.DriveFile{{Token: "file-1"}},
HasMore: true,
NextPageToken: "token-2",
},
}
}
return core.DriveFileListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.DriveFileListData{
Files: []core.DriveFile{{Token: "file-2"}},
HasMore: false,
NextPageToken: "",
},
}
},
wantRequests: 2,
wantFiles: []string{"file-1", "file-2"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mux := http.NewServeMux()
authPath := "/open-apis/auth/v3/tenant_access_token/internal"
mux.HandleFunc(authPath, func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, core.TokenResponse{
ApiResponse: core.ApiResponse{Code: 0},
TenantAccessToken: "fake-token",
Expire: 7200,
})
})
var requests atomic.Int64
mux.HandleFunc("/open-apis/drive/v1/files", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, tt.response(int(requests.Add(1))))
})
ts := httptest.NewServer(mux)
defer ts.Close()
client := core.NewClient(&core.Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL})
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
files, err := client.ListDriveFilesAllPages(ctx, "folder1")
if ctx.Err() != nil {
t.Fatalf("pagination never terminated (requests=%d, err=%v)", requests.Load(), err)
}
if tt.wantErr == "" {
if err != nil {
t.Fatalf("ListDriveFilesAllPages() error = %v, want nil", err)
}
} else if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("ListDriveFilesAllPages() error = %v, want error containing %q", err, tt.wantErr)
}
if got := int(requests.Load()); got != tt.wantRequests {
t.Fatalf("drive list requests = %d, want %d", got, tt.wantRequests)
}
gotFiles := make([]string, 0, len(files))
seen := make(map[string]bool, len(files))
for _, f := range files {
if seen[f.Token] {
t.Fatalf("file token %q was appended more than once", f.Token)
}
seen[f.Token] = true
gotFiles = append(gotFiles, f.Token)
}
if tt.wantFiles != nil && !reflect.DeepEqual(gotFiles, tt.wantFiles) {
t.Fatalf("files = %v, want %v", gotFiles, tt.wantFiles)
}
})
}
}
@@ -0,0 +1,158 @@
package drive
import (
"context"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/logger"
"academy/internal/types"
)
// This file implements the P1 directory mapping for the Drive connector:
// FetchedItem.FileName becomes "<根文件夹名>/<子目录...>/<文件名>" rooted at
// the selected sync root's own display name (the root folder = a top-level KB
// folder) so ingestion's types.SplitKnowledgeRelativePath derives the KB
// folder_path. The recursive
// walk itself is core.WalkDriveTree (the Drive connector's single walker,
// shared with core): DFS order, shortcut expansion, partial-failure
// aggregation — plus a folder-token → cleaned directory path table built in
// the same pass, so no extra API calls are made. This file only resolves the
// per-resource root and feeds the walk results into Fetch.
// driveFolderName resolves a folder's display name via GetDriveFolderMeta,
// one call per token per sync run (cached on success only — a failure is not
// cached, so the next resource in the same run retries). resolved is false
// when the meta call failed or returned no name — that folder's path prefix
// segment (root or sub-folder) is then skipped.
func (o *driveOps) driveFolderName(
ctx context.Context, client *core.Client, folderToken string,
) (name string, resolved bool) {
if o.folderNames == nil {
o.folderNames = make(map[string]string)
}
if name, ok := o.folderNames[folderToken]; ok {
return name, true
}
meta, err := client.GetDriveFolderMeta(ctx, folderToken)
if err != nil {
logger.Warnf(ctx, "[FeishuDrive] resolve folder name for %s: %v (falling back)", folderToken, err)
return "", false
}
if meta.Data.Name == "" {
return "", false
}
name = core.SanitizeFileName(meta.Data.Name)
o.folderNames[folderToken] = name
return name, true
}
// listDriveFilesForResource lists the files to sync for a resourceID and
// records the directory-path table for Fetch. A resourceID is either a bare
// rootFolderToken (sync the whole subtree) or "rootFolderToken:fileToken"
// (sync a single selected file or sub-folder). Every walk is rooted at the
// root folder's own display name, so the synced folder appears as a top-level
// KB folder holding its subtree (an unresolved root name falls back to no
// prefix, mirroring pre-root-mirror behaviour).
func (o *driveOps) listDriveFilesForResource(
ctx context.Context, client *core.Client, resourceID string,
) ([]core.DriveFile, error) {
rootFolderToken, fileToken := parseDriveResourceID(resourceID)
rootBase := ""
if rootName, ok := o.driveFolderName(ctx, client, rootFolderToken); ok {
rootBase = rootName
}
if fileToken == "" {
// The selected root folder maps to a top-level KB folder named after
// it: documents directly under it land in folder_path "<根名>".
files, dirPaths, failures := core.WalkDriveTree(ctx, client, rootFolderToken, rootBase)
o.dirPaths = dirPaths
return files, partialDriveError(failures)
}
// A shallow root listing identifies direct files without probing them with
// folder APIs, and direct folders without visiting unselected siblings.
if o.rootEntries == nil {
o.rootEntries = make(map[string][]core.DriveFile)
}
entries, cached := o.rootEntries[rootFolderToken]
if !cached {
if listed, err := client.ListDriveFilesAllPages(ctx, rootFolderToken); err == nil {
entries = listed
o.rootEntries[rootFolderToken] = listed
}
}
base := rootBase
folderFound := false
for _, entry := range entries {
f, ok := core.ExpandDriveShortcut(entry)
if !ok || (entry.Token != fileToken && f.Token != fileToken) {
continue
}
if f.Type != "folder" {
// Some list responses omit parent_token; the listing itself tells
// us the containing directory.
f.ParentToken = rootFolderToken
o.dirPaths = map[string]string{rootFolderToken: rootBase}
return []core.DriveFile{f}, nil
}
folderFound = true
base = joinDriveDir(rootBase, core.SanitizeFileName(f.Name))
break
}
if !folderFound {
// A nested selected folder can be walked directly, even when the
// caller cannot list its parent. No full-root discovery is needed.
if subName, ok := o.driveFolderName(ctx, client, fileToken); ok {
base = joinDriveDir(rootBase, subName)
}
}
files, dirPaths, failures := core.WalkDriveTree(ctx, client, fileToken, base)
for _, failure := range failures {
if failure.FolderToken == fileToken && isDriveNotFolderError(failure.Err) {
// Only nested single files need the legacy root search: Drive
// exposes no single-file parent query. Never use this fallback for
// permission/transport failures, which must retain the old cursor.
rootFiles, rootDirs, rootFailures := core.WalkDriveTree(ctx, client, rootFolderToken, rootBase)
o.dirPaths = rootDirs
return filterDriveFileByToken(rootFiles, fileToken), partialDriveError(rootFailures)
}
}
o.dirPaths = dirPaths
return files, partialDriveError(failures)
}
func joinDriveDir(parent, name string) string {
if parent == "" {
return name
}
if name == "" {
return parent
}
return parent + "/" + name
}
// partialDriveError wraps collected failures into a
// *core.PartialDriveFileListError (nil when there are none).
func partialDriveError(failures []core.DriveFileListFailure) error {
if len(failures) == 0 {
return nil
}
return &core.PartialDriveFileListError{Failures: failures}
}
// qualifyItemFileNames prefixes every fetched item's FileName with dir so
// ingestion derives the KB folder path. The prefix applies to the main item
// and to attachment/image sub-items alike — they all live in the same folder.
// An empty dir (parent folder not in the current walk) or FileName is untouched.
func qualifyItemFileNames(items []*types.FetchedItem, dir string) {
if dir == "" {
return
}
for _, it := range items {
if it != nil && it.FileName != "" {
it.FileName = dir + "/" + it.FileName
}
}
}
@@ -0,0 +1,598 @@
package wiki
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"time"
"academy/internal/datasource"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/logger"
"academy/internal/types"
)
// Connector implements the datasource.Connector interface for Feishu and, with
// the same code, for Lark: the two clouds expose an identical wiki/docx/drive
// API surface. A core.Region picks the cloud — see region.go.
type Connector struct {
region core.Region
}
// NewConnector creates a connector for the given region (RegionFeishu or RegionLark).
func NewConnector(region core.Region) *Connector {
return &Connector{region: region}
}
// Feishu supports resumable streaming sync; the service prefers FetchStream over
// FetchAll/FetchIncremental when a connector implements StreamingConnector.
var _ datasource.StreamingConnector = (*Connector)(nil)
var _ datasource.FullStreamingConnector = (*Connector)(nil)
// Type returns the connector type identifier.
func (c *Connector) Type() string {
return c.region.ConnectorType
}
// Validate verifies that the Feishu configuration is valid by testing connectivity.
func (c *Connector) Validate(ctx context.Context, config *types.DataSourceConfig) error {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return err
}
client := core.NewClient(feishuConfig)
if err := client.Ping(ctx); err != nil {
return fmt.Errorf("feishu connection failed: %w", err)
}
return nil
}
// ListResources lists Feishu Wiki resources for selection, loading the tree
// lazily one level at a time to avoid traversing the entire wiki up front.
//
// - parentID == "" → list all accessible wiki spaces.
// - parentID == spaceID → list the top-level nodes of that space.
// - parentID == "spaceID:nodeToken" → list the direct children of that node.
//
// Eagerly recursing the whole tree here used to time out for large wikis
// (Tencent/WeKnora#1672); the recursive walk now happens only at sync time.
func (c *Connector) ListResources(
ctx context.Context, config *types.DataSourceConfig, parentID string,
) ([]types.Resource, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
if parentID == "" {
spaces, err := client.ListWikiSpaces(ctx)
if err != nil {
return nil, fmt.Errorf("list feishu wiki spaces: %w", err)
}
resources := make([]types.Resource, 0, len(spaces))
for _, space := range spaces {
resources = append(resources, types.Resource{
ExternalID: space.SpaceID,
Name: space.Name,
Type: "wiki_space",
Description: space.Description,
URL: c.region.WikiURL(space.SpaceID),
HasChildren: true,
Metadata: map[string]interface{}{
"visibility": space.Visibility,
"space_id": space.SpaceID,
},
})
}
return resources, nil
}
// Lazy load: list only the direct children of the given space / node.
spaceID, nodeToken := parseWikiResourceID(parentID)
nodes, err := client.ListWikiNodes(ctx, spaceID, nodeToken)
if err != nil {
return nil, fmt.Errorf("list feishu wiki nodes under %s: %w", parentID, err)
}
resources := make([]types.Resource, 0, len(nodes))
for _, node := range nodes {
resources = append(resources, c.wikiNodeToResource(spaceID, node))
}
return resources, nil
}
// ResolveResourceAncestors returns the resource IDs of every parent that has to
// be expanded so the lazily-loaded picker can reveal each given selection. For a
// selected node "spaceID:nodeToken" that is its space plus every intermediate
// node up the tree; the walk uses GetWikiNode (parent_node_token) and is O(depth)
// per selection, so it never re-traverses the whole wiki.
func (c *Connector) ResolveResourceAncestors(
ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,
) ([]string, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
seen := make(map[string]bool)
ancestors := make([]string, 0)
add := func(id string) {
if id != "" && !seen[id] {
seen[id] = true
ancestors = append(ancestors, id)
}
}
for _, rid := range resourceIDs {
spaceID, nodeToken := parseWikiResourceID(rid)
if spaceID == "" || nodeToken == "" {
// A space-level selection is already a top-level node in the picker;
// there is nothing above it to reveal.
continue
}
// The space's direct children must be loaded to reveal the top-level node.
add(spaceID)
// Walk up from the selection to the top, loading each intermediate
// parent so the path down to the selection becomes visible.
current := nodeToken
for current != "" {
node, err := client.GetWikiNode(ctx, spaceID, current)
if err != nil {
// Best-effort: a broken path just stays collapsed, the rest of
// the selections are still revealed.
logger.Warnf(ctx, "[Feishu] resolve ancestors: get node %s:%s: %v", spaceID, current, err)
break
}
if node.ParentNodeID == "" {
break
}
add(makeWikiNodeResourceID(spaceID, node.ParentNodeID))
current = node.ParentNodeID
}
}
return ancestors, nil
}
// FetchAll performs a full sync of all documents from the specified wiki spaces.
// Defensive fallback path - the service prefers FetchStream when the connector
// implements StreamingConnector.
func (c *Connector) FetchAll(ctx context.Context, config *types.DataSourceConfig, resourceIDs []string) ([]types.FetchedItem, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
return core.FetchAllEngine(ctx, client, config, resourceIDs,
&wikiOps{region: c.region, parseMode: feishuConfig.ParseMode})
}
// FetchIncremental performs an incremental sync by comparing node edit times
// against the previously recorded state. Defensive fallback path - the service
// prefers FetchStream. Routed through the same engine, so the #2136
// failure-doesn't-advance-cursor semantics apply here too (previously this path
// advanced the cursor before fetching, a latent #2136 bug).
func (c *Connector) FetchIncremental(ctx context.Context, config *types.DataSourceConfig, cursor *types.SyncCursor) ([]types.FetchedItem, *types.SyncCursor, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, nil, err
}
client := core.NewClient(feishuConfig)
ops := &wikiOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchIncrementalEngine(ctx, client, config, cursor, ops)
}
// FetchStream performs a resumable, memory-bounded sync. It unifies the full
// and incremental paths: with cursor == nil it fetches everything, and with a
// cursor it skips nodes whose recorded edit time is unchanged - the same
// mechanism that lets a sync which timed out mid-traversal resume from the last
// checkpoint instead of restarting (Tencent/WeKnora#2136).
//
// The per-node loop lives in the shared engine (engine.go); this shell only
// wires the wiki NodeOps adapter.
func (c *Connector) FetchStream(
ctx context.Context, config *types.DataSourceConfig,
cursor *types.SyncCursor, h datasource.StreamHandler,
) (*types.SyncCursor, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
ops := &wikiOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchStreamEngine(ctx, client, config, cursor, h, ops)
}
// FetchFullStream refetches content without discarding the deletion baseline.
func (c *Connector) FetchFullStream(
ctx context.Context, config *types.DataSourceConfig,
cursor *types.SyncCursor, h datasource.StreamHandler,
) (*types.SyncCursor, error) {
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
if err != nil {
return nil, err
}
client := core.NewClient(feishuConfig)
ops := &wikiOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchFullStreamEngine(ctx, client, config, cursor, h, ops)
}
// wikiOps adapts the wiki Connector to the generic sync engine. It carries the
// region (for URL rendering), encodes/decodes the wiki cursor wire format
// (core.FeishuCursor / space_node_times), and holds the per-run directory
// mapping state (P1): dirPaths maps node token → cleaned directory prefix
// rooted at the space's own name, so every synced space lands in a top-level
// KB folder named after the space. List builds the state for the resource
// being synced; Fetch reads it. runSync processes one resource at a time, so
// the mutation is race-free.
type wikiOps struct {
region core.Region
parseMode string
dirPaths map[string]string
// spacePrefixes caches spaceID → sanitized folder prefix for the run, so
// syncing K selected spaces costs one ListWikiSpaces paging pass total
// instead of one per space (failures cache "" and do not retry mid-run).
spacePrefixes map[string]string
}
// spaceDirPrefix resolves the synced space's display name (sanitized) as the
// top-level KB folder for this run, cached per space for the whole run.
// An unresolved name yields "" and the documents fall back to landing at the
// KB root (pre-mirror behaviour) rather than failing the sync.
func (o *wikiOps) spaceDirPrefix(ctx context.Context, client *core.Client, spaceID string) string {
if o.spacePrefixes == nil {
o.spacePrefixes = make(map[string]string)
}
if prefix, ok := o.spacePrefixes[spaceID]; ok {
return prefix
}
prefix := ""
spaces, err := client.ListWikiSpaces(ctx)
if err != nil {
logger.Warnf(ctx, "[Feishu] list wiki spaces for space folder prefix %s: %v", spaceID, err)
} else {
for _, s := range spaces {
if s.SpaceID == spaceID && s.Name != "" {
prefix = core.SanitizeFileName(s.Name)
break
}
}
}
o.spacePrefixes[spaceID] = prefix
return prefix
}
func (o *wikiOps) List(ctx context.Context, client *core.Client, resourceID string) ([]core.WikiNode, error, error) {
spaceID, nodeToken := parseWikiResourceID(resourceID)
nodes, err := client.ListWikiNodesWithShortcuts(ctx, spaceID, nodeToken)
if err != nil {
var partial *core.PartialWikiNodeListError
if !errors.As(err, &partial) {
// Total listing failure: nothing usable — abort the sync.
return nodes, nil, err
}
// Partial listing: nodes are still usable; the failed sub-trees are
// surfaced via ListFailureItems, and the sync continues.
}
// On a partial listing the original's descendants may be missing even
// when the original node itself is present. Keep the accessible shortcut.
if err == nil {
nodes = filterShortcutSubtrees(nodes)
}
o.prepareDirPaths(nodes, o.spaceDirPrefix(ctx, client, spaceID))
if err != nil {
return nodes, err, nil
}
return nodes, nil, nil
}
func (o *wikiOps) Token(n core.WikiNode) string { return n.NodeToken }
func (o *wikiOps) Title(n core.WikiNode) string { return n.Title }
func (o *wikiOps) ObjType(n core.WikiNode) string { return n.ObjType }
// EditTime is an opaque change key including the effective destination path.
// An ancestor rename/move changes that path without touching this node's times.
// Timestamp-only legacy cursors refresh once; source_updated_at still uses
// contentEditTime and never contains the path fingerprint.
func (o *wikiOps) EditTime(n core.WikiNode) string {
timestamp := core.DocxChangeKey(wikiNodeEditTime(n), n.ObjType, o.parseMode)
if dir, ok := o.dirPaths[n.NodeToken]; ok {
pathHash := sha256.Sum256([]byte(dir + "\x00" + core.SanitizeFileName(n.Title)))
return fmt.Sprintf("%s:%x", timestamp, pathHash)
}
return timestamp
}
func wikiNodeEditTime(n core.WikiNode) string {
obj, objErr := strconv.ParseInt(n.ObjEditTime, 10, 64)
node, nodeErr := strconv.ParseInt(n.NodeEditTime, 10, 64)
switch {
case objErr != nil && nodeErr != nil:
return n.ObjEditTime
case objErr != nil:
return n.NodeEditTime
case nodeErr != nil:
return n.ObjEditTime
case node > obj:
return n.NodeEditTime
default:
return n.ObjEditTime
}
}
func (o *wikiOps) Fetch(
ctx context.Context, client *core.Client, n core.WikiNode, resourceID string,
) ([]*types.FetchedItem, error) {
spaceID, _ := parseWikiResourceID(resourceID)
if n.SpaceID != "" {
spaceID = n.SpaceID
}
items, err := fetchNodeContent(ctx, client, n, spaceID, resourceID, o.region, o.parseMode)
if err != nil {
return nil, err
}
// P1 directory mapping: prefix the FileName with the node's cleaned
// directory path so ingestion derives the KB folder_path from it.
qualifyItemFileNames(items, o.dirPaths[n.NodeToken])
return items, nil
}
func (o *wikiOps) ListFailureItems(resourceID string, partial error) []types.FetchedItem {
spaceID, _ := parseWikiResourceID(resourceID)
var pe *core.PartialWikiNodeListError
if errors.As(partial, &pe) {
return appendWikiNodeListFailureItems(nil, spaceID, resourceID, pe.Failures)
}
return nil
}
func (o *wikiOps) ResourceNoun() string { return "nodes" }
func (o *wikiOps) EmptyResourceIDsError() string {
return "no resource IDs (wiki space IDs or wiki node IDs) configured"
}
func (o *wikiOps) LogTag() string { return "[Feishu]" }
func (o *wikiOps) DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string {
var prev core.FeishuCursor
b, _ := json.Marshal(m)
_ = json.Unmarshal(b, &prev)
return prev.SpaceNodeTimes
}
func (o *wikiOps) EncodeCursor(times map[string]map[string]string, lastSync time.Time) *types.SyncCursor {
fc := core.FeishuCursor{LastSyncTime: lastSync, SpaceNodeTimes: times}
m := make(map[string]interface{})
b, _ := json.Marshal(fc)
_ = json.Unmarshal(b, &m)
return &types.SyncCursor{LastSyncTime: lastSync, ConnectorCursor: m}
}
func appendWikiNodeListFailureItems(items []types.FetchedItem, spaceID string, resourceID string, failures []core.WikiNodeListFailure) []types.FetchedItem {
for _, failure := range failures {
node := failure.Node
nodeSpaceID := node.SpaceID
if nodeSpaceID == "" {
nodeSpaceID = spaceID
}
title := node.Title
if title == "" {
title = node.NodeToken
}
items = append(items, types.FetchedItem{
ExternalID: node.NodeToken,
Title: title,
SourceResourceID: resourceID,
Metadata: core.FeishuErrorItemMeta(failure.Err, map[string]string{
"channel": types.ChannelFeishu,
"node_token": node.NodeToken,
"space_id": nodeSpaceID,
"failure_stage": "list_children",
}),
})
}
return items
}
// 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 fetchNodeContent(
ctx context.Context, client *core.Client, node core.WikiNode,
spaceID string, resourceID string, region core.Region, parseMode string,
) ([]*types.FetchedItem, error) {
if !core.IsSupportedDocType(node.ObjType) {
return nil, nil
}
editTime := contentEditTime(node)
createTime := contentCreateTime(node)
baseMeta := map[string]string{
"obj_token": node.ObjToken,
"obj_type": node.ObjType,
"node_token": node.NodeToken,
"space_id": spaceID,
"creator": node.Creator,
"owner": node.Owner,
"channel": types.ChannelFeishu,
}
switch node.ObjType {
case "docx":
return core.FetchDocxWithBlocks(ctx, client, core.DocxFetchInput{
DocToken: node.NodeToken,
ObjToken: node.ObjToken,
Title: node.Title,
URL: region.WikiURL(node.NodeToken),
ResourceID: resourceID,
EditTime: editTime,
CreateTime: createTime,
ParseMode: parseMode,
BaseMeta: baseMeta,
})
case "doc", "sheet", "bitable":
item, err := fetchViaExport(ctx, client, node, resourceID, editTime, baseMeta, region)
if err != nil {
return nil, err
}
item.CreatedAt = createTime
return []*types.FetchedItem{item}, nil
case "file":
item, err := fetchDriveFile(ctx, client, node, resourceID, editTime, baseMeta, region)
if err != nil {
return nil, err
}
item.CreatedAt = createTime
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 fetchViaExport(ctx context.Context, client *core.Client, node core.WikiNode, resourceID string, editTime time.Time, baseMeta map[string]string, region core.Region) (*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 := core.ExportFileExtToSuffix[core.ObjTypeToExportFileExtension[node.ObjType]]
if fileName == "" {
fileName = core.SanitizeFileName(node.Title) + ext
} else if !strings.HasSuffix(strings.ToLower(fileName), ext) {
// Feishu often returns the doc title without extension - append it
fileName = core.SanitizeFileName(fileName) + ext
}
return &types.FetchedItem{
ExternalID: node.NodeToken,
Title: node.Title,
Content: data,
ContentType: "application/octet-stream",
FileName: fileName,
URL: 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 fetchDriveFile(ctx context.Context, client *core.Client, node core.WikiNode, resourceID string, editTime time.Time, baseMeta map[string]string, region core.Region) (*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 := core.SanitizeFileName(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: region.WikiURL(node.NodeToken),
UpdatedAt: editTime,
SourceResourceID: resourceID,
Metadata: baseMeta,
}, nil
}
// contentEditTime is the document's last content edit time (obj_edit_time),
// falling back to the node attribute edit time when Feishu omits it. It is
// what ingestion persists as source_updated_at; NodeEditTime alone would move
// on a rename or a move in the tree without any content change.
func contentEditTime(node core.WikiNode) time.Time {
if t := core.ParseFeishuTimestamp(node.ObjEditTime); !t.IsZero() {
return t
}
return core.ParseFeishuTimestamp(node.NodeEditTime)
}
// contentCreateTime is the document creation time (obj_create_time), falling
// back to the node creation time. Persisted as source_created_at.
func contentCreateTime(node core.WikiNode) time.Time {
if t := core.ParseFeishuTimestamp(node.ObjCreateTime); !t.IsZero() {
return t
}
return core.ParseFeishuTimestamp(node.NodeCreateTime)
}
// --- Helper functions ---
func makeWikiNodeResourceID(spaceID, nodeToken string) string {
return spaceID + core.FeishuWikiNodeResourceSeparator + nodeToken
}
func parseWikiResourceID(resourceID string) (spaceID string, nodeToken string) {
spaceID, nodeToken, _ = strings.Cut(resourceID, core.FeishuWikiNodeResourceSeparator)
return spaceID, nodeToken
}
func (c *Connector) wikiNodeToResource(spaceID string, node core.WikiNode) types.Resource {
parentID := spaceID
if node.ParentNodeID != "" {
parentID = makeWikiNodeResourceID(spaceID, node.ParentNodeID)
}
name := node.Title
if name == "" {
name = node.NodeToken
}
modifiedAt := core.ParseFeishuTimestamp(node.ObjEditTime)
if modifiedAt.IsZero() {
modifiedAt = core.ParseFeishuTimestamp(node.NodeEditTime)
}
return types.Resource{
ExternalID: makeWikiNodeResourceID(spaceID, node.NodeToken),
Name: name,
Type: "wiki_node",
URL: c.region.WikiURL(node.NodeToken),
ParentID: parentID,
HasChildren: node.HasChild,
ModifiedAt: modifiedAt,
Metadata: map[string]interface{}{
"space_id": spaceID,
"node_token": node.NodeToken,
"obj_token": node.ObjToken,
"obj_type": node.ObjType,
},
}
}
@@ -0,0 +1,267 @@
package wiki
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/types"
)
// statefulFeishu is a fake Feishu server whose per-node export outcome can be
// changed between sync passes. A node whose obj_token is in failTokens has its
// export status poll return a failed job, so fetchNodeContent errors for it —
// modelling a transient rate-limit / export failure that later recovers.
type statefulFeishu struct {
mu sync.Mutex
failTokens map[string]bool
}
func (s *statefulFeishu) setFail(tokens ...string) {
s.mu.Lock()
defer s.mu.Unlock()
s.failTokens = map[string]bool{}
for _, t := range tokens {
s.failTokens[t] = true
}
}
func (s *statefulFeishu) shouldFail(token string) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.failTokens[token]
}
func newStatefulFeishu(nodes []core.WikiNode) (*httptest.Server, *core.Config, *statefulFeishu) {
s := &statefulFeishu{failTokens: map[string]bool{}}
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.TokenResponse{ApiResponse: core.ApiResponse{Code: 0}, TenantAccessToken: "fake-token", Expire: 7200})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiSpaceListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiSpaceListData{Items: []core.WikiSpace{{SpaceID: "space1", Name: "Test Space"}}},
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiNodeListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiNodeListData{Items: nodes},
})
})
// Export create: ticket == obj_token so the poll below can key on it.
mux.HandleFunc("/open-apis/drive/v1/export_tasks", func(w http.ResponseWriter, r *http.Request) {
var body struct {
Token string `json:"token"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
writeJSON(w, core.ExportTaskCreateResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.ExportTaskCreateData{Ticket: body.Token},
})
})
// Export status poll: /open-apis/drive/v1/export_tasks/<ticket>?token=<objToken>
mux.HandleFunc("/open-apis/drive/v1/export_tasks/", func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/file/") && strings.HasSuffix(r.URL.Path, "/download") {
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write([]byte("fake-docx-content"))
return
}
token := r.URL.Query().Get("token")
status := 0
if s.shouldFail(token) {
status = 3 // failed job
}
resp := core.ExportTaskStatusResponse{ApiResponse: core.ApiResponse{Code: 0}}
resp.Data.Result.FileToken = "file-" + token
resp.Data.Result.FileName = "exported.docx"
resp.Data.Result.JobStatus = status
resp.Data.Result.JobErrorMsg = "rate limited"
writeJSON(w, resp)
})
ts := httptest.NewServer(mux)
return ts, &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL}, s
}
// convergenceHandler models the service side across a resumable sync:
// - Emit ingests content items (mirroring the service's ctx check + apply),
// records failure items separately, and can simulate a mid-tree task timeout
// by canceling the run's context after cancelAfterCalls Emit calls.
// - Checkpoint snapshots the connector cursor (the DB round-trip).
type convergenceHandler struct {
ingested []string // ExternalIDs of successfully ingested content items
failed []string // ExternalIDs surfaced as failures (Metadata["error"])
exportedTokens map[string]int
checkpoints []core.FeishuCursor
calls int
cancelAfterCall int // >0: cancel ctx and abort on the Nth Emit call
cancel context.CancelFunc
}
func (h *convergenceHandler) Emit(ctx context.Context, item types.FetchedItem) error {
if err := ctx.Err(); err != nil { // mirror service Emit
return err
}
h.calls++
if h.cancelAfterCall > 0 && h.calls >= h.cancelAfterCall {
if h.cancel != nil {
h.cancel()
}
return context.Canceled // service returns ctx err → connector aborts
}
if item.Metadata["error"] != "" {
h.failed = append(h.failed, item.ExternalID)
return nil
}
h.ingested = append(h.ingested, item.ExternalID)
return nil
}
func (h *convergenceHandler) Checkpoint(ctx context.Context, cursor *types.SyncCursor) error {
var fc core.FeishuCursor
b, _ := json.Marshal(cursor.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
h.checkpoints = append(h.checkpoints, fc)
return nil
}
func lastCheckpointCursor(h *convergenceHandler, t *testing.T) *types.SyncCursor {
t.Helper()
if len(h.checkpoints) == 0 {
return nil
}
last := h.checkpoints[len(h.checkpoints)-1]
b, _ := json.Marshal(last)
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
t.Fatalf("rebuild persisted cursor: %v", err)
}
return &types.SyncCursor{ConnectorCursor: m}
}
// TestFetchStream_ResumeConvergesAfterTimeoutAndTransientFailure is the
// end-to-end proof for Tencent/WeKnora#2136: a large-ish wiki that (a) hits a
// transient per-node export failure and (b) is killed by the 2h task timeout
// mid-traversal must, on the asynq retry, resume from the last Checkpoint,
// re-core.Fetch only what is outstanding, retry the transiently-failed node, and end
// with EVERY document synced exactly once — no permanent core.Skip, no full restart,
// no redundant re-export of already-done nodes.
func TestFetchStream_ResumeConvergesAfterTimeoutAndTransientFailure(t *testing.T) {
// Checkpoint on every processed node so the persisted cursor is precise.
prevN := core.FeishuStreamCheckpointInterval
core.FeishuStreamCheckpointInterval = 1
defer func() { core.FeishuStreamCheckpointInterval = prevN }()
nodes := []core.WikiNode{
{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc1", ObjEditTime: "100"},
{NodeToken: "nt2", ObjToken: "obj2", ObjType: "docx", Title: "Doc2", ObjEditTime: "200"},
{NodeToken: "nt3", ObjToken: "obj3", ObjType: "docx", Title: "Doc3", ObjEditTime: "300"},
{NodeToken: "nt4", ObjToken: "obj4", ObjType: "docx", Title: "Doc4", ObjEditTime: "400"},
{NodeToken: "nt5", ObjToken: "obj5", ObjType: "docx", Title: "Doc5", ObjEditTime: "500"},
}
ts, cfg, srv := newStatefulFeishu(nodes)
defer ts.Close()
cfgDS := makeConfig(cfg, []string{"space1"})
c := NewConnector(core.RegionFeishu)
// ---- Pass 1: obj2 export fails transiently; task "times out" on the 3rd
// Emit call (nt1 success, nt2 failure-item, then cancel as nt3 is emitted).
srv.setFail("obj2")
ctx1, cancel1 := context.WithCancel(context.Background())
h1 := &convergenceHandler{cancelAfterCall: 3, cancel: cancel1}
_, err1 := c.FetchStream(ctx1, cfgDS, nil, h1)
cancel1()
if err1 == nil {
t.Fatalf("pass 1 expected a timeout/abort error, got nil")
}
// Pass 1 ingested only nt1; nt2 surfaced as a failure; nt3+ never reached.
if got := strings.Join(h1.ingested, ","); got != "nt1" {
t.Fatalf("pass 1 ingested = %q, want just nt1", got)
}
// The persisted cursor (last Checkpoint) must contain nt1 but NOT the
// aborted nt3, nor the transiently-failed nt2 — otherwise resume would core.Skip
// them forever.
persisted := lastCheckpointCursor(h1, t)
if persisted == nil {
t.Fatalf("pass 1 wrote no Checkpoint — resume would restart from scratch")
}
var pc core.FeishuCursor
pb, _ := json.Marshal(persisted.ConnectorCursor)
_ = json.Unmarshal(pb, &pc)
p := pc.SpaceNodeTimes["space1"]
if _, ok := p["nt1"]; !ok {
t.Errorf("persisted cursor missing nt1 (done work lost on resume)")
}
if _, ok := p["nt2"]; ok {
t.Errorf("persisted cursor recorded transiently-failed nt2 — it would be core.Skipped forever")
}
if _, ok := p["nt3"]; ok {
t.Errorf("persisted cursor recorded aborted nt3 — it would be core.Skipped forever")
}
// ---- Pass 2: asynq retry. obj2 has recovered; run to completion resuming
// from the persisted cursor.
srv.setFail() // clear all failures
h2 := &convergenceHandler{}
next2, err2 := c.FetchStream(context.Background(), cfgDS, persisted, h2)
if err2 != nil {
t.Fatalf("pass 2 error: %v", err2)
}
// nt1 was already done → must be core.Skipped (not re-exported, not re-ingested).
for _, id := range h2.ingested {
if id == "nt1" {
t.Errorf("pass 2 re-ingested nt1 — redundant re-export of completed work")
}
}
// Everything still outstanding (nt2 transiently-failed, nt3 aborted, nt4, nt5)
// must be ingested in pass 2.
want := map[string]bool{"nt2": true, "nt3": true, "nt4": true, "nt5": true}
got2 := map[string]bool{}
for _, id := range h2.ingested {
got2[id] = true
}
for id := range want {
if !got2[id] {
t.Errorf("pass 2 did not ingest %s (want all outstanding nodes)", id)
}
}
// ---- Convergence: union across both passes covers ALL five nodes exactly.
union := map[string]bool{}
for _, id := range h1.ingested {
union[id] = true
}
for _, id := range h2.ingested {
union[id] = true
}
for _, n := range nodes {
if !union[n.NodeToken] {
t.Errorf("node %s was NEVER synced across both passes — data loss (#2136)", n.NodeToken)
}
}
if len(union) != len(nodes) {
t.Errorf("synced %d distinct nodes, want %d", len(union), len(nodes))
}
// Final cursor is a complete snapshot of every node (next incremental sync
// starts clean).
var fc core.FeishuCursor
nb, _ := json.Marshal(next2.ConnectorCursor)
_ = json.Unmarshal(nb, &fc)
for _, n := range nodes {
if _, ok := fc.SpaceNodeTimes["space1"][n.NodeToken]; !ok {
t.Errorf("final cursor missing %s — incremental sync would re-core.Fetch it", n.NodeToken)
}
}
}
@@ -0,0 +1,294 @@
package wiki
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/datasource/connector/feishu/core"
"academy/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
// core.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) core.DocxBlock {
return core.DocxBlock{BlockID: id, BlockType: core.BlockTypeSheet, Sheet: &core.BlockTokenRef{Token: token}}
}
func bitableBlk(id, token string) core.DocxBlock {
return core.DocxBlock{BlockID: id, BlockType: core.BlockTypeBitable, Bitable: &core.BlockTokenRef{Token: token}}
}
func imageBlk(id, token string) core.DocxBlock {
return core.DocxBlock{BlockID: id, BlockType: core.BlockTypeImage, Image: &core.BlockTokenRef{Token: token}}
}
func fileBlk(id, token, name string) core.DocxBlock {
return core.DocxBlock{BlockID: id, BlockType: core.BlockTypeFile, File: &core.BlockFileRef{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) core.DocxBlock {
return core.DocxBlock{BlockID: id, BlockType: core.BlockTypeTableCell, Children: []string{id + "_txt"}}
}
// cellTextBlk builds the child text block a table cell points at.
func cellTextBlk(id, text string) core.DocxBlock {
return core.DocxBlock{BlockID: id + "_txt", BlockType: core.BlockTypeText, Text: txt(text)}
}
func tableBlk(id string, cols int, cellIDs ...string) core.DocxBlock {
b := core.DocxBlock{BlockID: id, BlockType: core.BlockTypeTable}
b.Table = &core.BlockTable{Cells: cellIDs}
b.Table.Property = &core.BlockTableProperty{ColumnSize: cols}
return b
}
// fakeFeishuGolden serves the full API surface a rich docx node needs.
func fakeFeishuGolden(nodes []core.WikiNode, docToken string, blocks []core.DocxBlock,
mediaByToken map[string][]byte,
) (*httptest.Server, *core.Config) {
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.TokenResponse{ApiResponse: core.ApiResponse{Code: 0}, TenantAccessToken: "fake-token", Expire: 7200})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiSpaceListResponse{ApiResponse: core.ApiResponse{Code: 0}, Data: core.WikiSpaceListData{Items: []core.WikiSpace{{SpaceID: "space1", Name: "Test Space"}}}})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiNodeListResponse{ApiResponse: core.ApiResponse{Code: 0}, Data: core.WikiNodeListData{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, core.DocxBlocksResponse{ApiResponse: core.ApiResponse{Code: 0}, Data: core.DocxBlocksData{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/<token>/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)
})
// ParseMode is set explicitly even though blocks is now the default, so the
// golden baseline stays valid if the default ever flips again (the env var
// FEISHU_DOCX_PARSE_MODE was retired in favor of per-data-source Settings).
ts := httptest.NewServer(mux)
return ts, &core.Config{
AppID: "test-app-id", AppSecret: "test-app-secret",
BaseURL: ts.URL, ParseMode: core.ParseModeBlocks,
}
}
func TestGolden_RichDocxAllCapabilities(t *testing.T) {
const docToken = "obj-golden"
bigPDF := bytes.Repeat([]byte("A"), core.MinAttachmentBytes+512) // kept
tinyPDF := bytes.Repeat([]byte("B"), 100) // whitelisted but too small → dropped
// Valid PNG for the embedded image block (image items are unconditional in
// the P3 marker pipeline; the media token stays out of the Markdown).
png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), core.MinAttachmentBytes)...)
blocks := []core.DocxBlock{
{BlockID: "root", BlockType: core.BlockTypePage},
{BlockID: "h1", BlockType: core.BlockTypeHeading1, Heading1: txt("季度报告")},
{BlockID: "p1", BlockType: core.BlockTypeText, Text: txt("本季度概览。")},
{BlockID: "h2", BlockType: core.BlockTypeHeading1 + 1, Heading2: txt("关键指标")},
{BlockID: "b1", BlockType: core.BlockTypeBullet, Bullet: txt("收入增长")},
{BlockID: "o1", BlockType: core.BlockTypeOrdered, Ordered: txt("第一步立项")},
{BlockID: "code1", BlockType: core.BlockTypeCode, Code: txt("SELECT 1")},
{BlockID: "q1", BlockType: core.BlockTypeQuote, Quote: txt("重要提示")},
{BlockID: "todo1", BlockType: core.BlockTypeTodo, Todo: txt("完成复盘")},
{BlockID: "call1", BlockType: core.BlockTypeCallout, Callout: txt("注意风险")},
{BlockID: "div1", BlockType: core.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 core.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 := []core.WikiNode{{
NodeToken: "nt-golden", ObjToken: docToken, ObjType: "docx",
Title: "季度报告文档", NodeEditTime: "1711468800",
}}
media := map[string][]byte{"tok-big": bigPDF, "tok-small": tinyPDF, "img-tok-SECRET": png}
ts, cfg := fakeFeishuGolden(nodes, docToken, blocks, media)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
items, err := c.FetchAll(context.Background(), makeConfig(cfg, []string{"space1"}), []string{"space1"})
if err != nil {
t.Fatalf("FetchAll error: %v", err)
}
// ── sub-items first (attachment), then the main markdown item ──
// Orthodox image flow (2026-09-20): images ride inline in the parent
// markdown as base64 data URIs — no image sub-items at all.
if len(items) != 2 {
t.Fatalf("want 2 items (1 kept attachment + main), got %d:\n%+v", len(items), items)
}
var main, att *types.FetchedItem
for i := range items {
switch items[i].ExternalID {
case "nt-golden":
main = &items[i]
case "nt-golden#file#tok-big":
att = &items[i]
}
}
if main == nil {
t.Fatal("main markdown item missing")
}
// P3 contract: sub-items precede the parent document.
if items[len(items)-1].ExternalID != "nt-golden" {
order := []string{items[0].ExternalID, items[1].ExternalID, items[2].ExternalID}
t.Errorf("main item must be emitted last, got order: %v", order)
}
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 ──
// Baseline re-recorded (2026-09-20, orthodox image flow): image blocks
// render inline base64 data URIs (stored to provider:// URLs by the
// doc-process image resolver), and file blocks render as
// `- 文件名` list entries (whitelisted) or `> [附件: …](链接)` references
// (non-whitelisted), replacing the old `📎 附件:…` placeholder.
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
"![图片](data:image/png;base64,", // image inlined as base64 data URI
"- 手册.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)
}
// The internal image media token must map to nothing: markers are gone.
if main.Metadata["image_map"] != "" {
t.Errorf("image_map must be gone, got %q", main.Metadata["image_map"])
}
if !strings.Contains(main.Metadata["attachment_ids"], "nt-golden#file#tok-big") {
t.Errorf("main.Metadata[attachment_ids] = %q, want it to contain tok-big", main.Metadata["attachment_ids"])
}
// ── 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)
}
}
@@ -0,0 +1,234 @@
//go:build feishu_integration
// Real-API integration test for FetchStream against a live Feishu tenant.
//
// It is OPT-IN and never runs in the normal suite or CI: it is guarded by the
// `feishu_integration` build tag AND skips unless the required env vars are set.
//
// Run it with:
//
// export CPLUS_INCLUDE_PATH="$(xcrun --show-sdk-path)/usr/include/c++/v1"
// FEISHU_APP_ID=... FEISHU_APP_SECRET=... FEISHU_TEST_SPACE_ID=... \
// go test -tags feishu_integration -run TestRealAPI -v \
// ./internal/datasource/connector/feishu/
//
// The test is strictly READ-ONLY: it lists and exports documents from the given
// wiki space but never creates, edits or deletes anything. It whitelists
// *.feishu.cn / *.larksuite.com for SSRF in-process so it works from a dev
// machine behind a fake-ip proxy without any production code change.
package wiki
import (
"context"
"encoding/json"
"os"
"strings"
"testing"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/types"
"academy/internal/utils"
)
// collectHandler records everything a real FetchStream emits so the test can
// assert coverage and resume behaviour. cancelAfter>0 simulates a task timeout
// by cancelling the run after that many successful content emits.
type collectHandler struct {
ingested []string
failed []string
checkpoints []*types.SyncCursor
calls int
cancelAfter int
cancel context.CancelFunc
}
func (h *collectHandler) Emit(ctx context.Context, item types.FetchedItem) error {
if err := ctx.Err(); err != nil {
return err
}
if item.Metadata["error"] != "" {
h.failed = append(h.failed, item.ExternalID)
return nil
}
h.calls++
if h.cancelAfter > 0 && h.calls > h.cancelAfter {
if h.cancel != nil {
h.cancel()
}
return context.Canceled
}
h.ingested = append(h.ingested, item.ExternalID)
return nil
}
func (h *collectHandler) Checkpoint(_ context.Context, cursor *types.SyncCursor) error {
// Snapshot the cursor JSON (mirrors the service serialising synchronously).
b, _ := json.Marshal(cursor.ConnectorCursor)
var m map[string]interface{}
_ = json.Unmarshal(b, &m)
h.checkpoints = append(h.checkpoints, &types.SyncCursor{ConnectorCursor: m})
return nil
}
func nodeTimes(t *testing.T, cur *types.SyncCursor) map[string]map[string]string {
t.Helper()
if cur == nil {
return nil
}
var fc core.FeishuCursor
b, _ := json.Marshal(cur.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
return fc.SpaceNodeTimes
}
func countNodes(m map[string]map[string]string) int {
n := 0
for _, v := range m {
n += len(v)
}
return n
}
// TestRealAPI_ListSpaces discovers which wiki spaces the app can access, so the
// space ID for the other tests can be found without guessing. Read-only.
func TestRealAPI_ListSpaces(t *testing.T) {
appID := os.Getenv("FEISHU_APP_ID")
appSecret := os.Getenv("FEISHU_APP_SECRET")
if appID == "" || appSecret == "" {
t.Skip("set FEISHU_APP_ID, FEISHU_APP_SECRET to run")
}
utils.SetSSRFWhitelistFromRaw("*.feishu.cn,*.larksuite.com")
client := core.NewClient(&core.Config{AppID: appID, AppSecret: appSecret, BaseURL: os.Getenv("FEISHU_BASE_URL")})
spaces, err := client.ListWikiSpaces(context.Background())
if err != nil {
t.Fatalf("ListWikiSpaces: %v", err)
}
if len(spaces) == 0 {
t.Fatalf("app can access 0 wiki spaces — add the app as a member of a knowledge base")
}
for _, s := range spaces {
t.Logf("SPACE space_id=%s name=%q", s.SpaceID, s.Name)
}
}
func TestRealAPI_FetchStreamResumeConverges(t *testing.T) {
appID := os.Getenv("FEISHU_APP_ID")
appSecret := os.Getenv("FEISHU_APP_SECRET")
spaceID := os.Getenv("FEISHU_TEST_SPACE_ID")
if appID == "" || appSecret == "" || spaceID == "" {
t.Skip("set FEISHU_APP_ID, FEISHU_APP_SECRET, FEISHU_TEST_SPACE_ID to run")
}
// Whitelist the Feishu/Lark hosts for SSRF so the dev-machine fake-ip proxy
// (198.18.x) is allowed. No production code change; scoped to these hosts.
utils.SetSSRFWhitelistFromRaw("*.feishu.cn,*.larksuite.com")
baseURL := os.Getenv("FEISHU_BASE_URL") // optional; defaults to region base
cfg := &types.DataSourceConfig{
Type: types.ConnectorTypeFeishu,
Credentials: map[string]interface{}{
"app_id": appID,
"app_secret": appSecret,
"base_url": baseURL,
},
ResourceIDs: []string{spaceID},
}
c := NewConnector(core.RegionFeishu)
// ---- Pass 1: full sync against the real space.
h1 := &collectHandler{}
cur1, err := c.FetchStream(context.Background(), cfg, nil, h1)
if err != nil {
t.Fatalf("pass 1 (full) FetchStream error: %v", err)
}
n := len(h1.ingested)
t.Logf("pass 1: ingested=%d failed=%d cursor_nodes=%d", n, len(h1.failed), countNodes(nodeTimes(t, cur1)))
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. 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 "<node>#file#..." or
// "<node>#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-core.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)
}
}
// ---- Pass 2: incremental with pass-1 cursor. Against the REAL API this is
// the load-bearing check a fake can't make: real obj_edit_time must be
// stable for unchanged docs, so NOTHING is re-ingested.
h2 := &collectHandler{}
cur2, err := c.FetchStream(context.Background(), cfg, cur1, h2)
if err != nil {
t.Fatalf("pass 2 (incremental) FetchStream error: %v", err)
}
t.Logf("pass 2: re-ingested=%d (want 0)", len(h2.ingested))
if len(h2.ingested) != 0 {
t.Errorf("pass 2 re-ingested %v — real edit-time is unstable or core.Skip logic is broken", h2.ingested)
}
if got := countNodes(nodeTimes(t, cur2)); got != countNodes(nt1AsMap(nt1)) {
t.Logf("note: cursor node count changed between passes (%d→%d) — space may have been edited concurrently", countNodes(nt1AsMap(nt1)), got)
}
// ---- Pass 3: interrupt mid-sync then resume, against the real API.
// Only meaningful with at least 2 documents.
if n < 2 {
t.Logf("only %d doc(s); skipping interrupt/resume convergence sub-test (needs >=2)", n)
return
}
prevN := core.FeishuStreamCheckpointInterval
core.FeishuStreamCheckpointInterval = 1 // Checkpoint every node so resume is precise
defer func() { core.FeishuStreamCheckpointInterval = prevN }()
ctx3, cancel3 := context.WithCancel(context.Background())
h3 := &collectHandler{cancelAfter: 1, cancel: cancel3} // abort after 1 success
_, err = c.FetchStream(ctx3, cfg, nil, h3)
cancel3()
if err == nil {
t.Fatalf("pass 3 expected an abort error from the simulated timeout")
}
if len(h3.checkpoints) == 0 {
t.Fatalf("pass 3 wrote no Checkpoint — resume would restart from scratch")
}
persisted := h3.checkpoints[len(h3.checkpoints)-1]
t.Logf("pass 3: ingested=%d before abort, persisted cursor nodes=%d", len(h3.ingested), countNodes(nodeTimes(t, persisted)))
// Resume from the persisted Checkpoint; must converge to full coverage.
h4 := &collectHandler{}
_, err = c.FetchStream(context.Background(), cfg, persisted, h4)
if err != nil {
t.Fatalf("pass 4 (resume) FetchStream error: %v", err)
}
union := map[string]bool{}
for _, id := range h3.ingested {
union[id] = true
}
for _, id := range h4.ingested {
union[id] = true
}
t.Logf("pass 3+4 union ingested=%d, pass-1 full=%d", len(union), n)
if len(union) < n {
t.Errorf("resume converged to %d docs but full sync had %d — a document was lost across interrupt+resume", len(union), n)
}
// Resume must not redo already-checkpointed work.
done := nodeTimes(t, persisted)[spaceID]
for _, id := range h4.ingested {
if _, ok := done[id]; ok {
t.Errorf("pass 4 re-ingested already-checkpointed node %s (redundant re-export)", id)
}
}
}
func nt1AsMap(m map[string]string) map[string]map[string]string {
return map[string]map[string]string{"_": m}
}
@@ -0,0 +1,152 @@
//go:build feishu_integration
// Seeder for the real-API integration test. OPT-IN (feishu_integration tag +
// env vars) so it never runs in the normal suite or CI.
//
// It WRITES to your Feishu tenant: it creates a handful of docx documents under
// the given wiki space, each titled "Academy sync test doc N" so you can find
// and delete them afterwards. Requires app write scopes:
// - wiki:wiki (create wiki nodes)
// - docx:document (write docx content)
//
// plus the app being a member of the space.
//
// Run:
//
// export CPLUS_INCLUDE_PATH="$(xcrun --show-sdk-path)/usr/include/c++/v1"
// FEISHU_APP_ID=... FEISHU_APP_SECRET=... FEISHU_TEST_SPACE_ID=... FEISHU_SEED_COUNT=3 \
// go test -tags feishu_integration -run TestRealAPI_SeedDocs -v \
// ./internal/datasource/connector/feishu/
package wiki
import (
"context"
"fmt"
"os"
"strconv"
"testing"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/utils"
)
// wikiNodeCreateResp is the subset of POST /wiki/v2/spaces/:id/nodes we need.
type wikiNodeCreateResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Node struct {
NodeToken string `json:"node_token"`
ObjToken string `json:"obj_token"`
ObjType string `json:"obj_type"`
Title string `json:"title"`
} `json:"node"`
} `json:"data"`
}
// TestRealAPI_CreateSpace creates a fresh knowledge base owned by the app, so
// the app can seed and read it without a human adding it to an existing space.
// It prints the new space_id for use as FEISHU_TEST_SPACE_ID.
func TestRealAPI_CreateSpace(t *testing.T) {
appID := os.Getenv("FEISHU_APP_ID")
appSecret := os.Getenv("FEISHU_APP_SECRET")
if appID == "" || appSecret == "" {
t.Skip("set FEISHU_APP_ID, FEISHU_APP_SECRET to run")
}
utils.SetSSRFWhitelistFromRaw("*.feishu.cn,*.larksuite.com")
client := core.NewClient(&core.Config{AppID: appID, AppSecret: appSecret, BaseURL: os.Getenv("FEISHU_BASE_URL")})
var resp struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Space struct {
SpaceID string `json:"space_id"`
Name string `json:"name"`
} `json:"space"`
} `json:"data"`
}
err := client.DoRequest(context.Background(), "POST", "/open-apis/wiki/v2/spaces",
map[string]interface{}{
"name": "Academy Resilience Test KB",
"description": "Auto-created for connector resilience testing (#2136). Safe to delete.",
}, &resp)
if err != nil {
t.Fatalf("create space: %v", err)
}
if resp.Code != 0 {
t.Fatalf("create space: code=%d msg=%s (needs wiki:wiki write scope)", resp.Code, resp.Msg)
}
t.Logf("CREATED_SPACE space_id=%s name=%q", resp.Data.Space.SpaceID, resp.Data.Space.Name)
}
func TestRealAPI_SeedDocs(t *testing.T) {
appID := os.Getenv("FEISHU_APP_ID")
appSecret := os.Getenv("FEISHU_APP_SECRET")
spaceID := os.Getenv("FEISHU_TEST_SPACE_ID")
if appID == "" || appSecret == "" || spaceID == "" {
t.Skip("set FEISHU_APP_ID, FEISHU_APP_SECRET, FEISHU_TEST_SPACE_ID to run")
}
count := 3
if v := os.Getenv("FEISHU_SEED_COUNT"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
count = n
}
}
utils.SetSSRFWhitelistFromRaw("*.feishu.cn,*.larksuite.com")
baseURL := os.Getenv("FEISHU_BASE_URL")
client := core.NewClient(&core.Config{AppID: appID, AppSecret: appSecret, BaseURL: baseURL})
ctx := context.Background()
for i := 1; i <= count; i++ {
title := fmt.Sprintf("Academy sync test doc %d", i)
// 1) Create a docx wiki node.
var created wikiNodeCreateResp
err := client.DoRequest(ctx, "POST",
fmt.Sprintf("/open-apis/wiki/v2/spaces/%s/nodes", spaceID),
map[string]interface{}{
"obj_type": "docx",
"node_type": "origin",
"title": title,
}, &created)
if err != nil {
t.Fatalf("create wiki node %d: %v", i, err)
}
if created.Code != 0 {
t.Fatalf("create wiki node %d: code=%d msg=%s (check wiki:wiki write scope + space membership)", i, created.Code, created.Msg)
}
docID := created.Data.Node.ObjToken // for docx, obj_token == document_id
// 2) Add a text block so the export is non-empty.
var blockResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
berr := client.DoRequest(ctx, "POST",
fmt.Sprintf("/open-apis/docx/v1/documents/%s/blocks/%s/children", docID, docID),
map[string]interface{}{
"index": 0,
"children": []map[string]interface{}{{
"block_type": 2, // text
"text": map[string]interface{}{
"elements": []map[string]interface{}{{
"text_run": map[string]interface{}{
"content": fmt.Sprintf("This is Academy sync test document number %d. It exists to validate connector resilience (issue #2136).", i),
},
}},
},
}},
}, &blockResp)
if berr != nil {
t.Logf("warn: add content to doc %d failed (%v) — doc still created, export may be empty", i, berr)
} else if blockResp.Code != 0 {
t.Logf("warn: add content to doc %d: code=%d msg=%s (needs docx:document write scope) — doc still created", i, blockResp.Code, blockResp.Msg)
}
t.Logf("created doc %d: title=%q node_token=%s obj_token=%s", i, title, created.Data.Node.NodeToken, docID)
}
t.Logf("seeded %d docs under space %s. Now run TestRealAPI_FetchStreamResumeConverges.", count, spaceID)
}
@@ -0,0 +1,493 @@
package wiki
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/types"
)
// fakeFeishuFailingExport serves the auth/spaces/nodes endpoints normally but
// fails every document export (code != 0), so fetchNodeContent returns an error
// for each supported node — modelling a rate-limited / broken export.
func fakeFeishuFailingExport(nodes []core.WikiNode) (*httptest.Server, *core.Config) {
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.TokenResponse{ApiResponse: core.ApiResponse{Code: 0}, TenantAccessToken: "fake-token", Expire: 7200})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiSpaceListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiSpaceListData{Items: []core.WikiSpace{{SpaceID: "space1", Name: "Test Space"}}},
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiNodeListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiNodeListData{Items: nodes},
})
})
// Export creation fails for every document.
mux.HandleFunc("/open-apis/drive/v1/export_tasks", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.ApiResponse{Code: 1, Msg: "export unavailable"})
})
ts := httptest.NewServer(mux)
return ts, &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL}
}
// A node whose core.Fetch fails must NOT have its new edit time recorded in the
// returned cursor: recording it would make the next sync's unchanged fast-path
// core.Skip it forever, silently dropping a document on a transient export failure
// (Tencent/WeKnora#2136). With a prior edit time known, the prior value is
// retained so prev != current next run and the node is retried.
func TestFetchStream_FailedFetchRetainsPriorCursor(t *testing.T) {
nodes := []core.WikiNode{{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"}}
ts, cfg := fakeFeishuFailingExport(nodes)
defer ts.Close()
cursor := makeStreamCursor(t, map[string]map[string]string{"space1": {"nt1": "50"}}) // prior, older
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{}
next, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), cursor, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
// A failure item must be surfaced, not silently dropped.
if len(h.emitted) != 1 || h.emitted[0].Metadata["error"] == "" {
t.Fatalf("expected 1 emitted failure item with error metadata, got %+v", h.emitted)
}
var fc core.FeishuCursor
b, _ := json.Marshal(next.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
got := fc.SpaceNodeTimes["space1"]["nt1"]
if got == "100" {
t.Fatalf("failed node advanced to current edit time %q — it will be core.Skipped forever", got)
}
if got != "50" {
t.Errorf("failed node cursor = %q, want prior value \"50\" (retry next run)", got)
}
}
// With no prior cursor entry, a failed core.Fetch must leave the node out of the
// returned cursor entirely, so the next run treats it as new and retries it.
func TestFetchStream_FailedFetchNoPriorOmitsFromCursor(t *testing.T) {
nodes := []core.WikiNode{{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"}}
ts, cfg := fakeFeishuFailingExport(nodes)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{}
next, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
var fc core.FeishuCursor
b, _ := json.Marshal(next.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
if v, ok := fc.SpaceNodeTimes["space1"]["nt1"]; ok {
t.Errorf("failed node recorded in cursor as %q; want absent so it is retried next run", v)
}
}
// recordingHandler captures the items and checkpoints a streaming core.Fetch emits.
// Checkpoints are snapshotted (JSON-encoded) at call time — mirroring the
// service, which serializes the cursor synchronously inside Checkpoint — so the
// test observes the cursor state as it was when Checkpoint was called, not the
// connector's later-mutated map.
type recordingHandler struct {
emitted []types.FetchedItem
checkpoints []core.FeishuCursor
emitErr func(item types.FetchedItem) error
}
func (h *recordingHandler) Emit(ctx context.Context, item types.FetchedItem) error {
if h.emitErr != nil {
if err := h.emitErr(item); err != nil {
return err
}
}
h.emitted = append(h.emitted, item)
return nil
}
func (h *recordingHandler) Checkpoint(ctx context.Context, cursor *types.SyncCursor) error {
var fc core.FeishuCursor
b, _ := json.Marshal(cursor.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
h.checkpoints = append(h.checkpoints, fc)
return nil
}
func makeStreamCursor(t *testing.T, spaceNodeTimes map[string]map[string]string) *types.SyncCursor {
t.Helper()
prev := core.FeishuCursor{SpaceNodeTimes: spaceNodeTimes}
b, _ := json.Marshal(prev)
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
t.Fatalf("build cursor: %v", err)
}
return &types.SyncCursor{ConnectorCursor: m}
}
// A nil-cursor stream emits every supported node once and skips unsupported
// types, and the returned cursor records the edit time of every discovered node
// (so the next incremental run can detect changes).
func TestFetchStream_EmitsSupportedSkipsUnsupported(t *testing.T) {
nodes := []core.WikiNode{
{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"},
{NodeToken: "nt2", ObjToken: "obj2", ObjType: "mindnote", Title: "Brain", ObjEditTime: "200"},
{NodeToken: "nt3", ObjToken: "obj3", ObjType: "docx", Title: "Doc3", ObjEditTime: "300"},
}
ts, cfg := fakeFeishu(nodes)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{}
next, 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("emitted %d items, want 2 (nt1, nt3)", len(h.emitted))
}
if h.emitted[0].ExternalID != "nt1" || h.emitted[1].ExternalID != "nt3" {
t.Errorf("emitted ids = %q,%q; want nt1,nt3", h.emitted[0].ExternalID, h.emitted[1].ExternalID)
}
var fc core.FeishuCursor
b, _ := json.Marshal(next.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
times := fc.SpaceNodeTimes["space1"]
for _, tok := range []string{"nt1", "nt2", "nt3"} {
if _, ok := times[tok]; !ok {
t.Errorf("returned cursor missing edit time for %s", tok)
}
}
}
// When a cursor already records a node at its current edit time, that node is
// unchanged and must not be re-emitted; only new/changed nodes stream through.
// This is the resume/incremental-core.Skip behavior that lets a timed-out sync
// converge across retries instead of re-exporting everything.
func TestFetchStream_SkipsUnchangedNodesFromCursor(t *testing.T) {
nodes := []core.WikiNode{
{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"},
{NodeToken: "nt3", ObjToken: "obj3", ObjType: "docx", Title: "Doc3", ObjEditTime: "300"},
}
ts, cfg := fakeFeishu(nodes)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
_, firstCursor, err := c.FetchIncremental(context.Background(), makeConfig(cfg, []string{"space1"}), nil)
if err != nil {
t.Fatalf("first sync: %v", err)
}
first := (&wikiOps{}).DecodeCursorTimes(firstCursor.ConnectorCursor)
delete(first["space1"], "nt3") // nt1 unchanged; nt3 unknown → new
cursor := makeStreamCursor(t, first)
h := &recordingHandler{}
if _, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), cursor, h); err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.emitted) != 1 {
t.Fatalf("emitted %d items, want 1 (only changed nt3)", len(h.emitted))
}
if h.emitted[0].ExternalID != "nt3" {
t.Errorf("emitted id = %q, want nt3", h.emitted[0].ExternalID)
}
}
// Checkpoints must persist progress at page boundaries so a crash mid-sync
// resumes from the last Checkpoint. With the interval set to 1, each emitted
// item triggers a Checkpoint, and the first Checkpoint must already contain the
// first node's edit time.
func TestFetchStream_CheckpointsProgress(t *testing.T) {
prev := core.FeishuStreamCheckpointInterval
core.FeishuStreamCheckpointInterval = 1
defer func() { core.FeishuStreamCheckpointInterval = prev }()
nodes := []core.WikiNode{
{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"},
{NodeToken: "nt3", ObjToken: "obj3", ObjType: "docx", Title: "Doc3", ObjEditTime: "300"},
}
ts, cfg := fakeFeishu(nodes)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{}
if _, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), nil, h); err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.checkpoints) == 0 {
t.Fatalf("expected at least one Checkpoint")
}
first := h.checkpoints[0]
if _, ok := first.SpaceNodeTimes["space1"]["nt1"]; !ok {
t.Errorf("first Checkpoint missing nt1 progress: %+v", first.SpaceNodeTimes)
}
}
// Checkpoints must ALSO fire on elapsed time, not only every N nodes.
// Otherwise a sync with fewer than the node interval of slow (rate-limited)
// exports reaches the 2h task timeout having never checkpointed, and resumes
// from scratch forever — exactly the #2136 "never fully syncs" case. With the
// node interval effectively disabled and the time interval at 0, every
// processed node must still produce a Checkpoint.
func TestFetchStream_CheckpointsOnElapsedTime(t *testing.T) {
prevN := core.FeishuStreamCheckpointInterval
prevT := core.FeishuStreamCheckpointMaxInterval
core.FeishuStreamCheckpointInterval = 1 << 30 // never fires by count
core.FeishuStreamCheckpointMaxInterval = 0 // fires by elapsed time every node
defer func() {
core.FeishuStreamCheckpointInterval = prevN
core.FeishuStreamCheckpointMaxInterval = prevT
}()
nodes := []core.WikiNode{
{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"},
{NodeToken: "nt3", ObjToken: "obj3", ObjType: "docx", Title: "Doc3", ObjEditTime: "300"},
}
ts, cfg := fakeFeishu(nodes)
defer ts.Close()
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{}
if _, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), nil, h); err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.checkpoints) == 0 {
t.Fatalf("expected time-based checkpoints even though node interval never fires")
}
}
// An Emit error aborts the stream immediately — the connector must return the
// error and stop fetching further nodes (the sync is failing; do not burn API
// budget on the rest of the tree).
func TestFetchStream_EmitErrorAborts(t *testing.T) {
nodes := []core.WikiNode{
{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"},
{NodeToken: "nt3", ObjToken: "obj3", ObjType: "docx", Title: "Doc3", ObjEditTime: "300"},
}
ts, cfg := fakeFeishu(nodes)
defer ts.Close()
boom := errors.New("ingest failed")
c := NewConnector(core.RegionFeishu)
h := &recordingHandler{emitErr: func(item types.FetchedItem) error { return boom }}
_, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), nil, h)
if !errors.Is(err, boom) {
t.Fatalf("FetchStream() error = %v, want %v", err, boom)
}
if len(h.emitted) != 0 {
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 → core.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 core.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 core.MinAttachmentBytes (2 KiB).
attContent := bytes.Repeat([]byte("a"), core.MinAttachmentBytes+1)
nodes := []core.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(core.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 (attachment + main doc), got %d: %+v", len(h.emitted), h.emitted)
}
// P3 contract: sub-items are emitted BEFORE the parent document.
att := h.emitted[0]
wantAttID := nodeToken + "#file#" + attToken
if att.ExternalID != wantAttID {
t.Errorf("items[0].ExternalID = %q, want %q", att.ExternalID, wantAttID)
}
if att.Metadata["attachment"] != "true" {
t.Errorf("items[0].Metadata[attachment] = %q, want \"true\"", att.Metadata["attachment"])
}
main := h.emitted[1]
if main.ExternalID != nodeToken {
t.Errorf("items[1].ExternalID = %q, want %q", main.ExternalID, nodeToken)
}
if main.ContentType != "text/markdown" {
t.Errorf("items[1].ContentType = %q, want text/markdown", main.ContentType)
}
if !main.ReplacesSubtree {
t.Errorf("items[1].ReplacesSubtree = false, want true")
}
}
// 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: core.FetchDocxWithBlocks → blocks error → fetchViaExport.
func fakeFeishuWithBlocksFallback(nodes []core.WikiNode, docToken string) (*httptest.Server, *core.Config) {
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.TokenResponse{
ApiResponse: core.ApiResponse{Code: 0},
TenantAccessToken: "fake-token",
Expire: 7200,
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiSpaceListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiSpaceListData{Items: []core.WikiSpace{{SpaceID: "space1", Name: "Test Space"}}},
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, core.WikiNodeListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiNodeListData{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, core.ExportTaskCreateResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.ExportTaskCreateData{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, core.ExportTaskStatusResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.ExportTaskStatusData{
Result: core.ExportTaskResult{
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, &core.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 := []core.WikiNode{{
NodeToken: nodeToken,
ObjToken: objToken,
ObjType: "docx",
Title: "Fallback Doc",
ObjEditTime: "600",
}}
ts, cfg := fakeFeishuWithBlocksFallback(nodes, objToken)
defer ts.Close()
c := NewConnector(core.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)")
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
package wiki
import "academy/internal/datasource/connector/feishu/core"
func txt(s string) *core.BlockText {
return &core.BlockText{Elements: []core.TextElement{{TextRun: &core.TextRun{Content: s}}}}
}
@@ -0,0 +1,86 @@
package wiki
import (
"context"
"strings"
"testing"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/types"
)
// A Lark connector must surface wiki links on the Lark host. Before Lark became
// its own connector type, every resource URL was hardcoded to feishu.cn, so Lark
// users got links into a cloud their content does not live on.
//
// The fake server stands in for the Open Platform (base_url points at it), but
// the resource URL is built from the region's web host, so this exercises the
// real ListResources → wikiNodeToResource → region.WikiURL path.
func TestListResources_ResourceURLFollowsRegion(t *testing.T) {
cases := []struct {
region core.Region
wantURL string
forbiddenIn string
}{
{core.RegionFeishu, "https://feishu.cn/wiki/space1", "larksuite"},
{core.RegionLark, "https://larksuite.com/wiki/space1", "feishu"},
}
for _, c := range cases {
t.Run(c.region.Label, func(t *testing.T) {
ts, cfg := fakeFeishu(nil)
defer ts.Close()
conn := NewConnector(c.region)
resources, err := conn.ListResources(context.Background(), makeConfig(cfg, nil), "")
if err != nil {
t.Fatalf("ListResources: %v", err)
}
if len(resources) != 1 {
t.Fatalf("got %d resources, want 1", len(resources))
}
if got := resources[0].URL; got != c.wantURL {
t.Errorf("resource URL = %q, want %q", got, c.wantURL)
}
if strings.Contains(resources[0].URL, c.forbiddenIn) {
t.Errorf("%s resource URL leaks the other cloud's host: %q", c.region.Label, resources[0].URL)
}
})
}
}
// A Lark connector with no base_url override must reach open.larksuite.com,
// never open.feishu.cn — the SDK-less client has no default of its own, so the
// region is the only thing standing between a Lark app and the wrong cloud.
func TestClient_ResolvesRegionHostWithoutOverride(t *testing.T) {
cases := []struct {
region core.Region
want string
}{
{core.RegionFeishu, "https://open.feishu.cn"},
{core.RegionLark, "https://open.larksuite.com"},
}
for _, c := range cases {
t.Run(c.region.Label, func(t *testing.T) {
cfg, err := core.ParseFeishuConfig(makeConfigNoBaseURL(), c.region)
if err != nil {
t.Fatalf("ParseFeishuConfig: %v", err)
}
if cfg.GetBaseURL() != c.want {
t.Errorf("baseURL = %q, want %q", cfg.GetBaseURL(), c.want)
}
})
}
}
// makeConfigNoBaseURL builds credentials without base_url, so the region default
// is what resolves.
func makeConfigNoBaseURL() *types.DataSourceConfig {
return &types.DataSourceConfig{
Credentials: map[string]interface{}{
"app_id": "cli_x",
"app_secret": "s",
},
}
}
@@ -0,0 +1,43 @@
package wiki
import (
"context"
"testing"
"academy/internal/datasource/connector/feishu/core"
)
func TestParseModeChangeRefetchesExistingDocument(t *testing.T) {
nodes := []core.WikiNode{{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"}}
ts, cfg := fakeFeishu(nodes)
defer ts.Close()
conf := makeConfig(cfg, []string{"space1"})
conf.Settings = map[string]interface{}{"parse_mode": "export"}
c := NewConnector(core.RegionFeishu)
items, cursor, err := c.FetchIncremental(context.Background(), conf, nil)
if err != nil {
t.Fatal(err)
}
if len(items) != 1 {
t.Fatalf("first sync items=%d", len(items))
}
t.Setenv("FEISHU_DOCX_PARSE_MODE", "export")
for _, mode := range []string{"blocks", "", "blocks", "export"} {
conf.Settings["parse_mode"] = mode
items, cursor, err = c.FetchIncremental(context.Background(), conf, cursor)
if err != nil {
t.Fatal(err)
}
if len(items) != 1 {
t.Fatalf("parse_mode change must refetch the document: got %d items", len(items))
}
items, _, err = c.FetchIncremental(context.Background(), conf, cursor)
if err != nil {
t.Fatal(err)
}
if len(items) != 0 {
t.Fatalf("unchanged effective mode must skip document: got %d items", len(items))
}
}
}
@@ -0,0 +1,142 @@
package wiki
import (
"strings"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/types"
)
// This file implements the P1 directory mapping: FetchedItem.FileName becomes
// "<空间名>/<目录A>/<目录B>/<文档名>.md" rooted at the synced space's own name
// (the space = a top-level KB folder) so ingestion's
// types.SplitKnowledgeRelativePath derives the KB folder_path (GitLab-style).
// The path table is built per sync run from the recursive node listing — zero
// engine changes. external_id stays the node token, so a move/rename lands in
// the new folder through the existing update=delete+recreate path.
// filterShortcutSubtrees drops only shortcuts whose original subtree is also
// in this complete listing. Never follow origins outside the selected scope:
// the shortcut can be the only accessible copy of a document.
func filterShortcutSubtrees(nodes []core.WikiNode) []core.WikiNode {
byToken := make(map[string]core.WikiNode, len(nodes))
for _, n := range nodes {
byToken[n.NodeToken] = n
}
redundant := make(map[string]bool)
for _, n := range nodes {
origin, ok := byToken[n.OriginNodeID]
if n.NodeType != "shortcut" || !ok || origin.NodeType == "shortcut" {
continue
}
if n.OriginSpaceID != "" && origin.SpaceID != "" && n.OriginSpaceID != origin.SpaceID {
continue
}
// An origin reached only through a shortcut is not an independently
// enumerated copy. In particular, do not discard mutually linked trees.
if !underShortcut(origin, byToken) {
redundant[n.NodeToken] = true
}
}
kept := make([]core.WikiNode, 0, len(nodes))
for _, n := range nodes {
if underFilteredNode(n, byToken, redundant) {
continue
}
kept = append(kept, n)
}
return kept
}
func underFilteredNode(n core.WikiNode, byToken map[string]core.WikiNode, filtered map[string]bool) bool {
visited := make(map[string]bool)
for token := n.NodeToken; token != "" && !visited[token]; token = byToken[token].ParentNodeID {
if filtered[token] {
return true
}
visited[token] = true
}
return false
}
// underShortcut reports whether n is itself a shortcut or has one on its
// ancestor chain within the listed set. An ancestor missing from the listing
// (subtree root's parent, or a partial listing) ends the walk as "no shortcut".
func underShortcut(n core.WikiNode, byToken map[string]core.WikiNode) bool {
if n.NodeType == "shortcut" {
return true
}
visited := make(map[string]bool)
for p := n.ParentNodeID; p != "" && !visited[p]; p = byToken[p].ParentNodeID {
visited[p] = true
parent, ok := byToken[p]
if !ok {
return false
}
if parent.NodeType == "shortcut" {
return true
}
}
return false
}
// buildWikiDirPaths maps each node token to its cleaned directory prefix,
// rooted at spacePrefix (the synced space's sanitized name): a top-level node
// maps to spacePrefix (its document lands in the space's own KB folder) and
// deeper nodes to "<space>/<父目录标题...>". Ancestors are resolved bottom-up
// through ParentNodeID within the listing; for a sub-tree selection the
// ancestors above the sub-tree root are unknown, so its documents land
// directly in the space folder. A docx node that also has children is both a
// document and a directory — its own item sits beside the child folder it
// forms. An empty spacePrefix (space name unresolved) falls back to paths
// relative to the listing root.
func buildWikiDirPaths(nodes []core.WikiNode, spacePrefix string) map[string]string {
byToken := make(map[string]core.WikiNode, len(nodes))
for _, n := range nodes {
byToken[n.NodeToken] = n
}
paths := make(map[string]string, len(nodes))
for _, n := range nodes {
// Walk up collecting ancestor titles, then reverse so the topmost
// directory leads; the space name itself leads the chain.
var ancestors []string
visited := make(map[string]bool)
for p := n.ParentNodeID; p != "" && !visited[p]; p = byToken[p].ParentNodeID {
visited[p] = true
parent, ok := byToken[p]
if !ok {
break
}
ancestors = append(ancestors, core.SanitizeFileName(parent.Title))
}
for i, j := 0, len(ancestors)-1; i < j; i, j = i+1, j-1 {
ancestors[i], ancestors[j] = ancestors[j], ancestors[i]
}
if spacePrefix != "" {
ancestors = append([]string{spacePrefix}, ancestors...)
}
paths[n.NodeToken] = strings.Join(ancestors, "/")
}
return paths
}
// prepareDirPaths rebuilds the per-resource directory table. Called from List
// after removing redundant shortcut subtrees.
func (o *wikiOps) prepareDirPaths(nodes []core.WikiNode, spacePrefix string) {
o.dirPaths = buildWikiDirPaths(nodes, spacePrefix)
}
// qualifyItemFileNames prefixes every fetched item's FileName with dir so
// ingestion derives the KB folder path. The prefix applies to the main item
// and to attachment/image sub-items alike — they all live in the same folder.
// An empty dir (node not in the current listing) or FileName is untouched.
func qualifyItemFileNames(items []*types.FetchedItem, dir string) {
if dir == "" {
return
}
for _, it := range items {
if it != nil && it.FileName != "" {
it.FileName = dir + "/" + it.FileName
}
}
}
@@ -0,0 +1,147 @@
package wiki
import (
"context"
"testing"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestWikiShortcutOutsideSelectionRemainsSyncable(t *testing.T) {
for _, resource := range []string{"space1", "space1:shortcut"} {
t.Run(resource, func(t *testing.T) {
shortcut := fileNode("shortcut", "reference.pdf", func(n *core.WikiNode) {
n.NodeType = "shortcut"
n.OriginNodeID = "outside"
n.OriginSpaceID = "space2"
n.HasChild = true
})
f := newFakeWikiTree(t, []core.WikiNode{shortcut}, map[string][]core.WikiNode{
"shortcut": {fileNode("child", "child.pdf")},
})
conn := NewConnector(core.RegionFeishu)
cfg := makeConfig(f.cfg, []string{resource})
items, cursor, err := conn.FetchIncremental(context.Background(), cfg, nil)
require.NoError(t, err)
require.Len(t, items, 2)
require.Equal(t, "shortcut", items[0].ExternalID)
require.Equal(t, "Test Space/reference.pdf/child.pdf", items[1].FileName)
items, _, err = conn.FetchIncremental(context.Background(), cfg, cursor)
require.NoError(t, err)
require.Empty(t, items, "unchanged shortcuts must not be deleted or fetched again")
})
}
}
func TestWikiShortcutDedupRequiresIndependentOrigin(t *testing.T) {
cases := []struct {
name string
nodes []core.WikiNode
want []string
}{
{"original in same listing", []core.WikiNode{
{NodeToken: "original", NodeType: "origin"},
{NodeToken: "shortcut", NodeType: "shortcut", OriginNodeID: "original"},
{NodeToken: "child", ParentNodeID: "shortcut"},
}, []string{"original"}},
{"original outside selected subtree", []core.WikiNode{
{NodeToken: "shortcut", NodeType: "shortcut", OriginNodeID: "outside"},
{NodeToken: "child", ParentNodeID: "shortcut"},
}, []string{"shortcut", "child"}},
{"origin exists only below shortcut", []core.WikiNode{
{NodeToken: "shortcut", NodeType: "shortcut", OriginNodeID: "original"},
{NodeToken: "original", ParentNodeID: "shortcut", NodeType: "origin"},
}, []string{"shortcut", "original"}},
{"mismatched origin space", []core.WikiNode{
{NodeToken: "original", NodeType: "origin", SpaceID: "space1"},
{NodeToken: "shortcut", NodeType: "shortcut", OriginNodeID: "original", OriginSpaceID: "space2"},
}, []string{"original", "shortcut"}},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
var ids []string
for _, n := range filterShortcutSubtrees(tt.nodes) {
ids = append(ids, n.NodeToken)
}
require.Equal(t, tt.want, ids)
})
}
}
func TestWikiAncestorChangesRefreshDescendants(t *testing.T) {
for _, change := range []string{"rename", "move"} {
t.Run(change, func(t *testing.T) {
parent := fileNode("parent", "Old", func(n *core.WikiNode) { n.HasChild = true })
f := newFakeWikiTree(t, []core.WikiNode{parent}, map[string][]core.WikiNode{
"parent": {fileNode("child", "child.pdf")},
})
conn := NewConnector(core.RegionFeishu)
cfg := makeConfig(f.cfg, []string{"space1"})
_, cursor, err := conn.FetchIncremental(context.Background(), cfg, nil)
require.NoError(t, err)
want := "Test Space/New/child.pdf"
if change == "rename" {
f.top[0].Title = "New"
f.top[0].NodeEditTime = "200"
} else {
parent.NodeEditTime = "200"
f.top = []core.WikiNode{fileNode("new-parent", "New", func(n *core.WikiNode) { n.HasChild = true })}
f.children["new-parent"] = []core.WikiNode{parent}
want = "Test Space/New/Old/child.pdf"
}
items, next, err := conn.FetchIncremental(context.Background(), cfg, cursor)
require.NoError(t, err)
var child *types.FetchedItem
for i := range items {
if items[i].ExternalID == "child" {
child = &items[i]
}
}
require.NotNil(t, child, "unchanged child must follow its ancestor's path")
require.Equal(t, want, child.FileName)
require.EqualValues(t, 100, child.UpdatedAt.Unix(), "source timestamp must remain the document's own")
items, _, err = conn.FetchIncremental(context.Background(), cfg, next)
require.NoError(t, err)
require.Empty(t, items)
})
}
}
func TestWikiLegacyTimestampCursorRefreshesOnce(t *testing.T) {
f := newFakeWikiTree(t, []core.WikiNode{fileNode("doc", "doc.pdf")}, nil)
conn := NewConnector(core.RegionFeishu)
cfg := makeConfig(f.cfg, []string{"space1"})
legacy := makeStreamCursor(t, map[string]map[string]string{"space1": {"doc": "100"}})
items, cursor, err := conn.FetchIncremental(context.Background(), cfg, legacy)
require.NoError(t, err)
require.Len(t, items, 1)
items, _, err = conn.FetchIncremental(context.Background(), cfg, cursor)
require.NoError(t, err)
require.Empty(t, items)
}
func TestWikiPartialListingKeepsAccessibleShortcut(t *testing.T) {
origin := fileNode("origin", "origin.pdf", func(n *core.WikiNode) { n.HasChild = true })
shortcut := fileNode("shortcut", "reference.pdf", func(n *core.WikiNode) {
n.NodeType = "shortcut"
n.OriginNodeID = "origin"
n.HasChild = true
})
server, cfg := fakeFeishuHierarchy([]core.WikiNode{origin, shortcut}, map[string][]core.WikiNode{
"shortcut": {fileNode("child", "child.pdf")},
}, "origin")
defer server.Close()
conn := NewConnector(core.RegionFeishu)
items, _, err := conn.FetchIncremental(context.Background(), makeConfig(cfg, []string{"space1"}), nil)
require.NoError(t, err)
var fetched []string
for _, item := range items {
if item.Metadata["error"] == "" {
fetched = append(fetched, item.ExternalID)
}
}
require.Contains(t, fetched, "shortcut")
require.Contains(t, fetched, "child", "a failed origin subtree must not suppress the accessible copy")
}
@@ -0,0 +1,282 @@
package wiki
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/datasource/connector/feishu/core"
"academy/internal/types"
)
// ──────────────────────────────────────────────────────────────────────
// P1 directory mapping tests: path-qualified FileName, shortcut subtree
// dedup, move/rename following, anchored against the fake wiki tree below.
// ──────────────────────────────────────────────────────────────────────
// fakeWikiTree serves a mutable wiki hierarchy: the test can rewrite the tree
// between sync runs to model moves/renames. All nodes are "file" obj_type so
// fetchDriveFile uses the node title verbatim as the base file name — the
// assertions then exercise only the path prefix logic under test.
type fakeWikiTree struct {
top []core.WikiNode
children map[string][]core.WikiNode
ts *httptest.Server
cfg *core.Config
}
func newFakeWikiTree(t *testing.T, top []core.WikiNode, children map[string][]core.WikiNode) *fakeWikiTree {
t.Helper()
f := &fakeWikiTree{top: top, children: children}
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, core.TokenResponse{
ApiResponse: core.ApiResponse{Code: 0},
TenantAccessToken: "fake-token", Expire: 7200,
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, core.WikiSpaceListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiSpaceListData{Items: []core.WikiSpace{{SpaceID: "space1", Name: "Test Space"}}},
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) {
parentToken := r.URL.Query().Get("parent_node_token")
nodes := f.top
if parentToken != "" {
nodes = f.children[parentToken]
for i := range nodes {
if nodes[i].ParentNodeID == "" {
nodes[i].ParentNodeID = parentToken
}
if nodes[i].SpaceID == "" {
nodes[i].SpaceID = "space1"
}
}
}
writeJSON(w, core.WikiNodeListResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiNodeListData{Items: nodes},
})
})
mux.HandleFunc("/open-apis/wiki/v2/spaces/get_node", func(w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("token")
for _, n := range f.top {
if n.NodeToken == token {
writeJSON(w, core.WikiNodeInfoResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiNodeInfoData{Node: n},
})
return
}
}
for _, group := range f.children {
for _, n := range group {
if n.NodeToken == token {
writeJSON(w, core.WikiNodeInfoResponse{
ApiResponse: core.ApiResponse{Code: 0},
Data: core.WikiNodeInfoData{Node: n},
})
return
}
}
}
writeJSON(w, core.WikiNodeInfoResponse{ApiResponse: core.ApiResponse{Code: 1663, Msg: "node not found"}})
})
// Drive download for "file" type nodes.
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("fake-file-content"))
return
}
http.NotFound(w, r)
})
f.ts = httptest.NewServer(mux)
t.Cleanup(f.ts.Close)
f.cfg = &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: f.ts.URL}
return f
}
func fileNode(token, title string, opts ...func(*core.WikiNode)) core.WikiNode {
n := core.WikiNode{
NodeToken: token,
ObjToken: "obj-" + token,
ObjType: "file",
NodeType: "origin",
Title: title,
NodeEditTime: "100",
}
for _, opt := range opts {
opt(&n)
}
return n
}
// TestWikiFetchAll_PathQualifiedMultiLevel anchors the multi-level directory
// mapping: the synced space mirrors as a top-level KB folder named after it,
// so paths are <空间名>/<目录A>/<目录B>/<文档名>, Chinese directory names kept
// as-is and "/" inside a directory name sanitised to "_" so it cannot fake an
// extra nesting level.
func TestWikiFetchAll_PathQualifiedMultiLevel(t *testing.T) {
f := newFakeWikiTree(t,
[]core.WikiNode{
fileNode("nt-dirA", "产品文档", func(n *core.WikiNode) { n.HasChild = true }),
fileNode("nt-top", "顶层.pdf"),
},
map[string][]core.WikiNode{
"nt-dirA": {
fileNode("nt-dirB", "子/目录", func(n *core.WikiNode) { n.HasChild = true }),
},
"nt-dirB": {
fileNode("nt-leaf", "规格说明.pdf"),
},
},
)
c := NewConnector(core.RegionFeishu)
items, err := c.FetchAll(context.Background(), makeConfig(f.cfg, []string{"space1"}), []string{"space1"})
if err != nil {
t.Fatalf("FetchAll() error: %v", err)
}
want := map[string]string{
// The synced space mirrors as a top-level KB folder ("Test Space" in
// the fake tree): every item's prefix starts with the space name,
// deeper items then carry the directory path. Base names are
// sanitised like directory segments: a "/" in a title must not fake
// an extra folder level (nt-dirB), while the directory path prefix
// is built from the sanitised folder name (nt-leaf).
"nt-dirA": "Test Space/产品文档",
"nt-top": "Test Space/顶层.pdf",
"nt-dirB": "Test Space/产品文档/子_目录",
"nt-leaf": "Test Space/产品文档/子_目录/规格说明.pdf",
}
got := make(map[string]string, len(items))
for _, item := range items {
got[item.ExternalID] = item.FileName
}
if len(got) != len(want) {
t.Fatalf("got %d items (%v), want %d", len(got), got, len(want))
}
for id, wantPath := range want {
if got[id] != wantPath {
t.Errorf("FileName for %s = %q, want %q", id, got[id], wantPath)
}
}
}
// TestWikiFetchAll_ShortcutSubtreeDeduped anchors the shortcut dedup: a
// shortcut node and its whole subtree are skipped — the origin entity is
// enumerated at its real location, so the shortcut would duplicate it.
func TestWikiFetchAll_ShortcutSubtreeDeduped(t *testing.T) {
origin := fileNode("nt-origin", "origin.pdf")
shortcut := fileNode("nt-shortcut", "origin.pdf", func(n *core.WikiNode) {
n.NodeType = "shortcut"
n.OriginNodeID = "nt-origin"
n.HasChild = true
})
f := newFakeWikiTree(t,
[]core.WikiNode{origin, shortcut},
map[string][]core.WikiNode{
// The client's recursive walk descends into the shortcut (HasChild),
// so the listing contains the origin's subtree a second time.
"nt-shortcut": {fileNode("nt-under-shortcut", "duplicate.pdf")},
},
)
c := NewConnector(core.RegionFeishu)
items, cursor, err := c.FetchIncremental(context.Background(), makeConfig(f.cfg, []string{"space1"}), nil)
if err != nil {
t.Fatalf("FetchIncremental() error: %v", err)
}
if len(items) != 1 {
t.Fatalf("expected exactly 1 item (the origin), got %d: %+v", len(items), items)
}
if items[0].ExternalID != "nt-origin" {
t.Errorf("item ExternalID = %q, want nt-origin", items[0].ExternalID)
}
// The cursor must only record the kept node, so the filtered shortcut and
// its subtree do not linger as ghosts.
var fc core.FeishuCursor
b, _ := json.Marshal(cursor.ConnectorCursor)
_ = json.Unmarshal(b, &fc)
times := fc.SpaceNodeTimes["space1"]
if _, ok := times["nt-shortcut"]; ok {
t.Error("cursor records the skipped shortcut node")
}
if _, ok := times["nt-under-shortcut"]; ok {
t.Error("cursor records a node under the skipped shortcut subtree")
}
if _, ok := times["nt-origin"]; !ok {
t.Error("cursor missing the origin node")
}
}
// TestWikiFetchIncremental_MoveFollowsNewPath anchors the move/rename story:
// the external_id is unchanged, and once the node's edit time moves the next
// sync re-fetches it under the NEW directory path. Ingestion's
// update=delete+recreate then lands the knowledge row in the new folder_path.
func TestWikiFetchIncremental_MoveFollowsNewPath(t *testing.T) {
doc := fileNode("nt-doc", "文档.pdf", func(n *core.WikiNode) { n.NodeEditTime = "100" })
f := newFakeWikiTree(t,
[]core.WikiNode{
fileNode("nt-dirA", "目录A", func(n *core.WikiNode) { n.HasChild = true }),
},
map[string][]core.WikiNode{"nt-dirA": {doc}},
)
c := NewConnector(core.RegionFeishu)
cfg := makeConfig(f.cfg, []string{"space1"})
items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
if err != nil {
t.Fatalf("first sync error: %v", err)
}
if len(items1) != 2 {
t.Fatalf("first sync: expected 2 items (dir + doc), got %d: %+v", len(items1), items1)
}
var docItem *types.FetchedItem
for i := range items1 {
if items1[i].ExternalID == "nt-doc" {
docItem = &items1[i]
}
}
if docItem == nil || docItem.FileName != "Test Space/目录A/文档.pdf" {
t.Fatalf("first sync: doc item missing or wrong path: %+v", items1)
}
// Move the doc from 目录A to a new top-level 目录B; the edit time moves so
// the incremental fast-path does not skip it.
f.top = append(f.top, fileNode("nt-dirB", "目录B", func(n *core.WikiNode) { n.HasChild = true }))
f.children = map[string][]core.WikiNode{
"nt-dirB": {fileNode("nt-doc", "文档.pdf", func(n *core.WikiNode) { n.NodeEditTime = "200" })},
}
items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
if err != nil {
t.Fatalf("second sync error: %v", err)
}
var moved *types.FetchedItem
for i := range items2 {
if items2[i].ExternalID == "nt-doc" && !items2[i].IsDeleted {
moved = &items2[i]
}
}
if moved == nil {
t.Fatalf("moved doc not re-fetched on second sync: %+v", items2)
}
if moved.FileName != "Test Space/目录B/文档.pdf" {
t.Errorf("moved doc FileName = %q, want %q (same external_id, new folder)",
moved.FileName, "Test Space/目录B/文档.pdf")
}
}