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
+24
View File
@@ -25,6 +25,29 @@ export interface DataSource {
latest_sync_log?: SyncLog
}
/**
* One user-facing failure sample. The backend sends a stable i18n `code`
* (+ interpolation `params`) so the UI localises it to the viewer's language;
* `message` is a fallback when no i18n key exists (old logs decode into it).
*/
export interface SyncItemError {
title?: string
code?: string
params?: Record<string, string>
message?: string
}
export interface SyncResultDetail {
total?: number
created?: number
updated?: number
deleted?: number
skipped?: number
failed?: number
/** Per-item failure samples (capped); localised in the sync-log drawer. */
errors?: SyncItemError[]
}
export interface SyncLog {
id: string
data_source_id: string
@@ -38,6 +61,7 @@ export interface SyncLog {
items_skipped: number
items_failed: number
error_message: string
result?: SyncResultDetail
}
export interface ConnectorMeta {
+13
View File
@@ -6216,6 +6216,19 @@ export default {
startTime: 'Started',
endTime: 'Finished',
duration: 'Duration',
failedItems: 'Failed documents',
failedItemsMore: '{n} more failed documents not shown',
docsFailedSummary: '{n} document(s) failed to sync',
},
syncError: {
feishu_auth_or_permission: 'Authentication or permission error; check credentials and app permissions',
feishu_rate_limited: 'Feishu API rate limited; will retry on the next sync',
feishu_timeout: 'Export or request timed out; will retry on the next sync',
feishu_server_unavailable: 'Feishu service temporarily unavailable; will retry on the next sync',
feishu_api_error: 'Feishu API error (code={code}); will retry on the next sync',
feishu_api_error_generic: 'Feishu API error; will retry on the next sync',
sync_failed: 'Sync failed; will retry on the next sync',
ingest_failed: 'Ingest failed; see server logs',
},
connector: {
feishu: 'Feishu',
+13
View File
@@ -6221,6 +6221,19 @@ export default {
startTime: "시작 시간",
endTime: "종료 시간",
duration: "소요 시간",
failedItems: "실패한 문서",
failedItemsMore: "표시되지 않은 실패 문서 {n}개",
docsFailedSummary: "문서 {n}개 동기화 실패",
},
syncError: {
feishu_auth_or_permission: "인증 또는 권한 부족: 자격 증명과 앱 권한을 확인하세요",
feishu_rate_limited: "Feishu API 요청 제한, 다음 동기화 시 다시 시도합니다",
feishu_timeout: "문서 내보내기 또는 요청 시간 초과, 다음 동기화 시 다시 시도합니다",
feishu_server_unavailable: "Feishu 서비스가 일시적으로 사용 불가, 다음 동기화 시 다시 시도합니다",
feishu_api_error: "Feishu API 오류(code={code}), 다음 동기화 시 다시 시도합니다",
feishu_api_error_generic: "Feishu API 오류, 다음 동기화 시 다시 시도합니다",
sync_failed: "동기화 실패, 다음 동기화 시 다시 시도합니다",
ingest_failed: "가져오기 실패, 서버 로그를 확인하세요",
},
connector: {
feishu: "페이슈 (Feishu)",
+13
View File
@@ -6042,6 +6042,19 @@ export default {
startTime: 'Время начала',
endTime: 'Время окончания',
duration: 'Длительность',
failedItems: 'Документы с ошибкой',
failedItemsMore: 'Ещё {n} документов с ошибкой не показаны',
docsFailedSummary: 'Не удалось синхронизировать документов: {n}',
},
syncError: {
feishu_auth_or_permission: 'Ошибка аутентификации или недостаточно прав; проверьте учётные данные и права приложения',
feishu_rate_limited: 'Превышен лимит запросов к API Feishu; повтор при следующей синхронизации',
feishu_timeout: 'Тайм-аут экспорта или запроса; повтор при следующей синхронизации',
feishu_server_unavailable: 'Сервис Feishu временно недоступен; повтор при следующей синхронизации',
feishu_api_error: 'Ошибка API Feishu (code={code}); повтор при следующей синхронизации',
feishu_api_error_generic: 'Ошибка API Feishu; повтор при следующей синхронизации',
sync_failed: 'Ошибка синхронизации; повтор при следующей синхронизации',
ingest_failed: 'Ошибка импорта; смотрите логи сервера',
},
connector: {
feishu: 'Feishu (Фэйшу)',
+13
View File
@@ -6241,6 +6241,19 @@ export default {
startTime: "开始时间",
endTime: "结束时间",
duration: "耗时",
failedItems: "失败文档",
failedItemsMore: "还有 {n} 个失败文档未显示",
docsFailedSummary: "{n} 个文档同步失败",
},
syncError: {
feishu_auth_or_permission: "应用鉴权或权限不足,请检查凭证与应用权限",
feishu_rate_limited: "飞书接口限流,下次同步时将重试",
feishu_timeout: "文档导出或请求超时,下次同步时将重试",
feishu_server_unavailable: "飞书服务暂时不可用,下次同步时将重试",
feishu_api_error: "飞书接口错误(code={code}),下次同步时将重试",
feishu_api_error_generic: "飞书接口错误,下次同步时将重试",
sync_failed: "同步失败,下次同步时将重试",
ingest_failed: "入库失败,详情见服务日志",
},
connector: {
feishu: "飞书",
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { getSyncLogs, type SyncLog } from '@/api/datasource'
import { getSyncLogs, type SyncLog, type SyncItemError } from '@/api/datasource'
const props = defineProps<{
dataSourceId: string
@@ -131,6 +131,30 @@ function hasPills(log: SyncLog) {
return log.items_created > 0 || log.items_updated > 0 || log.items_deleted > 0 || log.items_skipped > 0 || log.items_failed > 0
}
// Cap the per-item failure list so a sync that failed thousands of documents
// doesn't render an unbounded wall of text; the remainder is summarised.
const FAILED_ITEMS_CAP = 50
function failedItems(log: SyncLog): SyncItemError[] {
return (log.result?.errors || []).slice(0, FAILED_ITEMS_CAP)
}
// Render one failure sample. The backend sends a stable i18n `code` (+ params)
// so the reason is localised to the viewer's language; `message` is the fallback
// for old logs / codes this client doesn't know. The document title is kept
// separate and prefixed as "title — reason".
function formatSyncError(e: SyncItemError): string {
let reason = ''
if (e.code) {
const key = `datasource.syncError.${e.code}`
const localised = t(key, (e.params || {}) as Record<string, unknown>)
reason = localised === key ? (e.message || e.code) : localised
} else {
reason = e.message || ''
}
return e.title ? (reason ? `${e.title} — ${reason}` : e.title) : reason
}
// Group logs by date
const groupedLogs = computed(() => {
const groups: { date: string; logs: SyncLog[] }[] = []
@@ -253,9 +277,29 @@ const groupedLogs = computed(() => {
<span class="detail-label">{{ t('datasource.logMetric.total') }}</span>
<span>{{ log.items_total }}</span>
</div>
<div v-if="log.error_message" class="tl-error">
<!-- Localised failure summary; raw error_message only for a
pure infra failure with no per-document detail. -->
<div v-if="log.items_failed > 0" class="tl-error">
{{ t('datasource.logDetail.docsFailedSummary', { n: log.items_failed }) }}
</div>
<div v-else-if="log.error_message" class="tl-error">
{{ log.error_message }}
</div>
<!-- Per-item failures: which documents failed and why.
The true count is items_failed (a bounded int); result.errors
is only a capped sample the backend retains for display. -->
<div v-if="failedItems(log).length" class="tl-failed">
<div class="tl-failed-title">
{{ t('datasource.logDetail.failedItems') }} ({{ log.items_failed }})
</div>
<div v-for="(e, i) in failedItems(log)" :key="i" class="tl-failed-item" :title="formatSyncError(e)">
{{ formatSyncError(e) }}
</div>
<div v-if="log.items_failed > failedItems(log).length" class="tl-failed-more">
{{ t('datasource.logDetail.failedItemsMore', { n: (log.items_failed - failedItems(log).length) }) }}
</div>
</div>
</div>
</div>
</div>
@@ -513,6 +557,39 @@ const groupedLogs = computed(() => {
word-break: break-word;
}
/* --- Per-item failure list --- */
.tl-failed {
margin-top: 8px;
display: flex;
flex-direction: column;
gap: 2px;
}
.tl-failed-title {
font-size: 11px;
font-weight: 600;
color: var(--td-error-color);
margin-bottom: 2px;
}
.tl-failed-item {
font-size: 11px;
line-height: 1.5;
color: var(--td-text-color-secondary);
padding: 2px 8px;
border-left: 2px solid var(--td-error-color-3);
background: var(--td-bg-color-container);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tl-failed-more {
font-size: 11px;
color: var(--td-text-color-placeholder);
padding: 2px 8px;
}
/* --- Drawer header --- */
.logs-drawer-header {
display: flex;