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
@@ -0,0 +1,67 @@
package service
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
)
// A sync that fails thousands of documents must not accumulate an unbounded
// result.Errors slice: that slice is persisted as jsonb and shipped in every
// sync-log list response, so an uncapped list means multi-MB rows and payloads.
// The accurate count lives in result.Failed (a bounded int), so Errors only
// needs to retain a sample for display (Tencent/WeKnora#2136 / #1262).
func TestApplyFetchedItem_CapsErrorSampleButKeepsAccurateFailedCount(t *testing.T) {
s := &DataSourceService{}
ds := &types.DataSource{}
result := &types.SyncResult{}
ctx := context.Background()
const failures = 5000
for i := 0; i < failures; i++ {
s.applyFetchedItem(ctx, ds, &types.FetchedItem{
ExternalID: "node",
Title: "doc",
Metadata: map[string]string{"error": "export failed: rate limited"},
}, nil, result)
}
assert.Equal(t, failures, result.Failed,
"Failed must count every failure regardless of the error-sample cap")
assert.LessOrEqual(t, len(result.Errors), maxSyncResultErrors,
"Errors sample must be capped so the persisted jsonb stays bounded")
assert.Equal(t, maxSyncResultErrors, len(result.Errors),
"with more failures than the cap, the sample should be exactly the cap")
}
// The user-facing sample must be a structured SyncItemError carrying the
// connector's stable i18n code + params (so the frontend localises it), the
// title as a separate field, and no raw API body/log_id — that stays in logs.
func TestApplyFetchedItem_ProducesLocalisableStructuredError(t *testing.T) {
s := &DataSourceService{}
ds := &types.DataSource{}
result := &types.SyncResult{}
s.applyFetchedItem(context.Background(), ds, &types.FetchedItem{
ExternalID: "nt1",
Title: "季度报告",
Metadata: map[string]string{
// raw, for logs only
"error": `export 季度报告 (docx): feishu api error: status=500 body={"code":1663,"error":{"log_id":"20260"}}`,
// classification, for a localisable UI sample
"error_reason_code": "feishu_api_error",
"error_reason_code_value": "1663",
"error_reason": "Feishu API error (code=1663); will retry automatically",
},
}, nil, result)
assert.Equal(t, 1, len(result.Errors))
got := result.Errors[0]
assert.Equal(t, "季度报告", got.Title, "title is a separate field, not embedded in the message")
assert.Equal(t, "feishu_api_error", got.Code, "stable i18n code drives frontend localisation")
assert.Equal(t, "1663", got.Params["code"], "feishu error code is passed as an interpolation param")
assert.NotContains(t, got.Message, "body=", "raw API body must not reach the UI sample")
assert.NotContains(t, got.Message, "log_id", "raw log_id must not reach the UI sample")
}
@@ -625,6 +625,13 @@ func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) e
return err
}
// Streaming path: connectors that support it interleave fetch→ingest→
// checkpoint so a large sync bounds memory and resumes after a timeout
// instead of restarting (Tencent/WeKnora#2136). Others fall back below.
if sc, ok := connector.(datasource.StreamingConnector); ok {
return s.processSyncStreaming(ctx, sc, ds, syncLog, config, payload, wasPaused)
}
// Fetch items based on sync mode
var items []types.FetchedItem
var nextCursor *types.SyncCursor
@@ -697,56 +704,11 @@ func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) e
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenant)
// Auto-tag: find or create a tag for this data source so synced items are easily identifiable
autoTagIDs := []string{}
autoTagName := ds.Name
if autoTag, tagErr := s.tagService.FindOrCreateTagByName(ctx, ds.KnowledgeBaseID, autoTagName); tagErr != nil {
logger.Warnf(ctx, "failed to find/create auto-tag %q: %v (proceeding without tag)", autoTagName, tagErr)
} else if autoTag != nil {
autoTagIDs = append(autoTagIDs, autoTag.ID)
logger.Infof(ctx, "using auto-tag %q (id=%s) for data source sync", autoTagName, autoTag.ID)
}
autoTagIDs := s.resolveAutoTagIDs(ctx, ds)
for _, item := range items {
if item.IsDeleted {
if ds.SyncDeletions {
// Count only — actual KB deletion is intentionally not performed.
// Users manage knowledge removal explicitly via the KB UI to avoid
// accidental data loss from connector misdetection or reconfiguration.
result.Deleted++
}
continue
}
if len(item.Content) == 0 && item.URL == "" {
// Check if this is an error item from the connector (failed to fetch content)
if errMsg, hasErr := item.Metadata["error"]; hasErr {
logger.Warnf(ctx, "item %q (external_id=%s) fetch failed: %s", item.Title, item.ExternalID, errMsg)
result.Failed++
result.Errors = append(result.Errors, fmt.Sprintf("%s: %s", item.Title, errMsg))
} else {
logger.Infof(ctx, "skipping item %q (external_id=%s): no content or URL", item.Title, item.ExternalID)
result.Skipped++
}
continue
}
isUpdate, err := s.ingestItem(ctx, ds, &item, autoTagIDs)
if err != nil {
// Duplicate file/URL is not a failure — count as skipped
var dupErr *types.DuplicateKnowledgeError
if errors.As(err, &dupErr) {
logger.Infof(ctx, "item %q (external_id=%s) already exists, skipping", item.Title, item.ExternalID)
result.Skipped++
} else {
logger.Warnf(ctx, "failed to ingest item %q (external_id=%s): %v", item.Title, item.ExternalID, err)
result.Failed++
result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", item.Title, err))
}
} else if isUpdate {
result.Updated++
} else {
result.Created++
}
item := item
s.applyFetchedItem(ctx, ds, &item, autoTagIDs, result)
}
resultJSON, _ := result.ToJSON()
@@ -769,7 +731,7 @@ func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) e
syncStatus = types.SyncLogStatusPartial
syncErrorMessage = fmt.Sprintf("Some feeds failed: %s", strings.Join(fetchWarnings, "; "))
for _, w := range fetchWarnings {
result.Errors = append(result.Errors, w)
result.Errors = append(result.Errors, types.SyncItemError{Message: w})
}
resultJSON, _ = result.ToJSON()
}
@@ -781,6 +743,253 @@ func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) e
return nil
}
// resolveAutoTagIDs finds or creates the per-data-source tag applied to every
// synced item so results are identifiable in the KB. A tag failure is
// non-fatal: the sync proceeds untagged.
func (s *DataSourceService) resolveAutoTagIDs(ctx context.Context, ds *types.DataSource) []string {
autoTagIDs := []string{}
if autoTag, tagErr := s.tagService.FindOrCreateTagByName(ctx, ds.KnowledgeBaseID, ds.Name); tagErr != nil {
logger.Warnf(ctx, "failed to find/create auto-tag %q: %v (proceeding without tag)", ds.Name, tagErr)
} else if autoTag != nil {
autoTagIDs = append(autoTagIDs, autoTag.ID)
logger.Infof(ctx, "using auto-tag %q (id=%s) for data source sync", ds.Name, autoTag.ID)
}
return autoTagIDs
}
// maxSyncResultErrors bounds the per-item error sample retained in
// SyncResult.Errors. That slice is persisted as jsonb and returned in every
// sync-log list response, so an unbounded list on a sync that fails thousands of
// documents means multi-MB DB rows and payloads. The accurate failure count
// lives in SyncResult.Failed (a bounded int); this list only keeps a sample for
// display (Tencent/WeKnora#2136 / #1262).
const maxSyncResultErrors = 100
// recordSyncError appends an error sample to result.Errors, capped at
// maxSyncResultErrors. Callers still increment result.Failed for the exact count.
func recordSyncError(result *types.SyncResult, item types.SyncItemError) {
if len(result.Errors) < maxSyncResultErrors {
result.Errors = append(result.Errors, item)
}
}
// fetchFailureSyncError maps a connector error item into a structured, user-
// facing sample. Connectors that classify their errors (Feishu) provide a stable
// i18n code + params via metadata so the frontend localises it to the viewer's
// language; the raw status/body/log_id never leaves the server logs. Connectors
// without codes keep the raw text as a Message fallback. Best practice per
// Airbyte/Fivetran/Onyx: humanised, actionable, localised UI; raw detail in logs.
func fetchFailureSyncError(item *types.FetchedItem, rawMsg string) types.SyncItemError {
e := types.SyncItemError{Title: item.Title}
if code := item.Metadata["error_reason_code"]; code != "" {
e.Code = code
if v := item.Metadata["error_reason_code_value"]; v != "" {
e.Params = map[string]string{"code": v}
}
e.Message = item.Metadata["error_reason"] // fallback if the client lacks the key
} else {
e.Message = rawMsg
}
return e
}
// applyFetchedItem writes a single fetched item into the knowledge base and
// updates result counters. It is the shared core of the batch loop and the
// streaming handler so item classification (deleted / empty / ingest outcome)
// stays identical across both fetch paths.
func (s *DataSourceService) applyFetchedItem(
ctx context.Context, ds *types.DataSource, item *types.FetchedItem,
tagIDs []string, result *types.SyncResult,
) {
if item.IsDeleted {
if ds.SyncDeletions {
// Count only — actual KB deletion is intentionally not performed.
// Users manage knowledge removal explicitly via the KB UI to avoid
// accidental data loss from connector misdetection or reconfiguration.
result.Deleted++
}
return
}
if len(item.Content) == 0 && item.URL == "" {
// Check if this is an error item from the connector (failed to fetch content)
if errMsg, hasErr := item.Metadata["error"]; hasErr {
logger.Warnf(ctx, "item %q (external_id=%s) fetch failed: %s", item.Title, item.ExternalID, errMsg)
result.Failed++
recordSyncError(result, fetchFailureSyncError(item, errMsg))
} else {
logger.Infof(ctx, "skipping item %q (external_id=%s): no content or URL", item.Title, item.ExternalID)
result.Skipped++
}
return
}
isUpdate, err := s.ingestItem(ctx, ds, item, tagIDs)
if err != nil {
// Duplicate file/URL is not a failure — count as skipped
var dupErr *types.DuplicateKnowledgeError
if errors.As(err, &dupErr) {
logger.Infof(ctx, "item %q (external_id=%s) already exists, skipping", item.Title, item.ExternalID)
result.Skipped++
} else {
logger.Warnf(ctx, "failed to ingest item %q (external_id=%s): %v", item.Title, item.ExternalID, err)
result.Failed++
recordSyncError(result, types.SyncItemError{
Title: item.Title,
Code: "ingest_failed",
Message: "Ingest failed; see server logs",
})
}
} else if isUpdate {
result.Updated++
} else {
result.Created++
}
}
// streamStartCursor decides which cursor a streaming fetch should resume from.
// A user-triggered full sync on its first attempt drops the cursor so every
// item is re-fetched; a retried full sync (attempt > 0) and every incremental
// sync resume from the last persisted checkpoint so a timed-out run converges
// instead of restarting from scratch.
func streamStartCursor(ds *types.DataSource, forceFull bool, attempt int) (*types.SyncCursor, error) {
if forceFull && attempt == 0 {
return nil, nil
}
return ds.ParseSyncCursor()
}
// streamSyncHandler adapts a streaming fetch to the knowledge-base ingest path.
// Emit ingests each item as it arrives (bounding memory) and Checkpoint persists
// the connector cursor plus live progress counts at page boundaries.
type streamSyncHandler struct {
svc *DataSourceService
ds *types.DataSource
tagIDs []string
result *types.SyncResult
syncLog *types.SyncLog
}
// Emit ingests one streamed item. A canceled context aborts the stream so the
// connector stops fetching; per-item ingest failures are recorded in result and
// do NOT abort (matching the batch loop, which never fails the whole sync for
// one bad document).
func (h *streamSyncHandler) Emit(ctx context.Context, item types.FetchedItem) error {
if err := ctx.Err(); err != nil {
return err
}
h.result.Total++
h.svc.applyFetchedItem(ctx, h.ds, &item, h.tagIDs, h.result)
return nil
}
// Checkpoint persists the connector cursor onto the data source and mirrors the
// running counts into the sync log so progress survives a crash and the UI can
// reflect a long sync mid-flight instead of jumping from 0 to done.
func (h *streamSyncHandler) Checkpoint(ctx context.Context, cursor *types.SyncCursor) error {
if cursor == nil {
return nil
}
cursorJSON, err := cursor.ToJSON()
if err != nil {
return err
}
h.ds.LastSyncCursor = cursorJSON
if err := h.svc.dsRepo.UpdateSyncState(ctx, h.ds); err != nil {
return err
}
// Best-effort live progress; a failure here must not abort the sync.
h.syncLog.ItemsTotal = h.result.Total
h.syncLog.ItemsCreated = h.result.Created
h.syncLog.ItemsUpdated = h.result.Updated
h.syncLog.ItemsDeleted = h.result.Deleted
h.syncLog.ItemsSkipped = h.result.Skipped
h.syncLog.ItemsFailed = h.result.Failed
if err := h.svc.syncLogRepo.UpdateResult(ctx, h.syncLog); err != nil {
logger.Warnf(ctx, "failed to persist sync log progress at checkpoint: %v", err)
}
return nil
}
// processSyncStreaming runs a sync through a StreamingConnector, ingesting each
// item as it arrives and checkpointing progress so the run is memory-bounded and
// resumable after a timeout.
func (s *DataSourceService) processSyncStreaming(
ctx context.Context, sc datasource.StreamingConnector,
ds *types.DataSource, syncLog *types.SyncLog,
config *types.DataSourceConfig, payload types.DataSourceSyncPayload, wasPaused bool,
) error {
// Tenant + auto-tag setup must precede fetching because the stream ingests
// each item on the fly.
ctx = context.WithValue(ctx, types.TenantIDContextKey, ds.TenantID)
tenant, err := s.tenantRepo.GetTenantByID(ctx, ds.TenantID)
if err != nil {
logger.Errorf(ctx, "failed to get tenant info: %v", err)
s.updateSyncRunResult(ctx, ds, syncLog, &types.SyncResult{}, nil,
types.SyncLogStatusFailed, fmt.Sprintf("Failed to get tenant info: %v", err), wasPaused)
return err
}
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenant)
autoTagIDs := s.resolveAutoTagIDs(ctx, ds)
forceFull := payload.ForceFull || ds.SyncMode == types.SyncModeFull
attempt, _ := asynq.GetRetryCount(ctx)
startCursor, err := streamStartCursor(ds, forceFull, attempt)
if err != nil {
logger.Errorf(ctx, "failed to parse sync cursor: %v", err)
s.updateSyncRunResult(ctx, ds, syncLog, &types.SyncResult{}, nil,
types.SyncLogStatusFailed, fmt.Sprintf("Invalid cursor: %v", err), wasPaused)
return err
}
result := &types.SyncResult{}
handler := &streamSyncHandler{svc: s, ds: ds, tagIDs: autoTagIDs, result: result, syncLog: syncLog}
nextCursor, fetchErr := sc.FetchStream(ctx, config, startCursor, handler)
if fetchErr != nil {
// Progress so far is already checkpointed onto ds.LastSyncCursor; leave
// it in place so the Asynq retry resumes from there. Persist counts.
logger.Errorf(ctx, "streaming fetch failed: %v", fetchErr)
resultJSON, _ := result.ToJSON()
s.updateSyncRunResult(ctx, ds, syncLog, result, resultJSON,
types.SyncLogStatusFailed, fmt.Sprintf("Fetch failed: %v", fetchErr), wasPaused)
return fetchErr
}
resultJSON, _ := result.ToJSON()
if err := allFetchedItemsFailedError(result); err != nil {
logger.Errorf(ctx, "streaming sync failed while processing fetched items: %v", err)
s.updateSyncRunResult(ctx, ds, syncLog, result, resultJSON, types.SyncLogStatusFailed, err.Error(), wasPaused)
return err
}
// Persist the final cursor for the next incremental sync.
if nextCursor != nil {
if cursorJSON, cerr := nextCursor.ToJSON(); cerr == nil {
ds.LastSyncCursor = cursorJSON
}
}
ds.LastSyncAt = timePtr(time.Now().UTC())
// Surface per-document failures as a partial sync (not silent success), so
// the sync-log drawer's failure detail explains which docs didn't make it —
// the visibility gap behind "status normal but not everything syncs"
// (Tencent/WeKnora#2136). Failed nodes were not advanced in the cursor, so
// the next run retries them.
status := types.SyncLogStatusSuccess
errMsg := ""
if result.Failed > 0 {
status = types.SyncLogStatusPartial
errMsg = fmt.Sprintf("%d document(s) failed to sync", result.Failed)
}
s.updateSyncRunResult(ctx, ds, syncLog, result, resultJSON, status, errMsg, wasPaused)
logger.Infof(ctx, "streaming sync completed: ds=%s created=%d updated=%d deleted=%d skipped=%d failed=%d",
payload.DataSourceID, result.Created, result.Updated, result.Deleted, result.Skipped, result.Failed)
return nil
}
func (s *DataSourceService) updateSyncRunResult(
ctx context.Context,
ds *types.DataSource,
@@ -832,7 +1041,7 @@ func allFetchedItemsFailedError(result *types.SyncResult) error {
detail := ""
if len(result.Errors) > 0 {
detail = result.Errors[0]
detail = result.Errors[0].Display()
const maxDetailLen = 500
if len(detail) > maxDetailLen {
detail = detail[:maxDetailLen] + "..."
@@ -153,7 +153,7 @@ func TestAllFetchedItemsFailedError(t *testing.T) {
err := allFetchedItemsFailedError(&types.SyncResult{
Total: 2,
Failed: 2,
Errors: []string{"doc one: export failed"},
Errors: []types.SyncItemError{{Message: "doc one: export failed"}},
})
require.Error(t, err)
assert.Contains(t, err.Error(), "all fetched items failed during sync (2/2)")
@@ -181,7 +181,7 @@ func TestAllFetchedItemsFailedErrorTruncatesLongDetail(t *testing.T) {
err := allFetchedItemsFailedError(&types.SyncResult{
Total: 1,
Failed: 1,
Errors: []string{strings.Repeat("x", 600)},
Errors: []types.SyncItemError{{Message: strings.Repeat("x", 600)}},
})
require.Error(t, err)
assert.LessOrEqual(t, len(err.Error()), 560)
@@ -0,0 +1,117 @@
package service
import (
"context"
"encoding/json"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// recordingDSRepo captures UpdateSyncState calls so checkpoint persistence can
// be asserted without a database.
type recordingDSRepo struct {
kbDeleteDSRepo
updated []*types.DataSource
}
func (r *recordingDSRepo) UpdateSyncState(_ context.Context, ds *types.DataSource) error {
// Snapshot the fields a checkpoint is expected to persist.
cp := *ds
r.updated = append(r.updated, &cp)
return nil
}
func makeConnectorCursor(t *testing.T, spaceNodeTimes map[string]map[string]string) types.JSON {
t.Helper()
inner := map[string]interface{}{"space_node_times": spaceNodeTimes}
b, err := json.Marshal(&types.SyncCursor{ConnectorCursor: inner})
require.NoError(t, err)
return types.JSON(b)
}
// A fresh full sync (ForceFull, first attempt) must ignore any recorded cursor
// and re-fetch everything. A retry of that same task (attempt > 0) must instead
// resume from the checkpointed cursor so it converges instead of restarting.
func TestStreamStartCursor_ForceFullFirstAttemptDropsCursor(t *testing.T) {
ds := &types.DataSource{
LastSyncCursor: makeConnectorCursor(t, map[string]map[string]string{"space1": {"nt1": "100"}}),
}
fresh, err := streamStartCursor(ds, true /*forceFull*/, 0 /*attempt*/)
require.NoError(t, err)
assert.Nil(t, fresh, "fresh ForceFull must drop the cursor to re-fetch everything")
retry, err := streamStartCursor(ds, true /*forceFull*/, 1 /*attempt*/)
require.NoError(t, err)
require.NotNil(t, retry, "a retried ForceFull must resume from the checkpoint")
assert.NotNil(t, retry.ConnectorCursor["space_node_times"])
}
// Incremental sync always resumes from the recorded cursor regardless of attempt.
func TestStreamStartCursor_IncrementalKeepsCursor(t *testing.T) {
ds := &types.DataSource{
LastSyncCursor: makeConnectorCursor(t, map[string]map[string]string{"space1": {"nt1": "100"}}),
}
cur, err := streamStartCursor(ds, false /*forceFull*/, 0)
require.NoError(t, err)
require.NotNil(t, cur)
assert.NotNil(t, cur.ConnectorCursor["space_node_times"])
}
func newStreamHandler(svc *DataSourceService, ds *types.DataSource, result *types.SyncResult, syncLog *types.SyncLog) *streamSyncHandler {
return &streamSyncHandler{svc: svc, ds: ds, result: result, syncLog: syncLog}
}
// Emit routes items through the same classification as the batch loop: deleted
// items are counted, and connector-reported failures (an item carrying only a
// Metadata["error"]) land in result.Failed with a message — never silently lost.
func TestStreamHandler_EmitClassifiesDeletedAndFailed(t *testing.T) {
ds := &types.DataSource{ID: "ds-1", Type: types.ConnectorTypeFeishu, SyncDeletions: true}
result := &types.SyncResult{}
h := newStreamHandler(&DataSourceService{}, ds, result, &types.SyncLog{})
require.NoError(t, h.Emit(context.Background(), types.FetchedItem{ExternalID: "gone", IsDeleted: true}))
require.NoError(t, h.Emit(context.Background(), types.FetchedItem{
ExternalID: "bad", Title: "Broken Doc",
Metadata: map[string]string{"error": "export failed"},
}))
assert.Equal(t, 1, result.Deleted)
assert.Equal(t, 1, result.Failed)
require.Len(t, result.Errors, 1)
assert.Equal(t, "Broken Doc", result.Errors[0].Title)
assert.Contains(t, result.Errors[0].Message, "export failed")
}
// A canceled context aborts the stream: Emit returns the context error so the
// connector stops fetching instead of burning API budget on a doomed run.
func TestStreamHandler_EmitAbortsOnCanceledContext(t *testing.T) {
h := newStreamHandler(&DataSourceService{}, &types.DataSource{}, &types.SyncResult{}, &types.SyncLog{})
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := h.Emit(ctx, types.FetchedItem{ExternalID: "x", Content: []byte("data"), FileName: "x.md"})
require.Error(t, err)
assert.ErrorIs(t, err, context.Canceled)
}
// Checkpoint persists the connector cursor onto the data source so a crash
// after it keeps the progress made so far.
func TestStreamHandler_CheckpointPersistsCursor(t *testing.T) {
dsRepo := &recordingDSRepo{}
svc := &DataSourceService{dsRepo: dsRepo, syncLogRepo: &processSyncSyncLogRepo{logs: map[string]*types.SyncLog{}}}
ds := &types.DataSource{ID: "ds-1"}
result := &types.SyncResult{Created: 3}
syncLog := &types.SyncLog{ID: "log-1"}
h := newStreamHandler(svc, ds, result, syncLog)
cursor := &types.SyncCursor{ConnectorCursor: map[string]interface{}{
"space_node_times": map[string]map[string]string{"space1": {"nt1": "100"}},
}}
require.NoError(t, h.Checkpoint(context.Background(), cursor))
require.Len(t, dsRepo.updated, 1)
assert.NotEmpty(t, dsRepo.updated[0].LastSyncCursor, "checkpoint must persist the cursor JSON")
}