fix(feishu): resilient large-wiki sync — retry, streaming resume, failure visibility

Large Feishu wikis stopped syncing after the first batch (Tencent/WeKnora#2136:
5000+ docs, only ~150 ingested; #1262: a child-list failure aborted the run).
Three compounding causes, fixed in layers:

1. Rate-limit / transient failures had no retry. Feishu's wiki/drive/export
   APIs are aggressively rate limited; a thousand-doc sync issues tens of
   thousands of calls, and a single 429/5xx burst failed whole swathes of docs.
   Add exponential backoff honouring Retry-After to doRequest (JSON) and
   downloadRawBytes (files): 429 up to 3x, 5xx once, transport errors back off.

2. The batch path fetched the entire tree into memory before ingesting, so a
   sync that hit the 2h task timeout lost all progress and restarted from
   scratch, and a transient per-document export failure advanced the cursor and
   skipped that doc permanently. Add an optional StreamingConnector interface,
   implemented for Feishu: FetchStream interleaves fetch -> ingest -> checkpoint,
   bounding memory to one item and persisting a per-node edit-time cursor at
   page boundaries. The service dispatches to it via type assertion; connectors
   without it fall back to FetchAll / FetchIncremental unchanged (non-breaking).
   A resumed/incremental run skips nodes already recorded at their current edit
   time (converges), a failed fetch does not advance the cursor (retried next
   run instead of dropped), and partial listing failures emit error items and
   carry prior edit times forward instead of aborting the sync.

3. Failures and skips were invisible. Unsupported node types (mindnote/slides/…)
   were skipped with no item, error or log ("13 docs synced only 3"). FetchAll
   now tallies discovered/fetched/failed/skipped per resource with a per-type
   skip breakdown and a progress line every 100 nodes. The backend already
   persisted per-item errors in SyncLog.result.errors but the frontend type
   omitted the field; declare `result` on SyncLog and render up to 50 failed
   documents in the sync-log drawer (#1262). i18n for zh-CN/en-US/ko-KR/ru-RU.
   result.errors is a jsonb column shipped in every list response, so it is
   capped at 100 samples server-side (recordSyncError); the exact failure total
   comes from the bounded items_failed counter, which the drawer uses for its
   count and "N more" line so a sync that fails thousands of docs stays bounded.
   Each sample is a structured, localisable SyncItemError instead of a raw
   "title: ...api error: status=500 body={json}" dump that repeated the title
   and leaked status/body/log_id. The connector (feishuFailure) classifies the
   error into a stable i18n code (+ the feishu code as a param); the service
   builds {title, code, params, message}; the drawer localises via vue-i18n to
   the viewer's language (zh/en/ko/ru), falling back to message. A custom
   UnmarshalJSON keeps old string-form logs readable. The banner is localised
   from items_failed too. Raw errors stay in the server logs. Follows the
   two-tier norm of Airbyte/Fivetran/Onyx: human, actionable, localised
   summaries in the UI; raw detail in logs. Transient errors say "will retry"
   (the cursor is retained); auth/permission errors point at the fix instead.

Tests: client_retry_test (backoff), tally_test (accounting), connector_stream /
datasource_stream (streaming dispatch + checkpoint), connector_convergence
(timeout + transient-failure resume converges to full coverage; proven to catch
#2136 via bug injection), datasource_result_cap (error-sample cap + structured
localisable SyncItemError, no raw body), connector_error_reason (error→i18n-code
classification), sync_item_error (legacy-string + structured back-compat) — all
in the normal suite. connector_realapi / connector_seed are an opt-in real-Feishu
harness gated by the feishu_integration build tag AND env vars, never run in CI.
This commit is contained in:
nullkey
2026-07-21 00:20:57 +08:00
committed by lyingbug
parent 74cdd7cdd0
commit c695125dce
23 changed files with 2565 additions and 125 deletions
+49 -2
View File
@@ -358,13 +358,60 @@ type SyncResult struct {
// Items that failed
Failed int `json:"failed"`
// Detailed error messages
Errors []string `json:"errors,omitempty"`
// Per-item failure samples (capped), shown in the sync-log UI.
Errors []SyncItemError `json:"errors,omitempty"`
// Updated cursor for next incremental sync
NextCursor *SyncCursor `json:"next_cursor,omitempty"`
}
// SyncItemError is one user-facing failure sample. It carries a stable i18n
// Code (+ interpolation Params) so the frontend localises it to the viewer's
// language, plus a Message fallback for clients without the key. The raw API
// status/body/log_id is never stored here — that stays in the server logs.
type SyncItemError struct {
// Title is the document title (user content, not translated).
Title string `json:"title,omitempty"`
// Code is a stable key the frontend maps to a localized string, e.g.
// "feishu_rate_limited" → datasource.syncError.feishu_rate_limited.
Code string `json:"code,omitempty"`
// Params are interpolation values for the localized string, e.g. {"code":"1663"}.
Params map[string]string `json:"params,omitempty"`
// Message is a human fallback used when the client has no i18n key for Code.
Message string `json:"message,omitempty"`
}
// Display renders the sample as a single plain string for server-side use
// (logs, fatal-error detail). The localised UI string is built on the frontend
// from Code/Params; this is only a non-localised fallback.
func (e SyncItemError) Display() string {
switch {
case e.Title != "" && e.Message != "":
return e.Title + ": " + e.Message
case e.Message != "":
return e.Message
default:
return e.Title
}
}
// UnmarshalJSON keeps old sync logs readable: historically each error was a
// plain JSON string, so a bare string decodes into Message.
func (e *SyncItemError) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err == nil {
e.Message = s
return nil
}
type alias SyncItemError
var a alias
if err := json.Unmarshal(b, &a); err != nil {
return err
}
*e = SyncItemError(a)
return nil
}
// DataSourceSyncPayload represents the asynq task payload for data source sync
type DataSourceSyncPayload struct {
TracingContext
+44
View File
@@ -0,0 +1,44 @@
package types
import (
"encoding/json"
"testing"
)
// SyncResult.Errors is persisted as jsonb and read back when the sync-log drawer
// is opened. Historically each entry was a plain string; it is now a structured
// SyncItemError (title + i18n code + params + fallback message) so the frontend
// can localise it. Old rows must still deserialize, so a bare string decodes into
// the Message field.
func TestSyncItemError_UnmarshalAcceptsLegacyStringAndObject(t *testing.T) {
// Legacy format: array of plain strings.
var legacy []SyncItemError
if err := json.Unmarshal([]byte(`["季度报告: export failed"]`), &legacy); err != nil {
t.Fatalf("legacy string form must still decode: %v", err)
}
if len(legacy) != 1 || legacy[0].Message != "季度报告: export failed" {
t.Fatalf("legacy string should map to Message, got %+v", legacy)
}
if legacy[0].Code != "" {
t.Errorf("legacy string must not invent a code, got %q", legacy[0].Code)
}
// New format: structured object round-trips.
in := SyncItemError{
Title: "季度报告",
Code: "feishu_api_error",
Params: map[string]string{"code": "1663"},
Message: "Feishu API error (code=1663); will retry",
}
b, err := json.Marshal([]SyncItemError{in})
if err != nil {
t.Fatalf("marshal: %v", err)
}
var out []SyncItemError
if err := json.Unmarshal(b, &out); err != nil {
t.Fatalf("unmarshal structured: %v", err)
}
if len(out) != 1 || out[0].Code != "feishu_api_error" || out[0].Params["code"] != "1663" || out[0].Title != "季度报告" {
t.Fatalf("structured form did not round-trip: %+v", out)
}
}