fix(feishu): 多维表格字段分页补重复 page_token 防护与条数上限 (#3840)
内嵌多维表格的 list-fields 分页循环只判断 has_more 与 token 是否为空: 厂商在 has_more=true 时返回已读过的 page_token,循环就会反复请求同一页并把 同一批字段重复追加进 cols,直到任务 deadline(实测 2s 内 5 万余次请求仍未 返回)。该循环也是同文件里唯一既无去重、又无尺寸上限的分页循环。 - 按同库 wiki 空间/节点与云盘分页已有写法加 seenFieldPageTokens 集合,重复的 非空 token 立即返回 error,不再静默当作读完; - 补 maxBitableFields = 5000 的条数上限,命中时 Warn 并截断。 测试:重复 token 在第二次出现时报错并停止请求;厂商每页都返回新 token 时在 第 5000 个字段处停止并打 Warn;正常 100 条/页 分页不受影响。 Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>main
parent
0d3a053eb6
commit
b5c74b2dd6
|
|
@ -344,6 +344,12 @@ type bitableFieldsResponse struct {
|
|||
// 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"`
|
||||
|
|
@ -376,6 +382,7 @@ func (c *Client) readBitableRecords(ctx context.Context, embedToken string) ([][
|
|||
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 != "" {
|
||||
|
|
@ -396,13 +403,26 @@ func (c *Client) readBitableRecords(ctx context.Context, embedToken string) ([][
|
|||
cols = append(cols, bitableColumn{name: f.FieldName, fieldType: f.Type, dateFormatter: formatter})
|
||||
}
|
||||
if len(fieldsResp.Data.Items) == 0 {
|
||||
// Defensive: an empty page with has_more=true would loop forever (this
|
||||
// loop has no size cap of its own). Nothing more to read, so stop.
|
||||
// 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
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,14 +1,18 @@
|
|||
package core
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
func TestListDocumentBlocks_Paginates(t *testing.T) {
|
||||
|
|
@ -464,8 +468,8 @@ func TestReadBitableRecords_EmptyRecordPageTerminates(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestReadBitableRecords_EmptyFieldsPageTerminates guards the fields loop, which
|
||||
// has no size cap of its own — an empty page with has_more=true must still break.
|
||||
// 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) {
|
||||
|
|
@ -526,3 +530,103 @@ func TestListDocumentBlocks_EmptyPageTerminates(t *testing.T) {
|
|||
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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue