2026-03-27 07:02:40 +00:00
|
|
|
package service
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bytes"
|
|
|
|
|
"context"
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"errors"
|
|
|
|
|
"fmt"
|
|
|
|
|
"mime/multipart"
|
|
|
|
|
"net/textproto"
|
fix: redact sensitive fields and prevent credential loss on edit
Closes #988
Unify the "write-only secrets" pattern across MCP services, Models,
WebSearch providers, and DataSources. Fix two related defects:
1. GET responses leaked plaintext credentials — GetMCPServiceByID
while List masked, all Model / WebSearchProvider / DataSource GET
responses unconditionally.
2. When the frontend echoed a masked placeholder back on save, the
update path overwrote the stored secret with the mask — silently
wiping the real credential. MCP surfaced this most visibly:
ListMCPServices masked Token to "first4****last4" and
McpServiceDialog round-tripped that masked string back into the DB.
- internal/types/secret.go introduces the shared sentinel
RedactedSecretPlaceholder = "***" and two helpers:
- IsRedactedOrEmpty(s): true for "" or the sentinel
- PreserveIfRedacted(incoming, existing): merge predicate
- Each resource adds a RedactSensitiveData (mutates-in-place) or
Redacted (returns-a-copy) method and a MergeUpdate contract:
empty or placeholder preserves, any other value replaces, and a
write-only Clear* bool flag (gorm:"-", json omitempty) wipes with
precedence over preserve / replace. Clear* never persists.
- Every GET / List / Create / Update response path now redacts.
VectorStore's pre-existing "***" literal is refactored onto the
shared constant for consistency.
All four dialogs — McpServiceDialog, ModelEditorDialog,
WebSearchSettings, DataSourceEditorDialog — never pre-fill secret
inputs. The stored-state signal is collapsed into the input
placeholder: "•••••••• (Enter new value to replace)" when the server
reports a stored value, falling back to the connector-specific
placeholder otherwise. The input itself carries the "something is
there" cue, matching how password dots render.
An opt-in "Remove this credential" checkbox appears in edit mode when
a value is stored; checking it disables the input and triggers a
danger-themed confirmation dialog before submit. DataSource rolls the
clear up to a connector-level "Remove all credentials" flag since its
credentials are per-connector atomic bundles (e.g. Feishu app_id +
app_secret).
i18n updates across en-US, zh-CN, ko-KR, ru-RU:
secret.storedPlaceholder / clearHint / confirmClearTitle /
confirmClearBody.
- MCP update handler's manual map-to-struct projection was silently
dropping clear_api_key / clear_token / custom_headers on partial
updates. Pull them off the map explicitly.
- MCP configChanged detection now snapshots URL / StdioConfig /
TransportType before the merge so connection recycling still
triggers on real transport changes (not just whenever AuthConfig
is present).
- MCP CustomHeaders: nil preserves existing, non-nil replaces. Was
always overwriting, silently wiping headers on any auth-bearing
update.
- GetMCPServiceByID now redacts (was plaintext while List masked).
- WebSearchProvider update preserves Name / Description when empty
instead of clobbering them.
- WebSearchProvider TestProviderRaw rejects the "***" placeholder up
front with an actionable message rather than forwarding it to the
upstream provider API as a literal key.
- Model builtin hideSensitiveInfo now preserves non-secret metadata
(SupportsVision, Provider, ExtraConfig, InterfaceType,
ParameterSize, EmbeddingParameters) that were previously zeroed
out for builtin model cards.
- Replace local equalStringSlices / equalStringMaps helpers with
stdlib slices.Equal / maps.Equal (Go 1.21+).
- internal/types/{secret,mcp,model,web_search_provider,datasource}_test.go:
table-driven coverage of merge, redact, clear, and write-only flag
invariants for every resource.
- internal/application/service/mcp_service_test.go: full service layer
with a fake repo; covers ListMCPServices / GetMCPServiceByID
redaction, UpdateMCPService partial-update honoring of Clear*,
CustomHeaders preserve-on-nil / replace-on-non-nil, and
clear-flag precedence over submitted values.
Additive only. No changes to request or response JSON shape beyond
the write-only Clear* flags (omitted by default via omitempty). No DB
schema changes. No SDK struct field removals. Existing clients that
don't know about the new flags continue to function unchanged.
- DataSource.Config jsonb at-rest encryption. Pre-existing residual
risk; tracked as a follow-up.
- Renaming VectorStore.MaskSensitiveFields to match the new
RedactSensitiveData / Redacted naming convention. Left alone to
minimize diff; a follow-up rename PR can unify.
2026-04-18 12:48:50 +00:00
|
|
|
"reflect"
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
"slices"
|
2026-06-23 08:03:38 +00:00
|
|
|
"strings"
|
2026-03-27 07:02:40 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/datasource"
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/logger"
|
feat(observability): extend Langfuse tracing across asynq pipeline
Previously the Langfuse integration only traced in-process HTTP requests
(chat / search / eval), so file uploads and every downstream asynq task
(document parse, chunk embedding, OCR/VLM, summary / question gen, wiki
ingest, datasource sync, etc.) produced either disconnected shallow
traces or no observation at all.
This change threads one trace end-to-end:
- tracer: add SPAN observation type and StartSpan; add ResumeTrace so a
worker can attach to an upstream trace without emitting a duplicate
trace-create; StartGeneration now auto-picks parentObservationId from
ctx so nested trace -> span -> generation trees render correctly.
- types.TracingContext + LangfuseTracingCarrier: embed on all 17 asynq
payloads so trace_id / parent_obs_id / user_id / session_id serialise
into every job.
- langfuse.InjectTracing: injected at 28 enqueue sites before json.Marshal
so the HTTP-layer trace survives the Redis hop.
- langfuse.AsynqMiddleware: mux.Use hook that peeks the payload, either
resumes the upstream trace or opens a standalone asynq.<type> trace
for scheduled jobs, and wraps the handler in a SPAN with task metadata
(id / queue / retry / payload_bytes) plus ERROR level on failure.
- GinMiddleware.shouldTrace: whitelist ingestion / knowledge-mutation /
FAQ / wiki / datasource endpoints so the root trace actually starts.
- Tests: tracer_test.go covers span nesting, error status, and
ResumeTrace no-trace-create guarantee; asynq_test.go covers
InjectTracing round-trip, middleware resume path, and standalone
trace fallback.
- Docs: docs/Langfuse\u96c6\u6210.md now lists the covered task types
and documents the cross-process propagation model.
No behavioural change when Langfuse is disabled (all new code paths are
no-ops and carriers serialise to empty strings with omitempty).
2026-04-24 04:23:30 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
|
2026-03-27 07:02:40 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/types"
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
fix: redact sensitive fields and prevent credential loss on edit
Closes #988
Unify the "write-only secrets" pattern across MCP services, Models,
WebSearch providers, and DataSources. Fix two related defects:
1. GET responses leaked plaintext credentials — GetMCPServiceByID
while List masked, all Model / WebSearchProvider / DataSource GET
responses unconditionally.
2. When the frontend echoed a masked placeholder back on save, the
update path overwrote the stored secret with the mask — silently
wiping the real credential. MCP surfaced this most visibly:
ListMCPServices masked Token to "first4****last4" and
McpServiceDialog round-tripped that masked string back into the DB.
- internal/types/secret.go introduces the shared sentinel
RedactedSecretPlaceholder = "***" and two helpers:
- IsRedactedOrEmpty(s): true for "" or the sentinel
- PreserveIfRedacted(incoming, existing): merge predicate
- Each resource adds a RedactSensitiveData (mutates-in-place) or
Redacted (returns-a-copy) method and a MergeUpdate contract:
empty or placeholder preserves, any other value replaces, and a
write-only Clear* bool flag (gorm:"-", json omitempty) wipes with
precedence over preserve / replace. Clear* never persists.
- Every GET / List / Create / Update response path now redacts.
VectorStore's pre-existing "***" literal is refactored onto the
shared constant for consistency.
All four dialogs — McpServiceDialog, ModelEditorDialog,
WebSearchSettings, DataSourceEditorDialog — never pre-fill secret
inputs. The stored-state signal is collapsed into the input
placeholder: "•••••••• (Enter new value to replace)" when the server
reports a stored value, falling back to the connector-specific
placeholder otherwise. The input itself carries the "something is
there" cue, matching how password dots render.
An opt-in "Remove this credential" checkbox appears in edit mode when
a value is stored; checking it disables the input and triggers a
danger-themed confirmation dialog before submit. DataSource rolls the
clear up to a connector-level "Remove all credentials" flag since its
credentials are per-connector atomic bundles (e.g. Feishu app_id +
app_secret).
i18n updates across en-US, zh-CN, ko-KR, ru-RU:
secret.storedPlaceholder / clearHint / confirmClearTitle /
confirmClearBody.
- MCP update handler's manual map-to-struct projection was silently
dropping clear_api_key / clear_token / custom_headers on partial
updates. Pull them off the map explicitly.
- MCP configChanged detection now snapshots URL / StdioConfig /
TransportType before the merge so connection recycling still
triggers on real transport changes (not just whenever AuthConfig
is present).
- MCP CustomHeaders: nil preserves existing, non-nil replaces. Was
always overwriting, silently wiping headers on any auth-bearing
update.
- GetMCPServiceByID now redacts (was plaintext while List masked).
- WebSearchProvider update preserves Name / Description when empty
instead of clobbering them.
- WebSearchProvider TestProviderRaw rejects the "***" placeholder up
front with an actionable message rather than forwarding it to the
upstream provider API as a literal key.
- Model builtin hideSensitiveInfo now preserves non-secret metadata
(SupportsVision, Provider, ExtraConfig, InterfaceType,
ParameterSize, EmbeddingParameters) that were previously zeroed
out for builtin model cards.
- Replace local equalStringSlices / equalStringMaps helpers with
stdlib slices.Equal / maps.Equal (Go 1.21+).
- internal/types/{secret,mcp,model,web_search_provider,datasource}_test.go:
table-driven coverage of merge, redact, clear, and write-only flag
invariants for every resource.
- internal/application/service/mcp_service_test.go: full service layer
with a fake repo; covers ListMCPServices / GetMCPServiceByID
redaction, UpdateMCPService partial-update honoring of Clear*,
CustomHeaders preserve-on-nil / replace-on-non-nil, and
clear-flag precedence over submitted values.
Additive only. No changes to request or response JSON shape beyond
the write-only Clear* flags (omitted by default via omitempty). No DB
schema changes. No SDK struct field removals. Existing clients that
don't know about the new flags continue to function unchanged.
- DataSource.Config jsonb at-rest encryption. Pre-existing residual
risk; tracked as a follow-up.
- Renaming VectorStore.MaskSensitiveFields to match the new
RedactSensitiveData / Redacted naming convention. Left alone to
minimize diff; a follow-up rename PR can unify.
2026-04-18 12:48:50 +00:00
|
|
|
secutils "github.com/Tencent/WeKnora/internal/utils"
|
2026-03-27 07:02:40 +00:00
|
|
|
"github.com/hibiken/asynq"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// DataSourceService implements the DataSourceService interface
|
|
|
|
|
type DataSourceService struct {
|
|
|
|
|
dsRepo interfaces.DataSourceRepository
|
|
|
|
|
syncLogRepo interfaces.SyncLogRepository
|
|
|
|
|
knowledgeService interfaces.KnowledgeService
|
|
|
|
|
kbService interfaces.KnowledgeBaseService
|
|
|
|
|
taskEnqueuer interfaces.TaskEnqueuer
|
|
|
|
|
connectorRegistry *datasource.ConnectorRegistry
|
|
|
|
|
scheduler *datasource.Scheduler
|
|
|
|
|
tenantRepo interfaces.TenantRepository
|
|
|
|
|
tagService interfaces.KnowledgeTagService
|
2026-07-22 11:15:27 +00:00
|
|
|
audit interfaces.AuditLogService
|
2026-03-27 07:02:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// NewDataSourceService creates a new data source service
|
|
|
|
|
func NewDataSourceService(
|
|
|
|
|
dsRepo interfaces.DataSourceRepository,
|
|
|
|
|
syncLogRepo interfaces.SyncLogRepository,
|
|
|
|
|
knowledgeService interfaces.KnowledgeService,
|
|
|
|
|
kbService interfaces.KnowledgeBaseService,
|
|
|
|
|
taskEnqueuer interfaces.TaskEnqueuer,
|
|
|
|
|
connectorRegistry *datasource.ConnectorRegistry,
|
|
|
|
|
scheduler *datasource.Scheduler,
|
|
|
|
|
tenantRepo interfaces.TenantRepository,
|
|
|
|
|
tagService interfaces.KnowledgeTagService,
|
2026-07-22 11:15:27 +00:00
|
|
|
audit interfaces.AuditLogService,
|
2026-03-27 07:02:40 +00:00
|
|
|
) interfaces.DataSourceService {
|
|
|
|
|
return &DataSourceService{
|
|
|
|
|
dsRepo: dsRepo,
|
|
|
|
|
syncLogRepo: syncLogRepo,
|
|
|
|
|
knowledgeService: knowledgeService,
|
|
|
|
|
kbService: kbService,
|
|
|
|
|
taskEnqueuer: taskEnqueuer,
|
|
|
|
|
connectorRegistry: connectorRegistry,
|
|
|
|
|
scheduler: scheduler,
|
|
|
|
|
tenantRepo: tenantRepo,
|
|
|
|
|
tagService: tagService,
|
2026-07-22 11:15:27 +00:00
|
|
|
audit: audit,
|
2026-03-27 07:02:40 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// CreateDataSource creates a new data source configuration
|
|
|
|
|
func (s *DataSourceService) CreateDataSource(ctx context.Context, ds *types.DataSource) (*types.DataSource, error) {
|
|
|
|
|
if ds == nil {
|
|
|
|
|
return nil, datasource.ErrDataSourceInvalid
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Validate knowledge base exists
|
|
|
|
|
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, ds.KnowledgeBaseID)
|
|
|
|
|
if err != nil || kb == nil {
|
|
|
|
|
return nil, datasource.ErrKnowledgeBaseNotFound
|
|
|
|
|
}
|
2026-03-30 11:51:28 +00:00
|
|
|
if kb.TenantID != ds.TenantID {
|
|
|
|
|
return nil, datasource.ErrKnowledgeBaseNotFound
|
|
|
|
|
}
|
2026-03-27 07:02:40 +00:00
|
|
|
|
|
|
|
|
// Validate connector type
|
|
|
|
|
_, err = s.connectorRegistry.Get(ds.Type)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Validate configuration
|
2026-06-23 07:45:47 +00:00
|
|
|
if cfg, err := ds.ParseConfig(); err == nil && cfg != nil {
|
|
|
|
|
cfg.StripNonSecretCredentials(ds.Type)
|
|
|
|
|
if blob, err := cfg.ToJSON(); err == nil {
|
|
|
|
|
ds.Config = blob
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-03-27 07:02:40 +00:00
|
|
|
if err := s.validateDataSourceConfig(ctx, ds); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Create in database
|
|
|
|
|
if err := s.dsRepo.Create(ctx, ds); err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to create data source: %v", err)
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Register cron schedule if configured
|
|
|
|
|
if ds.SyncSchedule != "" && ds.Status == types.DataSourceStatusActive {
|
|
|
|
|
if err := s.scheduler.AddOrUpdate(ds); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "failed to register cron for ds=%s: %v", ds.ID, err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "data source created: id=%s type=%s kb=%s", ds.ID, ds.Type, ds.KnowledgeBaseID)
|
2026-07-22 11:15:27 +00:00
|
|
|
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, types.AuditActionDataSourceCreated,
|
|
|
|
|
"data_source", ds.ID, types.AuditOutcomeSuccess,
|
|
|
|
|
map[string]any{"name": ds.Name, "type": ds.Type})
|
2026-03-27 07:02:40 +00:00
|
|
|
return ds, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// GetDataSource retrieves a data source by ID
|
|
|
|
|
func (s *DataSourceService) GetDataSource(ctx context.Context, id string) (*types.DataSource, error) {
|
|
|
|
|
ds, err := s.dsRepo.FindByID(ctx, id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return ds, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ListDataSources lists all data sources for a knowledge base
|
|
|
|
|
func (s *DataSourceService) ListDataSources(ctx context.Context, kbID string) ([]*types.DataSource, error) {
|
|
|
|
|
dataSources, err := s.dsRepo.FindByKnowledgeBase(ctx, kbID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to list data sources: %v", err)
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Attach latest sync log to each data source
|
|
|
|
|
for _, ds := range dataSources {
|
|
|
|
|
log, _ := s.syncLogRepo.FindLatest(ctx, ds.ID)
|
|
|
|
|
if log != nil {
|
|
|
|
|
ds.LatestSyncLog = log
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return dataSources, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// UpdateDataSource updates an existing data source
|
|
|
|
|
func (s *DataSourceService) UpdateDataSource(ctx context.Context, ds *types.DataSource) (*types.DataSource, error) {
|
|
|
|
|
if ds == nil || ds.ID == "" {
|
|
|
|
|
return nil, datasource.ErrDataSourceInvalid
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Verify data source exists
|
|
|
|
|
existing, err := s.dsRepo.FindByID(ctx, ds.ID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-30 11:51:28 +00:00
|
|
|
if ds.KnowledgeBaseID == "" {
|
|
|
|
|
ds.KnowledgeBaseID = existing.KnowledgeBaseID
|
|
|
|
|
}
|
|
|
|
|
if ds.KnowledgeBaseID != existing.KnowledgeBaseID {
|
|
|
|
|
return nil, fmt.Errorf("changing knowledge base is not allowed")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ds.TenantID == 0 {
|
|
|
|
|
ds.TenantID = existing.TenantID
|
|
|
|
|
}
|
|
|
|
|
if ds.TenantID != existing.TenantID {
|
|
|
|
|
return nil, datasource.ErrDataSourceInvalid
|
|
|
|
|
}
|
|
|
|
|
|
refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.
Why
---
The previous design had three problems:
1. Main PUT body carried secret fields. The frontend echoed back a
redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
defense in the service layer tried to detect "user did not change this"
vs "user wants to clear this". A regression in that defense (or a new
frontend forgetting it) silently overwrites the stored secret with the
placeholder.
2. The "remove this credential" UX was a red checkbox under a pre-filled
password input. Three intents (preserve / replace / clear) collapsed
onto one field, and credential changes were bundled with unrelated
config edits in the same submit. Users wiped working keys by mistake.
3. Secret presence was inferred from "did the response come back with a
'***' placeholder", which couples the contract to a magic string.
Design
------
Each of the four resources now exposes:
PUT /{resource}/{id}/credentials # write one or more fields
DELETE /{resource}/{id}/credentials/{field} # clear a single field
"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.
Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.
Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
(unconfigured / configured / editing) and drives the dedicated
endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
card with the same behaviour because its credentials are a single
atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
prop. The previous async refresh() was a no-op while state was still
'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
deterrent; a modal confirm adds friction without adding safety (the
plaintext is irrecoverable client-side either way — recovery means
re-typing).
DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.
Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.
Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
/ ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
RedactedSecretPlaceholder constant is retained because VectorStore
still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
redaction handling removed; i18n keys renamed secret -> credential.
2026-05-17 07:09:30 +00:00
|
|
|
// Credentials NEVER flow through this endpoint — they live behind the
|
|
|
|
|
// /credentials subresource. Force-preserve the stored credentials map
|
|
|
|
|
// regardless of what the body says. Log a warning if a stale caller
|
|
|
|
|
// passes one so we can spot them and migrate later. Non-credential
|
|
|
|
|
// fields of Config (Type / ResourceIDs / Settings) flow through.
|
fix: redact sensitive fields and prevent credential loss on edit
Closes #988
Unify the "write-only secrets" pattern across MCP services, Models,
WebSearch providers, and DataSources. Fix two related defects:
1. GET responses leaked plaintext credentials — GetMCPServiceByID
while List masked, all Model / WebSearchProvider / DataSource GET
responses unconditionally.
2. When the frontend echoed a masked placeholder back on save, the
update path overwrote the stored secret with the mask — silently
wiping the real credential. MCP surfaced this most visibly:
ListMCPServices masked Token to "first4****last4" and
McpServiceDialog round-tripped that masked string back into the DB.
- internal/types/secret.go introduces the shared sentinel
RedactedSecretPlaceholder = "***" and two helpers:
- IsRedactedOrEmpty(s): true for "" or the sentinel
- PreserveIfRedacted(incoming, existing): merge predicate
- Each resource adds a RedactSensitiveData (mutates-in-place) or
Redacted (returns-a-copy) method and a MergeUpdate contract:
empty or placeholder preserves, any other value replaces, and a
write-only Clear* bool flag (gorm:"-", json omitempty) wipes with
precedence over preserve / replace. Clear* never persists.
- Every GET / List / Create / Update response path now redacts.
VectorStore's pre-existing "***" literal is refactored onto the
shared constant for consistency.
All four dialogs — McpServiceDialog, ModelEditorDialog,
WebSearchSettings, DataSourceEditorDialog — never pre-fill secret
inputs. The stored-state signal is collapsed into the input
placeholder: "•••••••• (Enter new value to replace)" when the server
reports a stored value, falling back to the connector-specific
placeholder otherwise. The input itself carries the "something is
there" cue, matching how password dots render.
An opt-in "Remove this credential" checkbox appears in edit mode when
a value is stored; checking it disables the input and triggers a
danger-themed confirmation dialog before submit. DataSource rolls the
clear up to a connector-level "Remove all credentials" flag since its
credentials are per-connector atomic bundles (e.g. Feishu app_id +
app_secret).
i18n updates across en-US, zh-CN, ko-KR, ru-RU:
secret.storedPlaceholder / clearHint / confirmClearTitle /
confirmClearBody.
- MCP update handler's manual map-to-struct projection was silently
dropping clear_api_key / clear_token / custom_headers on partial
updates. Pull them off the map explicitly.
- MCP configChanged detection now snapshots URL / StdioConfig /
TransportType before the merge so connection recycling still
triggers on real transport changes (not just whenever AuthConfig
is present).
- MCP CustomHeaders: nil preserves existing, non-nil replaces. Was
always overwriting, silently wiping headers on any auth-bearing
update.
- GetMCPServiceByID now redacts (was plaintext while List masked).
- WebSearchProvider update preserves Name / Description when empty
instead of clobbering them.
- WebSearchProvider TestProviderRaw rejects the "***" placeholder up
front with an actionable message rather than forwarding it to the
upstream provider API as a literal key.
- Model builtin hideSensitiveInfo now preserves non-secret metadata
(SupportsVision, Provider, ExtraConfig, InterfaceType,
ParameterSize, EmbeddingParameters) that were previously zeroed
out for builtin model cards.
- Replace local equalStringSlices / equalStringMaps helpers with
stdlib slices.Equal / maps.Equal (Go 1.21+).
- internal/types/{secret,mcp,model,web_search_provider,datasource}_test.go:
table-driven coverage of merge, redact, clear, and write-only flag
invariants for every resource.
- internal/application/service/mcp_service_test.go: full service layer
with a fake repo; covers ListMCPServices / GetMCPServiceByID
redaction, UpdateMCPService partial-update honoring of Clear*,
CustomHeaders preserve-on-nil / replace-on-non-nil, and
clear-flag precedence over submitted values.
Additive only. No changes to request or response JSON shape beyond
the write-only Clear* flags (omitted by default via omitempty). No DB
schema changes. No SDK struct field removals. Existing clients that
don't know about the new flags continue to function unchanged.
- DataSource.Config jsonb at-rest encryption. Pre-existing residual
risk; tracked as a follow-up.
- Renaming VectorStore.MaskSensitiveFields to match the new
RedactSensitiveData / Redacted naming convention. Left alone to
minimize diff; a follow-up rename PR can unify.
2026-04-18 12:48:50 +00:00
|
|
|
var mergedCfg, existingParsedCfg *types.DataSourceConfig
|
|
|
|
|
if len(ds.Config) > 0 {
|
|
|
|
|
incomingCfg, parseIncErr := ds.ParseConfig()
|
|
|
|
|
existingCfg, parseExErr := existing.ParseConfig()
|
|
|
|
|
if parseIncErr == nil && parseExErr == nil && incomingCfg != nil {
|
refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.
Why
---
The previous design had three problems:
1. Main PUT body carried secret fields. The frontend echoed back a
redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
defense in the service layer tried to detect "user did not change this"
vs "user wants to clear this". A regression in that defense (or a new
frontend forgetting it) silently overwrites the stored secret with the
placeholder.
2. The "remove this credential" UX was a red checkbox under a pre-filled
password input. Three intents (preserve / replace / clear) collapsed
onto one field, and credential changes were bundled with unrelated
config edits in the same submit. Users wiped working keys by mistake.
3. Secret presence was inferred from "did the response come back with a
'***' placeholder", which couples the contract to a magic string.
Design
------
Each of the four resources now exposes:
PUT /{resource}/{id}/credentials # write one or more fields
DELETE /{resource}/{id}/credentials/{field} # clear a single field
"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.
Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.
Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
(unconfigured / configured / editing) and drives the dedicated
endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
card with the same behaviour because its credentials are a single
atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
prop. The previous async refresh() was a no-op while state was still
'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
deterrent; a modal confirm adds friction without adding safety (the
plaintext is irrecoverable client-side either way — recovery means
re-typing).
DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.
Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.
Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
/ ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
RedactedSecretPlaceholder constant is retained because VectorStore
still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
redaction handling removed; i18n keys renamed secret -> credential.
2026-05-17 07:09:30 +00:00
|
|
|
if incomingCfg.HasCredentials() {
|
|
|
|
|
logger.Warnf(ctx,
|
|
|
|
|
"deprecated: credentials in PUT /datasource/%s body are ignored; use PUT /credentials instead",
|
fix: redact sensitive fields and prevent credential loss on edit
Closes #988
Unify the "write-only secrets" pattern across MCP services, Models,
WebSearch providers, and DataSources. Fix two related defects:
1. GET responses leaked plaintext credentials — GetMCPServiceByID
while List masked, all Model / WebSearchProvider / DataSource GET
responses unconditionally.
2. When the frontend echoed a masked placeholder back on save, the
update path overwrote the stored secret with the mask — silently
wiping the real credential. MCP surfaced this most visibly:
ListMCPServices masked Token to "first4****last4" and
McpServiceDialog round-tripped that masked string back into the DB.
- internal/types/secret.go introduces the shared sentinel
RedactedSecretPlaceholder = "***" and two helpers:
- IsRedactedOrEmpty(s): true for "" or the sentinel
- PreserveIfRedacted(incoming, existing): merge predicate
- Each resource adds a RedactSensitiveData (mutates-in-place) or
Redacted (returns-a-copy) method and a MergeUpdate contract:
empty or placeholder preserves, any other value replaces, and a
write-only Clear* bool flag (gorm:"-", json omitempty) wipes with
precedence over preserve / replace. Clear* never persists.
- Every GET / List / Create / Update response path now redacts.
VectorStore's pre-existing "***" literal is refactored onto the
shared constant for consistency.
All four dialogs — McpServiceDialog, ModelEditorDialog,
WebSearchSettings, DataSourceEditorDialog — never pre-fill secret
inputs. The stored-state signal is collapsed into the input
placeholder: "•••••••• (Enter new value to replace)" when the server
reports a stored value, falling back to the connector-specific
placeholder otherwise. The input itself carries the "something is
there" cue, matching how password dots render.
An opt-in "Remove this credential" checkbox appears in edit mode when
a value is stored; checking it disables the input and triggers a
danger-themed confirmation dialog before submit. DataSource rolls the
clear up to a connector-level "Remove all credentials" flag since its
credentials are per-connector atomic bundles (e.g. Feishu app_id +
app_secret).
i18n updates across en-US, zh-CN, ko-KR, ru-RU:
secret.storedPlaceholder / clearHint / confirmClearTitle /
confirmClearBody.
- MCP update handler's manual map-to-struct projection was silently
dropping clear_api_key / clear_token / custom_headers on partial
updates. Pull them off the map explicitly.
- MCP configChanged detection now snapshots URL / StdioConfig /
TransportType before the merge so connection recycling still
triggers on real transport changes (not just whenever AuthConfig
is present).
- MCP CustomHeaders: nil preserves existing, non-nil replaces. Was
always overwriting, silently wiping headers on any auth-bearing
update.
- GetMCPServiceByID now redacts (was plaintext while List masked).
- WebSearchProvider update preserves Name / Description when empty
instead of clobbering them.
- WebSearchProvider TestProviderRaw rejects the "***" placeholder up
front with an actionable message rather than forwarding it to the
upstream provider API as a literal key.
- Model builtin hideSensitiveInfo now preserves non-secret metadata
(SupportsVision, Provider, ExtraConfig, InterfaceType,
ParameterSize, EmbeddingParameters) that were previously zeroed
out for builtin model cards.
- Replace local equalStringSlices / equalStringMaps helpers with
stdlib slices.Equal / maps.Equal (Go 1.21+).
- internal/types/{secret,mcp,model,web_search_provider,datasource}_test.go:
table-driven coverage of merge, redact, clear, and write-only flag
invariants for every resource.
- internal/application/service/mcp_service_test.go: full service layer
with a fake repo; covers ListMCPServices / GetMCPServiceByID
redaction, UpdateMCPService partial-update honoring of Clear*,
CustomHeaders preserve-on-nil / replace-on-non-nil, and
clear-flag precedence over submitted values.
Additive only. No changes to request or response JSON shape beyond
the write-only Clear* flags (omitted by default via omitempty). No DB
schema changes. No SDK struct field removals. Existing clients that
don't know about the new flags continue to function unchanged.
- DataSource.Config jsonb at-rest encryption. Pre-existing residual
risk; tracked as a follow-up.
- Renaming VectorStore.MaskSensitiveFields to match the new
RedactSensitiveData / Redacted naming convention. Left alone to
minimize diff; a follow-up rename PR can unify.
2026-04-18 12:48:50 +00:00
|
|
|
secutils.SanitizeForLog(ds.ID))
|
|
|
|
|
}
|
refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.
Why
---
The previous design had three problems:
1. Main PUT body carried secret fields. The frontend echoed back a
redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
defense in the service layer tried to detect "user did not change this"
vs "user wants to clear this". A regression in that defense (or a new
frontend forgetting it) silently overwrites the stored secret with the
placeholder.
2. The "remove this credential" UX was a red checkbox under a pre-filled
password input. Three intents (preserve / replace / clear) collapsed
onto one field, and credential changes were bundled with unrelated
config edits in the same submit. Users wiped working keys by mistake.
3. Secret presence was inferred from "did the response come back with a
'***' placeholder", which couples the contract to a magic string.
Design
------
Each of the four resources now exposes:
PUT /{resource}/{id}/credentials # write one or more fields
DELETE /{resource}/{id}/credentials/{field} # clear a single field
"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.
Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.
Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
(unconfigured / configured / editing) and drives the dedicated
endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
card with the same behaviour because its credentials are a single
atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
prop. The previous async refresh() was a no-op while state was still
'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
deterrent; a modal confirm adds friction without adding safety (the
plaintext is irrecoverable client-side either way — recovery means
re-typing).
DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.
Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.
Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
/ ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
RedactedSecretPlaceholder constant is retained because VectorStore
still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
redaction handling removed; i18n keys renamed secret -> credential.
2026-05-17 07:09:30 +00:00
|
|
|
merged := *incomingCfg
|
|
|
|
|
if existingCfg != nil {
|
|
|
|
|
merged.Credentials = existingCfg.Credentials
|
|
|
|
|
} else {
|
|
|
|
|
merged.Credentials = nil
|
|
|
|
|
}
|
2026-06-23 07:45:47 +00:00
|
|
|
merged.StripNonSecretCredentials(ds.Type)
|
fix: redact sensitive fields and prevent credential loss on edit
Closes #988
Unify the "write-only secrets" pattern across MCP services, Models,
WebSearch providers, and DataSources. Fix two related defects:
1. GET responses leaked plaintext credentials — GetMCPServiceByID
while List masked, all Model / WebSearchProvider / DataSource GET
responses unconditionally.
2. When the frontend echoed a masked placeholder back on save, the
update path overwrote the stored secret with the mask — silently
wiping the real credential. MCP surfaced this most visibly:
ListMCPServices masked Token to "first4****last4" and
McpServiceDialog round-tripped that masked string back into the DB.
- internal/types/secret.go introduces the shared sentinel
RedactedSecretPlaceholder = "***" and two helpers:
- IsRedactedOrEmpty(s): true for "" or the sentinel
- PreserveIfRedacted(incoming, existing): merge predicate
- Each resource adds a RedactSensitiveData (mutates-in-place) or
Redacted (returns-a-copy) method and a MergeUpdate contract:
empty or placeholder preserves, any other value replaces, and a
write-only Clear* bool flag (gorm:"-", json omitempty) wipes with
precedence over preserve / replace. Clear* never persists.
- Every GET / List / Create / Update response path now redacts.
VectorStore's pre-existing "***" literal is refactored onto the
shared constant for consistency.
All four dialogs — McpServiceDialog, ModelEditorDialog,
WebSearchSettings, DataSourceEditorDialog — never pre-fill secret
inputs. The stored-state signal is collapsed into the input
placeholder: "•••••••• (Enter new value to replace)" when the server
reports a stored value, falling back to the connector-specific
placeholder otherwise. The input itself carries the "something is
there" cue, matching how password dots render.
An opt-in "Remove this credential" checkbox appears in edit mode when
a value is stored; checking it disables the input and triggers a
danger-themed confirmation dialog before submit. DataSource rolls the
clear up to a connector-level "Remove all credentials" flag since its
credentials are per-connector atomic bundles (e.g. Feishu app_id +
app_secret).
i18n updates across en-US, zh-CN, ko-KR, ru-RU:
secret.storedPlaceholder / clearHint / confirmClearTitle /
confirmClearBody.
- MCP update handler's manual map-to-struct projection was silently
dropping clear_api_key / clear_token / custom_headers on partial
updates. Pull them off the map explicitly.
- MCP configChanged detection now snapshots URL / StdioConfig /
TransportType before the merge so connection recycling still
triggers on real transport changes (not just whenever AuthConfig
is present).
- MCP CustomHeaders: nil preserves existing, non-nil replaces. Was
always overwriting, silently wiping headers on any auth-bearing
update.
- GetMCPServiceByID now redacts (was plaintext while List masked).
- WebSearchProvider update preserves Name / Description when empty
instead of clobbering them.
- WebSearchProvider TestProviderRaw rejects the "***" placeholder up
front with an actionable message rather than forwarding it to the
upstream provider API as a literal key.
- Model builtin hideSensitiveInfo now preserves non-secret metadata
(SupportsVision, Provider, ExtraConfig, InterfaceType,
ParameterSize, EmbeddingParameters) that were previously zeroed
out for builtin model cards.
- Replace local equalStringSlices / equalStringMaps helpers with
stdlib slices.Equal / maps.Equal (Go 1.21+).
- internal/types/{secret,mcp,model,web_search_provider,datasource}_test.go:
table-driven coverage of merge, redact, clear, and write-only flag
invariants for every resource.
- internal/application/service/mcp_service_test.go: full service layer
with a fake repo; covers ListMCPServices / GetMCPServiceByID
redaction, UpdateMCPService partial-update honoring of Clear*,
CustomHeaders preserve-on-nil / replace-on-non-nil, and
clear-flag precedence over submitted values.
Additive only. No changes to request or response JSON shape beyond
the write-only Clear* flags (omitted by default via omitempty). No DB
schema changes. No SDK struct field removals. Existing clients that
don't know about the new flags continue to function unchanged.
- DataSource.Config jsonb at-rest encryption. Pre-existing residual
risk; tracked as a follow-up.
- Renaming VectorStore.MaskSensitiveFields to match the new
RedactSensitiveData / Redacted naming convention. Left alone to
minimize diff; a follow-up rename PR can unify.
2026-04-18 12:48:50 +00:00
|
|
|
if blob, err := merged.ToJSON(); err == nil {
|
|
|
|
|
ds.Config = blob
|
|
|
|
|
}
|
|
|
|
|
mergedCfg = &merged
|
|
|
|
|
existingParsedCfg = existingCfg
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.
Why
---
The previous design had three problems:
1. Main PUT body carried secret fields. The frontend echoed back a
redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
defense in the service layer tried to detect "user did not change this"
vs "user wants to clear this". A regression in that defense (or a new
frontend forgetting it) silently overwrites the stored secret with the
placeholder.
2. The "remove this credential" UX was a red checkbox under a pre-filled
password input. Three intents (preserve / replace / clear) collapsed
onto one field, and credential changes were bundled with unrelated
config edits in the same submit. Users wiped working keys by mistake.
3. Secret presence was inferred from "did the response come back with a
'***' placeholder", which couples the contract to a magic string.
Design
------
Each of the four resources now exposes:
PUT /{resource}/{id}/credentials # write one or more fields
DELETE /{resource}/{id}/credentials/{field} # clear a single field
"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.
Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.
Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
(unconfigured / configured / editing) and drives the dedicated
endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
card with the same behaviour because its credentials are a single
atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
prop. The previous async refresh() was a no-op while state was still
'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
deterrent; a modal confirm adds friction without adding safety (the
plaintext is irrecoverable client-side either way — recovery means
re-typing).
DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.
Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.
Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
/ ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
RedactedSecretPlaceholder constant is retained because VectorStore
still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
redaction handling removed; i18n keys renamed secret -> credential.
2026-05-17 07:09:30 +00:00
|
|
|
// Validate new configuration if non-credential fields changed. Skip
|
|
|
|
|
// when there are no stored credentials yet (validators would fail with
|
|
|
|
|
// no token to call the live API) and when the parsed config is
|
|
|
|
|
// structurally identical.
|
fix: redact sensitive fields and prevent credential loss on edit
Closes #988
Unify the "write-only secrets" pattern across MCP services, Models,
WebSearch providers, and DataSources. Fix two related defects:
1. GET responses leaked plaintext credentials — GetMCPServiceByID
while List masked, all Model / WebSearchProvider / DataSource GET
responses unconditionally.
2. When the frontend echoed a masked placeholder back on save, the
update path overwrote the stored secret with the mask — silently
wiping the real credential. MCP surfaced this most visibly:
ListMCPServices masked Token to "first4****last4" and
McpServiceDialog round-tripped that masked string back into the DB.
- internal/types/secret.go introduces the shared sentinel
RedactedSecretPlaceholder = "***" and two helpers:
- IsRedactedOrEmpty(s): true for "" or the sentinel
- PreserveIfRedacted(incoming, existing): merge predicate
- Each resource adds a RedactSensitiveData (mutates-in-place) or
Redacted (returns-a-copy) method and a MergeUpdate contract:
empty or placeholder preserves, any other value replaces, and a
write-only Clear* bool flag (gorm:"-", json omitempty) wipes with
precedence over preserve / replace. Clear* never persists.
- Every GET / List / Create / Update response path now redacts.
VectorStore's pre-existing "***" literal is refactored onto the
shared constant for consistency.
All four dialogs — McpServiceDialog, ModelEditorDialog,
WebSearchSettings, DataSourceEditorDialog — never pre-fill secret
inputs. The stored-state signal is collapsed into the input
placeholder: "•••••••• (Enter new value to replace)" when the server
reports a stored value, falling back to the connector-specific
placeholder otherwise. The input itself carries the "something is
there" cue, matching how password dots render.
An opt-in "Remove this credential" checkbox appears in edit mode when
a value is stored; checking it disables the input and triggers a
danger-themed confirmation dialog before submit. DataSource rolls the
clear up to a connector-level "Remove all credentials" flag since its
credentials are per-connector atomic bundles (e.g. Feishu app_id +
app_secret).
i18n updates across en-US, zh-CN, ko-KR, ru-RU:
secret.storedPlaceholder / clearHint / confirmClearTitle /
confirmClearBody.
- MCP update handler's manual map-to-struct projection was silently
dropping clear_api_key / clear_token / custom_headers on partial
updates. Pull them off the map explicitly.
- MCP configChanged detection now snapshots URL / StdioConfig /
TransportType before the merge so connection recycling still
triggers on real transport changes (not just whenever AuthConfig
is present).
- MCP CustomHeaders: nil preserves existing, non-nil replaces. Was
always overwriting, silently wiping headers on any auth-bearing
update.
- GetMCPServiceByID now redacts (was plaintext while List masked).
- WebSearchProvider update preserves Name / Description when empty
instead of clobbering them.
- WebSearchProvider TestProviderRaw rejects the "***" placeholder up
front with an actionable message rather than forwarding it to the
upstream provider API as a literal key.
- Model builtin hideSensitiveInfo now preserves non-secret metadata
(SupportsVision, Provider, ExtraConfig, InterfaceType,
ParameterSize, EmbeddingParameters) that were previously zeroed
out for builtin model cards.
- Replace local equalStringSlices / equalStringMaps helpers with
stdlib slices.Equal / maps.Equal (Go 1.21+).
- internal/types/{secret,mcp,model,web_search_provider,datasource}_test.go:
table-driven coverage of merge, redact, clear, and write-only flag
invariants for every resource.
- internal/application/service/mcp_service_test.go: full service layer
with a fake repo; covers ListMCPServices / GetMCPServiceByID
redaction, UpdateMCPService partial-update honoring of Clear*,
CustomHeaders preserve-on-nil / replace-on-non-nil, and
clear-flag precedence over submitted values.
Additive only. No changes to request or response JSON shape beyond
the write-only Clear* flags (omitted by default via omitempty). No DB
schema changes. No SDK struct field removals. Existing clients that
don't know about the new flags continue to function unchanged.
- DataSource.Config jsonb at-rest encryption. Pre-existing residual
risk; tracked as a follow-up.
- Renaming VectorStore.MaskSensitiveFields to match the new
RedactSensitiveData / Redacted naming convention. Left alone to
minimize diff; a follow-up rename PR can unify.
2026-04-18 12:48:50 +00:00
|
|
|
configActuallyChanged := true
|
|
|
|
|
if mergedCfg != nil && existingParsedCfg != nil {
|
|
|
|
|
configActuallyChanged = !reflect.DeepEqual(*mergedCfg, *existingParsedCfg)
|
|
|
|
|
}
|
2026-06-23 07:45:47 +00:00
|
|
|
hasCreds := mergedCfg != nil && mergedCfg.HasConfiguredCredentials(ds.Type)
|
refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.
Why
---
The previous design had three problems:
1. Main PUT body carried secret fields. The frontend echoed back a
redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
defense in the service layer tried to detect "user did not change this"
vs "user wants to clear this". A regression in that defense (or a new
frontend forgetting it) silently overwrites the stored secret with the
placeholder.
2. The "remove this credential" UX was a red checkbox under a pre-filled
password input. Three intents (preserve / replace / clear) collapsed
onto one field, and credential changes were bundled with unrelated
config edits in the same submit. Users wiped working keys by mistake.
3. Secret presence was inferred from "did the response come back with a
'***' placeholder", which couples the contract to a magic string.
Design
------
Each of the four resources now exposes:
PUT /{resource}/{id}/credentials # write one or more fields
DELETE /{resource}/{id}/credentials/{field} # clear a single field
"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.
Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.
Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
(unconfigured / configured / editing) and drives the dedicated
endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
card with the same behaviour because its credentials are a single
atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
prop. The previous async refresh() was a no-op while state was still
'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
deterrent; a modal confirm adds friction without adding safety (the
plaintext is irrecoverable client-side either way — recovery means
re-typing).
DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.
Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.
Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
/ ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
RedactedSecretPlaceholder constant is retained because VectorStore
still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
redaction handling removed; i18n keys renamed secret -> credential.
2026-05-17 07:09:30 +00:00
|
|
|
if hasCreds && (ds.Type != existing.Type || configActuallyChanged) {
|
2026-03-27 07:02:40 +00:00
|
|
|
if err := s.validateDataSourceConfig(ctx, ds); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := s.dsRepo.Update(ctx, ds); err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to update data source: %v", err)
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Update cron schedule
|
|
|
|
|
if err := s.scheduler.AddOrUpdate(ds); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "failed to update cron for ds=%s: %v", ds.ID, err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "data source updated: id=%s", ds.ID)
|
2026-07-22 11:15:27 +00:00
|
|
|
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, types.AuditActionDataSourceUpdated,
|
|
|
|
|
"data_source", ds.ID, types.AuditOutcomeSuccess,
|
|
|
|
|
map[string]any{"name": ds.Name, "type": ds.Type, "changed_fields": []string{"settings"}})
|
2026-03-27 07:02:40 +00:00
|
|
|
return ds, nil
|
|
|
|
|
}
|
|
|
|
|
|
refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.
Why
---
The previous design had three problems:
1. Main PUT body carried secret fields. The frontend echoed back a
redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
defense in the service layer tried to detect "user did not change this"
vs "user wants to clear this". A regression in that defense (or a new
frontend forgetting it) silently overwrites the stored secret with the
placeholder.
2. The "remove this credential" UX was a red checkbox under a pre-filled
password input. Three intents (preserve / replace / clear) collapsed
onto one field, and credential changes were bundled with unrelated
config edits in the same submit. Users wiped working keys by mistake.
3. Secret presence was inferred from "did the response come back with a
'***' placeholder", which couples the contract to a magic string.
Design
------
Each of the four resources now exposes:
PUT /{resource}/{id}/credentials # write one or more fields
DELETE /{resource}/{id}/credentials/{field} # clear a single field
"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.
Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.
Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
(unconfigured / configured / editing) and drives the dedicated
endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
card with the same behaviour because its credentials are a single
atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
prop. The previous async refresh() was a no-op while state was still
'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
deterrent; a modal confirm adds friction without adding safety (the
plaintext is irrecoverable client-side either way — recovery means
re-typing).
DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.
Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.
Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
/ ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
RedactedSecretPlaceholder constant is retained because VectorStore
still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
redaction handling removed; i18n keys renamed secret -> credential.
2026-05-17 07:09:30 +00:00
|
|
|
// UpdateDataSourceCredentials replaces the connector credential map. This is
|
|
|
|
|
// a single atomic write; the previous credential set is discarded entirely
|
|
|
|
|
// (callers cannot patch individual keys because half-configured connector
|
|
|
|
|
// auth is meaningless). After persisting, the live connection is validated
|
|
|
|
|
// so the caller learns immediately if the new credentials are wrong.
|
|
|
|
|
func (s *DataSourceService) UpdateDataSourceCredentials(
|
|
|
|
|
ctx context.Context, id string, credentials map[string]interface{},
|
|
|
|
|
) (*types.DataSource, error) {
|
|
|
|
|
if id == "" {
|
|
|
|
|
return nil, datasource.ErrDataSourceInvalid
|
|
|
|
|
}
|
|
|
|
|
existing, err := s.dsRepo.FindByID(ctx, id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
parsed, err := existing.ParseConfig()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
if parsed == nil {
|
|
|
|
|
parsed = &types.DataSourceConfig{Type: existing.Type}
|
|
|
|
|
}
|
|
|
|
|
parsed.Credentials = credentials
|
2026-06-23 07:45:47 +00:00
|
|
|
parsed.StripNonSecretCredentials(existing.Type)
|
refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.
Why
---
The previous design had three problems:
1. Main PUT body carried secret fields. The frontend echoed back a
redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
defense in the service layer tried to detect "user did not change this"
vs "user wants to clear this". A regression in that defense (or a new
frontend forgetting it) silently overwrites the stored secret with the
placeholder.
2. The "remove this credential" UX was a red checkbox under a pre-filled
password input. Three intents (preserve / replace / clear) collapsed
onto one field, and credential changes were bundled with unrelated
config edits in the same submit. Users wiped working keys by mistake.
3. Secret presence was inferred from "did the response come back with a
'***' placeholder", which couples the contract to a magic string.
Design
------
Each of the four resources now exposes:
PUT /{resource}/{id}/credentials # write one or more fields
DELETE /{resource}/{id}/credentials/{field} # clear a single field
"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.
Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.
Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
(unconfigured / configured / editing) and drives the dedicated
endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
card with the same behaviour because its credentials are a single
atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
prop. The previous async refresh() was a no-op while state was still
'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
deterrent; a modal confirm adds friction without adding safety (the
plaintext is irrecoverable client-side either way — recovery means
re-typing).
DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.
Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.
Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
/ ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
RedactedSecretPlaceholder constant is retained because VectorStore
still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
redaction handling removed; i18n keys renamed secret -> credential.
2026-05-17 07:09:30 +00:00
|
|
|
blob, err := parsed.ToJSON()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
existing.Config = blob
|
|
|
|
|
|
|
|
|
|
// Run live validation now that the credentials are in place — surfaces
|
|
|
|
|
// "wrong token" feedback immediately to the user instead of waiting for
|
|
|
|
|
// the next scheduled sync.
|
|
|
|
|
if err := s.validateDataSourceConfig(ctx, existing); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
if err := s.dsRepo.Update(ctx, existing); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
logger.Infof(ctx, "DataSource credentials updated: id=%s", secutils.SanitizeForLog(id))
|
2026-07-22 11:15:27 +00:00
|
|
|
recordKBActivity(ctx, s.audit, existing.TenantID, existing.KnowledgeBaseID, types.AuditActionDataSourceUpdated,
|
|
|
|
|
"data_source", existing.ID, types.AuditOutcomeSuccess,
|
|
|
|
|
map[string]any{"name": existing.Name, "type": existing.Type, "changed_fields": []string{"credentials"}})
|
refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.
Why
---
The previous design had three problems:
1. Main PUT body carried secret fields. The frontend echoed back a
redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
defense in the service layer tried to detect "user did not change this"
vs "user wants to clear this". A regression in that defense (or a new
frontend forgetting it) silently overwrites the stored secret with the
placeholder.
2. The "remove this credential" UX was a red checkbox under a pre-filled
password input. Three intents (preserve / replace / clear) collapsed
onto one field, and credential changes were bundled with unrelated
config edits in the same submit. Users wiped working keys by mistake.
3. Secret presence was inferred from "did the response come back with a
'***' placeholder", which couples the contract to a magic string.
Design
------
Each of the four resources now exposes:
PUT /{resource}/{id}/credentials # write one or more fields
DELETE /{resource}/{id}/credentials/{field} # clear a single field
"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.
Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.
Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
(unconfigured / configured / editing) and drives the dedicated
endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
card with the same behaviour because its credentials are a single
atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
prop. The previous async refresh() was a no-op while state was still
'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
deterrent; a modal confirm adds friction without adding safety (the
plaintext is irrecoverable client-side either way — recovery means
re-typing).
DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.
Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.
Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
/ ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
RedactedSecretPlaceholder constant is retained because VectorStore
still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
redaction handling removed; i18n keys renamed secret -> credential.
2026-05-17 07:09:30 +00:00
|
|
|
return existing, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ClearDataSourceCredentials wipes the connector credential map without
|
|
|
|
|
// touching any other config field. Idempotent.
|
|
|
|
|
func (s *DataSourceService) ClearDataSourceCredentials(ctx context.Context, id string) error {
|
|
|
|
|
if id == "" {
|
|
|
|
|
return datasource.ErrDataSourceInvalid
|
|
|
|
|
}
|
|
|
|
|
existing, err := s.dsRepo.FindByID(ctx, id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
parsed, err := existing.ParseConfig()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2026-06-23 07:45:47 +00:00
|
|
|
if parsed == nil {
|
refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.
Why
---
The previous design had three problems:
1. Main PUT body carried secret fields. The frontend echoed back a
redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
defense in the service layer tried to detect "user did not change this"
vs "user wants to clear this". A regression in that defense (or a new
frontend forgetting it) silently overwrites the stored secret with the
placeholder.
2. The "remove this credential" UX was a red checkbox under a pre-filled
password input. Three intents (preserve / replace / clear) collapsed
onto one field, and credential changes were bundled with unrelated
config edits in the same submit. Users wiped working keys by mistake.
3. Secret presence was inferred from "did the response come back with a
'***' placeholder", which couples the contract to a magic string.
Design
------
Each of the four resources now exposes:
PUT /{resource}/{id}/credentials # write one or more fields
DELETE /{resource}/{id}/credentials/{field} # clear a single field
"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.
Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.
Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
(unconfigured / configured / editing) and drives the dedicated
endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
card with the same behaviour because its credentials are a single
atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
prop. The previous async refresh() was a no-op while state was still
'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
deterrent; a modal confirm adds friction without adding safety (the
plaintext is irrecoverable client-side either way — recovery means
re-typing).
DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.
Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.
Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
/ ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
RedactedSecretPlaceholder constant is retained because VectorStore
still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
redaction handling removed; i18n keys renamed secret -> credential.
2026-05-17 07:09:30 +00:00
|
|
|
return nil
|
|
|
|
|
}
|
2026-06-23 07:45:47 +00:00
|
|
|
parsed.StripNonSecretCredentials(existing.Type)
|
|
|
|
|
if !parsed.HasConfiguredCredentials(existing.Type) {
|
|
|
|
|
blob, err := parsed.ToJSON()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
existing.Config = blob
|
|
|
|
|
return s.dsRepo.Update(ctx, existing)
|
|
|
|
|
}
|
refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.
Why
---
The previous design had three problems:
1. Main PUT body carried secret fields. The frontend echoed back a
redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
defense in the service layer tried to detect "user did not change this"
vs "user wants to clear this". A regression in that defense (or a new
frontend forgetting it) silently overwrites the stored secret with the
placeholder.
2. The "remove this credential" UX was a red checkbox under a pre-filled
password input. Three intents (preserve / replace / clear) collapsed
onto one field, and credential changes were bundled with unrelated
config edits in the same submit. Users wiped working keys by mistake.
3. Secret presence was inferred from "did the response come back with a
'***' placeholder", which couples the contract to a magic string.
Design
------
Each of the four resources now exposes:
PUT /{resource}/{id}/credentials # write one or more fields
DELETE /{resource}/{id}/credentials/{field} # clear a single field
"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.
Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.
Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
(unconfigured / configured / editing) and drives the dedicated
endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
card with the same behaviour because its credentials are a single
atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
prop. The previous async refresh() was a no-op while state was still
'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
deterrent; a modal confirm adds friction without adding safety (the
plaintext is irrecoverable client-side either way — recovery means
re-typing).
DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.
Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.
Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
/ ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
RedactedSecretPlaceholder constant is retained because VectorStore
still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
redaction handling removed; i18n keys renamed secret -> credential.
2026-05-17 07:09:30 +00:00
|
|
|
parsed.Credentials = nil
|
|
|
|
|
blob, err := parsed.ToJSON()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
existing.Config = blob
|
|
|
|
|
if err := s.dsRepo.Update(ctx, existing); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
logger.Infof(ctx, "DataSource credentials cleared by user: id=%s", secutils.SanitizeForLog(id))
|
2026-07-22 11:15:27 +00:00
|
|
|
recordKBActivity(ctx, s.audit, existing.TenantID, existing.KnowledgeBaseID, types.AuditActionDataSourceUpdated,
|
|
|
|
|
"data_source", existing.ID, types.AuditOutcomeSuccess,
|
|
|
|
|
map[string]any{"name": existing.Name, "type": existing.Type, "changed_fields": []string{"credentials"}})
|
refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.
Why
---
The previous design had three problems:
1. Main PUT body carried secret fields. The frontend echoed back a
redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
defense in the service layer tried to detect "user did not change this"
vs "user wants to clear this". A regression in that defense (or a new
frontend forgetting it) silently overwrites the stored secret with the
placeholder.
2. The "remove this credential" UX was a red checkbox under a pre-filled
password input. Three intents (preserve / replace / clear) collapsed
onto one field, and credential changes were bundled with unrelated
config edits in the same submit. Users wiped working keys by mistake.
3. Secret presence was inferred from "did the response come back with a
'***' placeholder", which couples the contract to a magic string.
Design
------
Each of the four resources now exposes:
PUT /{resource}/{id}/credentials # write one or more fields
DELETE /{resource}/{id}/credentials/{field} # clear a single field
"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.
Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.
Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
(unconfigured / configured / editing) and drives the dedicated
endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
card with the same behaviour because its credentials are a single
atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
prop. The previous async refresh() was a no-op while state was still
'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
deterrent; a modal confirm adds friction without adding safety (the
plaintext is irrecoverable client-side either way — recovery means
re-typing).
DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.
Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.
Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
/ ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
RedactedSecretPlaceholder constant is retained because VectorStore
still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
redaction handling removed; i18n keys renamed secret -> credential.
2026-05-17 07:09:30 +00:00
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-27 07:02:40 +00:00
|
|
|
// DeleteDataSource deletes a data source (soft delete)
|
|
|
|
|
func (s *DataSourceService) DeleteDataSource(ctx context.Context, id string) error {
|
|
|
|
|
// Verify data source exists
|
2026-07-22 11:15:27 +00:00
|
|
|
existing, err := s.dsRepo.FindByID(ctx, id)
|
2026-03-27 07:02:40 +00:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := s.dsRepo.Delete(ctx, id); err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to delete data source: %v", err)
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Remove cron schedule
|
|
|
|
|
s.scheduler.Remove(id)
|
|
|
|
|
|
2026-03-30 07:12:00 +00:00
|
|
|
// Cancel any pending/running sync logs so queued asynq tasks won't retry
|
|
|
|
|
if err := s.syncLogRepo.CancelPendingByDataSource(ctx, id); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "failed to cancel pending sync logs for ds=%s: %v", id, err)
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-27 07:02:40 +00:00
|
|
|
logger.Infof(ctx, "data source deleted: id=%s", id)
|
2026-07-22 11:15:27 +00:00
|
|
|
recordKBActivity(ctx, s.audit, existing.TenantID, existing.KnowledgeBaseID, types.AuditActionDataSourceDeleted,
|
|
|
|
|
"data_source", existing.ID, types.AuditOutcomeSuccess,
|
|
|
|
|
map[string]any{"name": existing.Name, "type": existing.Type})
|
2026-03-27 07:02:40 +00:00
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ValidateConnection tests the connection to an external data source
|
|
|
|
|
func (s *DataSourceService) ValidateConnection(ctx context.Context, dsID string) error {
|
|
|
|
|
ds, err := s.GetDataSource(ctx, dsID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Get connector
|
|
|
|
|
connector, err := s.connectorRegistry.Get(ds.Type)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Parse configuration
|
|
|
|
|
config, err := ds.ParseConfig()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return datasource.ErrInvalidConfig
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Validate connection
|
|
|
|
|
if err := connector.Validate(ctx, config); err != nil {
|
|
|
|
|
// Update data source with error
|
|
|
|
|
ds.Status = types.DataSourceStatusError
|
|
|
|
|
ds.ErrorMessage = err.Error()
|
|
|
|
|
_ = s.dsRepo.Update(ctx, ds)
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Clear error if it was previously in error state
|
|
|
|
|
if ds.Status == types.DataSourceStatusError {
|
|
|
|
|
ds.Status = types.DataSourceStatusActive
|
|
|
|
|
ds.ErrorMessage = ""
|
|
|
|
|
_ = s.dsRepo.Update(ctx, ds)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-22 09:41:18 +00:00
|
|
|
// ListAvailableResources lists resources available for sync in the external system.
|
|
|
|
|
// parentID enables lazy (on-demand) loading of hierarchical resources: pass "" to
|
|
|
|
|
// list the top level, or a resource's ExternalID to list only its direct children.
|
|
|
|
|
func (s *DataSourceService) ListAvailableResources(
|
|
|
|
|
ctx context.Context, dsID string, parentID string,
|
|
|
|
|
) ([]types.Resource, error) {
|
2026-03-27 07:02:40 +00:00
|
|
|
ds, err := s.GetDataSource(ctx, dsID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Get connector
|
|
|
|
|
connector, err := s.connectorRegistry.Get(ds.Type)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Parse configuration
|
|
|
|
|
config, err := ds.ParseConfig()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, datasource.ErrInvalidConfig
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// List resources
|
2026-06-22 09:41:18 +00:00
|
|
|
resources, err := connector.ListResources(ctx, config, parentID)
|
2026-03-27 07:02:40 +00:00
|
|
|
if err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to list resources: %v", err)
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return resources, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-22 10:15:27 +00:00
|
|
|
// ResolveResourceAncestors resolves the ancestor ExternalIDs needed to reveal the
|
|
|
|
|
// given resources in a lazily-loaded picker (see the connector method for details).
|
|
|
|
|
func (s *DataSourceService) ResolveResourceAncestors(
|
|
|
|
|
ctx context.Context, dsID string, resourceIDs []string,
|
|
|
|
|
) ([]string, error) {
|
|
|
|
|
if len(resourceIDs) == 0 {
|
|
|
|
|
return []string{}, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ds, err := s.GetDataSource(ctx, dsID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
connector, err := s.connectorRegistry.Get(ds.Type)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
config, err := ds.ParseConfig()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, datasource.ErrInvalidConfig
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ancestors, err := connector.ResolveResourceAncestors(ctx, config, resourceIDs)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to resolve resource ancestors: %v", err)
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return ancestors, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-27 07:02:40 +00:00
|
|
|
// ManualSync triggers an immediate sync for a data source
|
|
|
|
|
func (s *DataSourceService) ManualSync(ctx context.Context, dsID string) (*types.SyncLog, error) {
|
|
|
|
|
ds, err := s.GetDataSource(ctx, dsID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-30 12:10:08 +00:00
|
|
|
if ds.Status != types.DataSourceStatusActive &&
|
|
|
|
|
ds.Status != types.DataSourceStatusError &&
|
|
|
|
|
ds.Status != types.DataSourceStatusPaused {
|
2026-03-27 07:02:40 +00:00
|
|
|
return nil, datasource.ErrDataSourceNotActive
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Create sync log
|
|
|
|
|
syncLog := &types.SyncLog{
|
|
|
|
|
DataSourceID: dsID,
|
|
|
|
|
TenantID: ds.TenantID,
|
|
|
|
|
Status: types.SyncLogStatusRunning,
|
|
|
|
|
StartedAt: time.Now().UTC(),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := s.syncLogRepo.Create(ctx, syncLog); err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to create sync log: %v", err)
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Enqueue sync task
|
|
|
|
|
payload := &types.DataSourceSyncPayload{
|
|
|
|
|
DataSourceID: dsID,
|
|
|
|
|
TenantID: ds.TenantID,
|
|
|
|
|
SyncLogID: syncLog.ID,
|
|
|
|
|
ForceFull: false,
|
2026-07-22 11:15:27 +00:00
|
|
|
Initiator: types.TaskInitiatorFromContext(ctx),
|
|
|
|
|
Trigger: "manual",
|
2026-03-27 07:02:40 +00:00
|
|
|
}
|
feat(observability): extend Langfuse tracing across asynq pipeline
Previously the Langfuse integration only traced in-process HTTP requests
(chat / search / eval), so file uploads and every downstream asynq task
(document parse, chunk embedding, OCR/VLM, summary / question gen, wiki
ingest, datasource sync, etc.) produced either disconnected shallow
traces or no observation at all.
This change threads one trace end-to-end:
- tracer: add SPAN observation type and StartSpan; add ResumeTrace so a
worker can attach to an upstream trace without emitting a duplicate
trace-create; StartGeneration now auto-picks parentObservationId from
ctx so nested trace -> span -> generation trees render correctly.
- types.TracingContext + LangfuseTracingCarrier: embed on all 17 asynq
payloads so trace_id / parent_obs_id / user_id / session_id serialise
into every job.
- langfuse.InjectTracing: injected at 28 enqueue sites before json.Marshal
so the HTTP-layer trace survives the Redis hop.
- langfuse.AsynqMiddleware: mux.Use hook that peeks the payload, either
resumes the upstream trace or opens a standalone asynq.<type> trace
for scheduled jobs, and wraps the handler in a SPAN with task metadata
(id / queue / retry / payload_bytes) plus ERROR level on failure.
- GinMiddleware.shouldTrace: whitelist ingestion / knowledge-mutation /
FAQ / wiki / datasource endpoints so the root trace actually starts.
- Tests: tracer_test.go covers span nesting, error status, and
ResumeTrace no-trace-create guarantee; asynq_test.go covers
InjectTracing round-trip, middleware resume path, and standalone
trace fallback.
- Docs: docs/Langfuse\u96c6\u6210.md now lists the covered task types
and documents the cross-process propagation model.
No behavioural change when Langfuse is disabled (all new code paths are
no-ops and carriers serialise to empty strings with omitempty).
2026-04-24 04:23:30 +00:00
|
|
|
langfuse.InjectTracing(ctx, payload)
|
2026-03-27 07:02:40 +00:00
|
|
|
|
|
|
|
|
payloadJSON, _ := json.Marshal(payload)
|
2026-07-10 15:19:41 +00:00
|
|
|
task := asynq.NewTask(types.TypeDataSourceSync, payloadJSON,
|
|
|
|
|
asynq.Queue(types.QueueSync), asynq.MaxRetry(5), asynq.Timeout(2*time.Hour))
|
2026-03-27 07:02:40 +00:00
|
|
|
|
2026-07-22 11:15:27 +00:00
|
|
|
info, err := s.taskEnqueuer.Enqueue(task)
|
2026-03-27 07:02:40 +00:00
|
|
|
if err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to enqueue sync task: %v", err)
|
|
|
|
|
syncLog.Status = types.SyncLogStatusFailed
|
2026-03-30 11:33:17 +00:00
|
|
|
syncLog.FinishedAt = timePtr(time.Now().UTC())
|
2026-03-27 07:02:40 +00:00
|
|
|
syncLog.ErrorMessage = err.Error()
|
|
|
|
|
_ = s.syncLogRepo.Update(ctx, syncLog)
|
2026-03-30 12:10:08 +00:00
|
|
|
if ds.Status != types.DataSourceStatusPaused {
|
|
|
|
|
ds.Status = types.DataSourceStatusError
|
|
|
|
|
}
|
2026-03-30 07:08:57 +00:00
|
|
|
ds.ErrorMessage = fmt.Sprintf("Failed to enqueue sync: %v", err)
|
|
|
|
|
_ = s.dsRepo.Update(ctx, ds)
|
2026-07-22 11:15:27 +00:00
|
|
|
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, types.AuditActionDataSourceSyncFailed,
|
|
|
|
|
"data_source", ds.ID, types.AuditOutcomeFailed,
|
|
|
|
|
map[string]any{"name": ds.Name, "type": ds.Type, "sync_log_id": syncLog.ID, "trigger": "manual"})
|
2026-03-27 07:02:40 +00:00
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "sync task enqueued: ds=%s syncLog=%s", dsID, syncLog.ID)
|
2026-07-22 11:15:27 +00:00
|
|
|
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, types.AuditActionDataSourceSyncStarted,
|
|
|
|
|
"data_source", ds.ID, types.AuditOutcomeAccepted,
|
|
|
|
|
map[string]any{"name": ds.Name, "type": ds.Type, "sync_log_id": syncLog.ID,
|
|
|
|
|
"task_id": info.ID, "trigger": "manual", "processing_status": "pending"})
|
2026-03-27 07:02:40 +00:00
|
|
|
return syncLog, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// PauseDataSource pauses a data source's scheduled syncs
|
|
|
|
|
func (s *DataSourceService) PauseDataSource(ctx context.Context, id string) error {
|
|
|
|
|
ds, err := s.GetDataSource(ctx, id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ds.Status = types.DataSourceStatusPaused
|
|
|
|
|
if err := s.dsRepo.Update(ctx, ds); err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to pause data source: %v", err)
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Remove cron schedule
|
|
|
|
|
s.scheduler.Remove(id)
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "data source paused: id=%s", id)
|
2026-07-22 11:15:27 +00:00
|
|
|
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, types.AuditActionDataSourcePaused,
|
|
|
|
|
"data_source", ds.ID, types.AuditOutcomeSuccess, map[string]any{"name": ds.Name, "type": ds.Type})
|
2026-03-27 07:02:40 +00:00
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ResumeDataSource resumes a paused data source
|
|
|
|
|
func (s *DataSourceService) ResumeDataSource(ctx context.Context, id string) error {
|
|
|
|
|
ds, err := s.GetDataSource(ctx, id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ds.Status = types.DataSourceStatusActive
|
|
|
|
|
if err := s.dsRepo.Update(ctx, ds); err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to resume data source: %v", err)
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Re-register cron schedule
|
|
|
|
|
if err := s.scheduler.AddOrUpdate(ds); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "failed to re-register cron for ds=%s: %v", ds.ID, err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "data source resumed: id=%s", id)
|
2026-07-22 11:15:27 +00:00
|
|
|
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, types.AuditActionDataSourceResumed,
|
|
|
|
|
"data_source", ds.ID, types.AuditOutcomeSuccess, map[string]any{"name": ds.Name, "type": ds.Type})
|
2026-03-27 07:02:40 +00:00
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// GetSyncLogs retrieves sync history for a data source
|
|
|
|
|
func (s *DataSourceService) GetSyncLogs(ctx context.Context, dsID string, limit int, offset int) ([]*types.SyncLog, error) {
|
|
|
|
|
logs, err := s.syncLogRepo.FindByDataSource(ctx, dsID, limit, offset)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to get sync logs: %v", err)
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return logs, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// GetSyncLog retrieves a specific sync log entry
|
|
|
|
|
func (s *DataSourceService) GetSyncLog(ctx context.Context, syncLogID string) (*types.SyncLog, error) {
|
|
|
|
|
log, err := s.syncLogRepo.FindByID(ctx, syncLogID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return log, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ProcessSync handles the actual sync operation (called by asynq task)
|
|
|
|
|
func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) error {
|
|
|
|
|
var payload types.DataSourceSyncPayload
|
|
|
|
|
if err := json.Unmarshal(task.Payload(), &payload); err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to unmarshal sync payload: %v", err)
|
|
|
|
|
return err
|
|
|
|
|
}
|
2026-07-22 11:15:27 +00:00
|
|
|
ctx = payload.Initiator.Apply(ctx)
|
|
|
|
|
taskID, _ := asynq.GetTaskID(ctx)
|
|
|
|
|
ctx = withKBActivityTask(ctx, taskID, payload.Trigger)
|
2026-03-27 07:02:40 +00:00
|
|
|
|
|
|
|
|
logger.Infof(ctx, "processing data source sync: ds=%s syncLog=%s", payload.DataSourceID, payload.SyncLogID)
|
|
|
|
|
|
|
|
|
|
// Get data source
|
|
|
|
|
ds, err := s.GetDataSource(ctx, payload.DataSourceID)
|
|
|
|
|
if err != nil {
|
2026-03-30 07:12:00 +00:00
|
|
|
logger.Warnf(ctx, "data source not found (likely deleted), cancelling sync: ds=%s err=%v", payload.DataSourceID, err)
|
|
|
|
|
if syncLog, slErr := s.syncLogRepo.FindByID(ctx, payload.SyncLogID); slErr == nil && syncLog != nil {
|
|
|
|
|
syncLog.Status = types.SyncLogStatusCanceled
|
2026-03-30 11:33:17 +00:00
|
|
|
syncLog.FinishedAt = timePtr(time.Now().UTC())
|
2026-03-30 07:12:00 +00:00
|
|
|
syncLog.ErrorMessage = "data source has been deleted"
|
|
|
|
|
_ = s.syncLogRepo.Update(ctx, syncLog)
|
|
|
|
|
}
|
|
|
|
|
return nil
|
2026-03-27 07:02:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Get sync log
|
|
|
|
|
syncLog, err := s.syncLogRepo.FindByID(ctx, payload.SyncLogID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to get sync log: %v", err)
|
2026-03-30 07:12:00 +00:00
|
|
|
return nil
|
2026-03-27 07:02:40 +00:00
|
|
|
}
|
|
|
|
|
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
kb, kbErr := s.kbService.GetKnowledgeBaseByID(ctx, ds.KnowledgeBaseID)
|
|
|
|
|
if kbErr != nil {
|
2026-06-23 07:45:47 +00:00
|
|
|
logger.Warnf(ctx, "knowledge base not found (likely deleted), cancelling sync: kb=%s ds=%s err=%v",
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
ds.KnowledgeBaseID, payload.DataSourceID, kbErr)
|
2026-06-23 07:45:47 +00:00
|
|
|
syncLog.Status = types.SyncLogStatusCanceled
|
|
|
|
|
syncLog.FinishedAt = timePtr(time.Now().UTC())
|
|
|
|
|
syncLog.ErrorMessage = "knowledge base has been deleted"
|
|
|
|
|
_ = s.syncLogRepo.Update(ctx, syncLog)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-30 12:10:08 +00:00
|
|
|
wasPaused := ds.Status == types.DataSourceStatusPaused
|
|
|
|
|
|
2026-03-27 07:02:40 +00:00
|
|
|
// Get connector
|
|
|
|
|
connector, err := s.connectorRegistry.Get(ds.Type)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Errorf(ctx, "connector not found: type=%s", ds.Type)
|
|
|
|
|
syncLog.Status = types.SyncLogStatusFailed
|
2026-03-30 11:33:17 +00:00
|
|
|
syncLog.FinishedAt = timePtr(time.Now().UTC())
|
2026-03-27 07:02:40 +00:00
|
|
|
syncLog.ErrorMessage = fmt.Sprintf("Connector not found: %s", ds.Type)
|
|
|
|
|
_ = s.syncLogRepo.Update(ctx, syncLog)
|
2026-03-30 12:10:08 +00:00
|
|
|
if !wasPaused {
|
|
|
|
|
ds.Status = types.DataSourceStatusError
|
|
|
|
|
}
|
2026-03-30 07:08:57 +00:00
|
|
|
ds.ErrorMessage = syncLog.ErrorMessage
|
|
|
|
|
_ = s.dsRepo.Update(ctx, ds)
|
2026-03-27 07:02:40 +00:00
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Parse configuration
|
|
|
|
|
config, err := ds.ParseConfig()
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to parse config: %v", err)
|
|
|
|
|
syncLog.Status = types.SyncLogStatusFailed
|
2026-03-30 11:33:17 +00:00
|
|
|
syncLog.FinishedAt = timePtr(time.Now().UTC())
|
2026-03-27 07:02:40 +00:00
|
|
|
syncLog.ErrorMessage = fmt.Sprintf("Invalid configuration: %v", err)
|
|
|
|
|
_ = s.syncLogRepo.Update(ctx, syncLog)
|
2026-03-30 12:10:08 +00:00
|
|
|
if !wasPaused {
|
|
|
|
|
ds.Status = types.DataSourceStatusError
|
|
|
|
|
}
|
2026-03-30 07:08:57 +00:00
|
|
|
ds.ErrorMessage = syncLog.ErrorMessage
|
|
|
|
|
_ = s.dsRepo.Update(ctx, ds)
|
2026-03-27 07:02:40 +00:00
|
|
|
return err
|
|
|
|
|
}
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
// Surface the KB's multimodal/VLM state to the connector so it only extracts
|
|
|
|
|
// embedded images for OCR when the KB can actually ingest them (never persisted).
|
|
|
|
|
config.MultimodalEnabled = kb.IsMultimodalEnabled()
|
2026-03-27 07:02:40 +00:00
|
|
|
|
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.
2026-07-20 16:20:57 +00:00
|
|
|
// 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)
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-27 07:02:40 +00:00
|
|
|
// Fetch items based on sync mode
|
|
|
|
|
var items []types.FetchedItem
|
|
|
|
|
var nextCursor *types.SyncCursor
|
|
|
|
|
var fetchErr error
|
|
|
|
|
|
|
|
|
|
if payload.ForceFull || ds.SyncMode == types.SyncModeFull {
|
|
|
|
|
// Full sync
|
|
|
|
|
items, fetchErr = connector.FetchAll(ctx, config, config.ResourceIDs)
|
|
|
|
|
logger.Infof(ctx, "full sync fetched %d items", len(items))
|
|
|
|
|
} else {
|
|
|
|
|
// Incremental sync
|
|
|
|
|
cursor, _ := ds.ParseSyncCursor()
|
|
|
|
|
items, nextCursor, fetchErr = connector.FetchIncremental(ctx, config, cursor)
|
|
|
|
|
logger.Infof(ctx, "incremental sync fetched %d items", len(items))
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-23 08:03:38 +00:00
|
|
|
var fetchWarnings []string
|
|
|
|
|
var partialFetch *datasource.PartialFetchError
|
|
|
|
|
if errors.As(fetchErr, &partialFetch) {
|
|
|
|
|
fetchWarnings = partialFetch.Details
|
|
|
|
|
fetchErr = nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-27 07:02:40 +00:00
|
|
|
if fetchErr != nil {
|
2026-06-23 08:03:38 +00:00
|
|
|
// Persist connector cursor even when fetch failed so transient outages
|
|
|
|
|
// (e.g. RSS feed downtime) do not force a full re-ingest on recovery.
|
|
|
|
|
if nextCursor != nil {
|
|
|
|
|
if cursorJSON, cerr := nextCursor.ToJSON(); cerr == nil {
|
|
|
|
|
ds.LastSyncCursor = cursorJSON
|
|
|
|
|
if uerr := s.dsRepo.UpdateSyncState(ctx, ds); uerr != nil {
|
|
|
|
|
logger.Warnf(ctx, "failed to persist sync cursor after fetch error: %v", uerr)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-03-27 07:02:40 +00:00
|
|
|
logger.Errorf(ctx, "fetch operation failed: %v", fetchErr)
|
|
|
|
|
syncLog.Status = types.SyncLogStatusFailed
|
2026-03-30 11:33:17 +00:00
|
|
|
syncLog.FinishedAt = timePtr(time.Now().UTC())
|
2026-03-27 07:02:40 +00:00
|
|
|
syncLog.ErrorMessage = fmt.Sprintf("Fetch failed: %v", fetchErr)
|
|
|
|
|
_ = s.syncLogRepo.Update(ctx, syncLog)
|
2026-03-30 12:10:08 +00:00
|
|
|
if !wasPaused {
|
|
|
|
|
ds.Status = types.DataSourceStatusError
|
|
|
|
|
}
|
2026-03-30 07:08:57 +00:00
|
|
|
ds.ErrorMessage = syncLog.ErrorMessage
|
|
|
|
|
_ = s.dsRepo.Update(ctx, ds)
|
2026-03-27 07:02:40 +00:00
|
|
|
return fetchErr
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Process fetched items and write to knowledge base
|
|
|
|
|
var result = &types.SyncResult{
|
|
|
|
|
Total: len(items),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Set tenant context so KnowledgeService can resolve tenant info correctly
|
|
|
|
|
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)
|
|
|
|
|
syncLog.Status = types.SyncLogStatusFailed
|
2026-03-30 11:33:17 +00:00
|
|
|
syncLog.FinishedAt = timePtr(time.Now().UTC())
|
2026-03-27 07:02:40 +00:00
|
|
|
syncLog.ErrorMessage = fmt.Sprintf("Failed to get tenant info: %v", err)
|
|
|
|
|
_ = s.syncLogRepo.Update(ctx, syncLog)
|
2026-03-30 12:10:08 +00:00
|
|
|
if !wasPaused {
|
|
|
|
|
ds.Status = types.DataSourceStatusError
|
|
|
|
|
}
|
2026-03-30 07:08:57 +00:00
|
|
|
ds.ErrorMessage = syncLog.ErrorMessage
|
|
|
|
|
_ = s.dsRepo.Update(ctx, ds)
|
2026-03-27 07:02:40 +00:00
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenant)
|
|
|
|
|
|
|
|
|
|
// Auto-tag: find or create a tag for this data source so synced items are easily identifiable
|
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.
2026-07-20 16:20:57 +00:00
|
|
|
autoTagIDs := s.resolveAutoTagIDs(ctx, ds)
|
2026-03-27 07:02:40 +00:00
|
|
|
|
|
|
|
|
for _, item := range items {
|
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.
2026-07-20 16:20:57 +00:00
|
|
|
item := item
|
2026-07-22 11:15:27 +00:00
|
|
|
s.applyFetchedItem(withKBActivitySuppressed(ctx), ds, &item, autoTagIDs, result)
|
2026-03-27 07:02:40 +00:00
|
|
|
}
|
|
|
|
|
|
2026-06-04 08:16:05 +00:00
|
|
|
resultJSON, _ := result.ToJSON()
|
|
|
|
|
if err := allFetchedItemsFailedError(result); err != nil {
|
|
|
|
|
logger.Errorf(ctx, "data source sync failed while processing fetched items: %v", err)
|
|
|
|
|
s.updateSyncRunResult(ctx, ds, syncLog, result, resultJSON, types.SyncLogStatusFailed, err.Error(), wasPaused)
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Update cursor for next incremental sync
|
|
|
|
|
if nextCursor != nil {
|
|
|
|
|
cursorJSON, _ := nextCursor.ToJSON()
|
|
|
|
|
ds.LastSyncCursor = cursorJSON
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ds.LastSyncAt = timePtr(time.Now().UTC())
|
2026-06-23 08:03:38 +00:00
|
|
|
syncStatus := types.SyncLogStatusSuccess
|
|
|
|
|
syncErrorMessage := ""
|
|
|
|
|
if len(fetchWarnings) > 0 {
|
|
|
|
|
syncStatus = types.SyncLogStatusPartial
|
|
|
|
|
syncErrorMessage = fmt.Sprintf("Some feeds failed: %s", strings.Join(fetchWarnings, "; "))
|
|
|
|
|
for _, w := range fetchWarnings {
|
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.
2026-07-20 16:20:57 +00:00
|
|
|
result.Errors = append(result.Errors, types.SyncItemError{Message: w})
|
2026-06-23 08:03:38 +00:00
|
|
|
}
|
|
|
|
|
resultJSON, _ = result.ToJSON()
|
|
|
|
|
}
|
2026-08-13 11:52:44 +00:00
|
|
|
if result.Failed > 0 {
|
|
|
|
|
// Per-document failures flip the sync to partial so the drawer shows
|
|
|
|
|
// which docs didn't make it (mirrors the streaming path). Deletion
|
|
|
|
|
// failures additionally only retry on a later full sync.
|
|
|
|
|
syncStatus = types.SyncLogStatusPartial
|
|
|
|
|
if syncErrorMessage != "" {
|
|
|
|
|
syncErrorMessage += "; "
|
|
|
|
|
}
|
|
|
|
|
syncErrorMessage += fmt.Sprintf("%d document(s) failed to sync", result.Failed)
|
|
|
|
|
if result.DeletionFailed > 0 {
|
|
|
|
|
syncErrorMessage += fmt.Sprintf(
|
|
|
|
|
"; %d deletion failure(s) will only retry on the next full sync", result.DeletionFailed)
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-06-23 08:03:38 +00:00
|
|
|
s.updateSyncRunResult(ctx, ds, syncLog, result, resultJSON, syncStatus, syncErrorMessage, wasPaused)
|
2026-06-04 08:16:05 +00:00
|
|
|
|
|
|
|
|
logger.Infof(ctx, "data source sync completed: ds=%s created=%d updated=%d deleted=%d",
|
|
|
|
|
payload.DataSourceID, syncLog.ItemsCreated, syncLog.ItemsUpdated, syncLog.ItemsDeleted)
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
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.
2026-07-20 16:20:57 +00:00
|
|
|
// 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 {
|
2026-08-13 11:52:44 +00:00
|
|
|
if !ds.SyncDeletions {
|
|
|
|
|
// Sync deletion disabled: neither count nor delete.
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if item.ExternalID == "" {
|
|
|
|
|
logger.Warnf(ctx, "skipping deletion for item %q: empty external_id", item.Title)
|
|
|
|
|
result.Skipped++
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
// Perform real KB deletion, scoped to items owned by this data source
|
|
|
|
|
// so identical external IDs from different data sources cannot collide.
|
|
|
|
|
repo := s.knowledgeService.GetRepository()
|
|
|
|
|
existing, lookupErr := repo.FindByDataSourceExternalID(
|
|
|
|
|
ctx, ds.TenantID, ds.KnowledgeBaseID, ds.ID, item.ExternalID,
|
|
|
|
|
)
|
|
|
|
|
if lookupErr != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to find deleted knowledge for external_id=%s (ds=%s, kb=%s): %v",
|
|
|
|
|
item.ExternalID, ds.ID, ds.KnowledgeBaseID, lookupErr)
|
|
|
|
|
result.Failed++
|
|
|
|
|
result.DeletionFailed++
|
|
|
|
|
recordSyncError(result, types.SyncItemError{
|
|
|
|
|
Title: item.Title,
|
|
|
|
|
Code: "deletion_lookup_failed",
|
|
|
|
|
Message: "Failed to look up the item before deletion; see server logs",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if existing == nil {
|
|
|
|
|
// Deletion is idempotent: the source item may already have been
|
|
|
|
|
// removed manually or by an earlier sync.
|
|
|
|
|
result.Skipped++
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if deleteErr := s.knowledgeService.DeleteKnowledge(ctx, existing.ID); deleteErr != nil {
|
|
|
|
|
// The cursor is already past this item, so a failed deletion normally
|
|
|
|
|
// retries only on a later full sync. Counted separately so the
|
|
|
|
|
// sync-log message can warn the operator about this gap.
|
|
|
|
|
result.Failed++
|
|
|
|
|
result.DeletionFailed++
|
|
|
|
|
logger.Errorf(ctx, "failed to delete knowledge %s for external_id=%s (ds=%s): %v",
|
|
|
|
|
existing.ID, item.ExternalID, ds.ID, deleteErr)
|
|
|
|
|
recordSyncError(result, types.SyncItemError{
|
|
|
|
|
Title: item.Title,
|
|
|
|
|
Code: "deletion_failed",
|
|
|
|
|
Message: "Deletion failed; see server logs",
|
|
|
|
|
})
|
|
|
|
|
return
|
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.
2026-07-20 16:20:57 +00:00
|
|
|
}
|
2026-08-13 11:52:44 +00:00
|
|
|
if herr := repo.HardDeleteKnowledge(ctx, ds.TenantID, existing.ID); herr != nil {
|
|
|
|
|
result.Failed++
|
|
|
|
|
result.DeletionFailed++
|
|
|
|
|
logger.Errorf(ctx, "failed to hard-delete knowledge %s for external_id=%s (ds=%s): %v",
|
|
|
|
|
existing.ID, item.ExternalID, ds.ID, herr)
|
|
|
|
|
recordSyncError(result, types.SyncItemError{
|
|
|
|
|
Title: item.Title,
|
|
|
|
|
Code: "deletion_failed",
|
|
|
|
|
Message: "Deletion failed; see server logs",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
result.Deleted++
|
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.
2026-07-20 16:20:57 +00:00
|
|
|
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 {
|
|
|
|
|
var dupErr *types.DuplicateKnowledgeError
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
switch {
|
|
|
|
|
case errors.As(err, &dupErr):
|
|
|
|
|
// Duplicate file/URL is not a failure — count as skipped.
|
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.
2026-07-20 16:20:57 +00:00
|
|
|
logger.Infof(ctx, "item %q (external_id=%s) already exists, skipping", item.Title, item.ExternalID)
|
|
|
|
|
result.Skipped++
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
case item.Metadata["embedded_image"] == "true":
|
|
|
|
|
// An image extracted from a document for OCR is a best-effort
|
|
|
|
|
// enrichment, not the document itself. If the KB cannot ingest it
|
|
|
|
|
// (VLM/object-storage not configured for images, or a transient error),
|
|
|
|
|
// skip it rather than failing the whole sync: the doc body already
|
|
|
|
|
// synced, and the image stays in SubtreeKeep for a later retry once the
|
|
|
|
|
// KB is configured.
|
|
|
|
|
logger.Infof(ctx, "skipping embedded image %q (external_id=%s), not ingested: %v",
|
|
|
|
|
item.Title, item.ExternalID, err)
|
|
|
|
|
result.Skipped++
|
|
|
|
|
default:
|
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.
2026-07-20 16:20:57 +00:00
|
|
|
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++
|
2026-07-22 11:15:27 +00:00
|
|
|
h.svc.applyFetchedItem(withKBActivitySuppressed(ctx), h.ds, &item, h.tagIDs, h.result)
|
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.
2026-07-20 16:20:57 +00:00
|
|
|
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"
|
2026-08-13 11:52:44 +00:00
|
|
|
// (Tencent/WeKnora#2136). Fetch failures abort the stream before the failed
|
|
|
|
|
// page is checkpointed, so the next run retries them; deletion failures are
|
|
|
|
|
// past the cursor and only retry on a full sync in the normal case (see
|
|
|
|
|
// applyFetchedItem).
|
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.
2026-07-20 16:20:57 +00:00
|
|
|
status := types.SyncLogStatusSuccess
|
|
|
|
|
errMsg := ""
|
|
|
|
|
if result.Failed > 0 {
|
|
|
|
|
status = types.SyncLogStatusPartial
|
|
|
|
|
errMsg = fmt.Sprintf("%d document(s) failed to sync", result.Failed)
|
2026-08-13 11:52:44 +00:00
|
|
|
if result.DeletionFailed > 0 {
|
|
|
|
|
errMsg += fmt.Sprintf("; %d deletion failure(s) will only retry on the next full sync", result.DeletionFailed)
|
|
|
|
|
}
|
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.
2026-07-20 16:20:57 +00:00
|
|
|
}
|
|
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-04 08:16:05 +00:00
|
|
|
func (s *DataSourceService) updateSyncRunResult(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
ds *types.DataSource,
|
|
|
|
|
syncLog *types.SyncLog,
|
|
|
|
|
result *types.SyncResult,
|
|
|
|
|
resultJSON types.JSON,
|
|
|
|
|
status string,
|
|
|
|
|
errorMessage string,
|
|
|
|
|
wasPaused bool,
|
|
|
|
|
) {
|
2026-03-27 07:02:40 +00:00
|
|
|
syncLog.ItemsTotal = result.Total
|
|
|
|
|
syncLog.ItemsCreated = result.Created
|
|
|
|
|
syncLog.ItemsUpdated = result.Updated
|
|
|
|
|
syncLog.ItemsDeleted = result.Deleted
|
|
|
|
|
syncLog.ItemsSkipped = result.Skipped
|
|
|
|
|
syncLog.ItemsFailed = result.Failed
|
2026-06-04 08:16:05 +00:00
|
|
|
syncLog.Status = status
|
2026-03-30 11:33:17 +00:00
|
|
|
syncLog.FinishedAt = timePtr(time.Now().UTC())
|
2026-06-04 08:16:05 +00:00
|
|
|
syncLog.ErrorMessage = errorMessage
|
|
|
|
|
syncLog.Result = resultJSON
|
|
|
|
|
if err := s.syncLogRepo.UpdateResult(ctx, syncLog); err != nil {
|
|
|
|
|
logger.Errorf(ctx, "failed to update sync log: %v", err)
|
2026-03-27 07:02:40 +00:00
|
|
|
}
|
|
|
|
|
|
2026-06-04 08:16:05 +00:00
|
|
|
if status == types.SyncLogStatusFailed {
|
|
|
|
|
if !wasPaused {
|
|
|
|
|
ds.Status = types.DataSourceStatusError
|
|
|
|
|
}
|
|
|
|
|
} else if wasPaused {
|
2026-03-30 12:10:08 +00:00
|
|
|
ds.Status = types.DataSourceStatusPaused
|
|
|
|
|
} else {
|
|
|
|
|
ds.Status = types.DataSourceStatusActive
|
|
|
|
|
}
|
2026-06-04 08:16:05 +00:00
|
|
|
ds.ErrorMessage = errorMessage
|
2026-03-27 07:02:40 +00:00
|
|
|
ds.LastSyncResult = resultJSON
|
2026-06-04 08:16:05 +00:00
|
|
|
if err := s.dsRepo.UpdateSyncState(ctx, ds); err != nil {
|
2026-03-27 07:02:40 +00:00
|
|
|
logger.Errorf(ctx, "failed to update data source: %v", err)
|
|
|
|
|
}
|
2026-07-22 11:15:27 +00:00
|
|
|
action := types.AuditActionDataSourceSyncCompleted
|
|
|
|
|
outcome := types.AuditOutcomeSuccess
|
|
|
|
|
if status == types.SyncLogStatusFailed {
|
|
|
|
|
action = types.AuditActionDataSourceSyncFailed
|
|
|
|
|
outcome = types.AuditOutcomeFailed
|
|
|
|
|
} else if status == types.SyncLogStatusPartial {
|
|
|
|
|
outcome = types.AuditOutcomePartial
|
|
|
|
|
}
|
|
|
|
|
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, action,
|
|
|
|
|
"data_source", ds.ID, outcome,
|
|
|
|
|
map[string]any{
|
|
|
|
|
"name": ds.Name, "type": ds.Type, "sync_log_id": syncLog.ID,
|
|
|
|
|
"total": result.Total, "created": result.Created, "updated": result.Updated,
|
|
|
|
|
"deleted": result.Deleted, "skipped": result.Skipped, "failed": result.Failed,
|
|
|
|
|
})
|
2026-06-04 08:16:05 +00:00
|
|
|
}
|
2026-03-27 07:02:40 +00:00
|
|
|
|
2026-06-04 08:16:05 +00:00
|
|
|
func allFetchedItemsFailedError(result *types.SyncResult) error {
|
|
|
|
|
if result == nil || result.Total == 0 {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
if result.Failed != result.Total || result.Created != 0 || result.Updated != 0 ||
|
|
|
|
|
result.Deleted != 0 || result.Skipped != 0 {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2026-03-27 07:02:40 +00:00
|
|
|
|
2026-06-04 08:16:05 +00:00
|
|
|
detail := ""
|
|
|
|
|
if len(result.Errors) > 0 {
|
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.
2026-07-20 16:20:57 +00:00
|
|
|
detail = result.Errors[0].Display()
|
2026-06-04 08:16:05 +00:00
|
|
|
const maxDetailLen = 500
|
|
|
|
|
if len(detail) > maxDetailLen {
|
|
|
|
|
detail = detail[:maxDetailLen] + "..."
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if detail == "" {
|
|
|
|
|
return fmt.Errorf("all fetched items failed during sync (%d/%d)", result.Failed, result.Total)
|
|
|
|
|
}
|
|
|
|
|
return fmt.Errorf("all fetched items failed during sync (%d/%d): %s", result.Failed, result.Total, detail)
|
2026-03-27 07:02:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ValidateCredentials tests connectivity using raw credentials without persisting anything.
|
|
|
|
|
func (s *DataSourceService) ValidateCredentials(ctx context.Context, connectorType string, credentials map[string]interface{}) error {
|
|
|
|
|
connector, err := s.connectorRegistry.Get(connectorType)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
config := &types.DataSourceConfig{
|
|
|
|
|
Type: connectorType,
|
|
|
|
|
Credentials: credentials,
|
|
|
|
|
}
|
|
|
|
|
if err := connector.Validate(ctx, config); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Helper functions
|
|
|
|
|
|
|
|
|
|
func (s *DataSourceService) validateDataSourceConfig(ctx context.Context, ds *types.DataSource) error {
|
|
|
|
|
connector, err := s.connectorRegistry.Get(ds.Type)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
config, err := ds.ParseConfig()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return datasource.ErrInvalidConfig
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return connector.Validate(ctx, config)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ingestItem writes a single FetchedItem into the knowledge base.
|
|
|
|
|
// If a knowledge item with the same external_id already exists, it is deleted first (update = delete + re-create).
|
|
|
|
|
//
|
|
|
|
|
// Routing logic:
|
|
|
|
|
// - Has Content bytes → CreateKnowledgeFromFile (走完整的文档解析 pipeline)
|
|
|
|
|
// - Has URL only → CreateKnowledgeFromURL (让 WeKnora 下载并解析)
|
|
|
|
|
//
|
|
|
|
|
// Returns (isUpdate, error) — isUpdate is true when an existing item was replaced.
|
feat: support multi-tag for document knowledge (#1790)
* feat: support multi-tag for document knowledge
- Add knowledge_tag_relations join table for many-to-many tag-knowledge mapping
- Migrate existing single tag_id data to the new table
- Update Knowledge struct, filter, payload types (TagID -> Tags/TagIDs)
- Rewrite repository layer: SetKnowledgeTags, GetKnowledgeTags, ListIDsByTagIDs
- Update tag count references to query knowledge_tag_relations
- Update service/handler layers for multi-tag create/list/batch-update
- Frontend: multi-select tag sidebar, multi-tag chip display, tag toggle in popup
- FAQ tags remain single-tag model (unchanged)
* feat(knowledge): tag edit dialog with dynamic overflow and inline creation
- Add TagEditDialog component with search, multi-select, and confirm
- Replace inline t-popup tag selector with dialog-based editing
- Tags overflow with +N badge, visible count adapts to container width via ResizeObserver
- Date/card layout: fixed date width, tags flex to fill remaining space
- Add persistent new-tag input bar in dialog (Enter to create, auto-select)
- Tag creation emits callback to refresh parent tag list immediately
- Apply same overflow + dialog trigger to both card view and list view
- Add i18n keys: tagEditDialogTitle, tagEditSearch, tagSelectedCount, tagOverflowTip, tagNewPlaceholder
* fix: exclude soft-deleted knowledge from tag reference counts
CountReferences, BatchCountReferences, and DeleteUnusedTags now
JOIN with knowledges table to filter out soft-deleted records
when counting knowledge_tag_relations. Previously they queried
knowledge_tag_relations directly without the deleted_at check,
causing stale tag counts after knowledge deletion.
* fix: refresh tag counts after async knowledge deletion completes
Add a second delayed tag list refresh (2.5s) after tag deletion to capture
updated reference counts for remaining tags. The original immediate refresh
handles removing the deleted tag from the list, while this delayed refresh
ensures other tags' counts are correct after the async deletion finishes.
---------
Co-authored-by: lyingbug <xiayula2014@gmail.com>
2026-06-25 16:18:48 +00:00
|
|
|
func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource, item *types.FetchedItem, tagIDs []string) (bool, error) {
|
feat(feishu-driver): 新增飞书云盘数据源 (#2466)
* feat(datasource): add Feishu/Lark Drive (云盘) connector
Add a new Drive (云盘) data source alongside the existing Feishu wiki
connector, letting users sync documents/files under a user-supplied Drive
folder_token. Shares the feishu connector package (Client/Config/Region/
export/download/error-handling) with the wiki connector; only resource
enumeration and fetch dispatch differ.
Backend:
- types/datasource.go: ConnectorTypeFeishuDrive / ConnectorTypeLarkDrive
- region.go: RegionFeishuDrive / RegionLarkDrive + driveFolderURL
- types.go: driveFile / driveFileListResponse / partialDriveFileListError
/ feishuDriveCursor
- client.go: ListDriveFiles / ListDriveFilesRecursiveFrom (shortcut
expansion via shortcut_info, visited cycle guard, root-folder rejection)
- drive_connector.go: DriveConnector implementing StreamingConnector
(FetchStream) + FetchAll + FetchIncremental fallback paths, mirroring
the wiki connector's three cursor semantics (resume fast-path,
failure-does-not-advance-cursor, toSyncCursor snapshot), plus
ListResources / ResolveResourceAncestors (top-down shared traversal,
best-effort) / fetchDriveFileContent / parseDriveResourceID
- container.go + connector.go: register two Drive instances + metadata
Incremental detection uses modified_time returned directly by the list
API (verified) - no batch_query/metas call needed. Shortcuts are expanded
at list-parse time via shortcut_info; target_type is never "folder".
Frontend:
- DataSourceEditorDialog.vue: connectorDefs for feishu_drive/lark_drive,
Drive root folder_token input + load button before the lazy-load tree,
edit-mode prefill from resource_ids
- datasourceIcons.ts: reuse feishu/lark icons
- i18n (zh-CN/en-US/ko-KR/ru-RU): connector labels, descriptions, drive
input group
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(datasource): refine Feishu Drive connector UI, channel and root folder
A batch of fixes from end-to-end verification of the Feishu/Lark Drive
connector, all aimed at matching the wiki connector's behavior:
Channel (knowledge "source" label):
- Add ChannelFeishuDrive / ChannelLarkDrive constants so Drive docs show
"飞书云盘" / "Lark 云盘" instead of "unknown", distinct from the wiki
connector's "飞书" (ChannelFeishu).
- fetchDriveFileContent / appendDriveFileListFailureItems select the
channel by region via a new driveChannel() helper.
- ingestItem now prefers metadata["channel"] over ds.Type so the
connector-supplied channel value reaches the knowledge base.
- doc-content.vue channelLabelMap maps feishu_drive/lark_drive.
Frontend Drive picker UX:
- loadDriveRoot persists the new folder_token in edit mode too (previously
skipped updates in edit mode, so listResources read the old token).
- The folder_token input is now always visible alongside the tree (not a
switch); the tree area shows a "load a folder first" placeholder until
the first successful load.
- extractDriveFolderToken accepts a bare token or a Feishu Drive folder
URL (https://xxx.feishu.cn/drive/folder/<token>) and extracts the token.
- Edit mode auto-loads when a saved folder_token exists, and reveals
pre-existing selections via revealExistingSelections.
- Classify Drive list errors (403/forbidden, 401/auth, not-found) into
actionable i18n hints.
Root folder name & selection:
- Add GetDriveFolderMeta (GET /drive/explorer/v2/folder/:folderToken/meta)
to resolve the root folder's human-readable name; the list API only
returns children. Best-effort, falls back to the token.
- Fix root folder ExternalID to be the bare rootFolderToken (no ":token"
suffix) so it matches the saved resource_id form and the direct
children's ParentID, which previously broke selection matching on edit.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(datasource): sync a single selected Drive file without folder error
When a user selects a single file (not a folder) in the Drive picker, the
resourceID is "rootFolderToken:fileToken". FetchStream/FetchAll/
FetchIncremental previously passed fileToken straight to
ListDriveFilesRecursiveFrom, which expects a folder token - the Feishu
list API returns 1061002 (params error) for a file token, failing the
whole sync with "all fetched items failed".
The wiki connector resolves a single selected node via GetWikiNode; Drive
has no single-file meta API (folder meta only works on folders, and
metas/batch_query requires doc_type as input - a chicken-and-egg).
Instead, listDriveFilesForResource walks the root folder subtree (the
file's parent) and filters to the selected fileToken, yielding the full
driveFile (type/name/modified_time) needed for fetchDriveFileContent.
A sub-folder selection (fileToken is itself a folder) still walks that
sub-folder directly - ListDriveFilesRecursiveFrom accepts a folder token,
so no filtering is needed there.
Co-Authored-By: Claude <noreply@anthropic.com>
* ci: add build-test-images workflow for tar.gz artifact export
Manual-only workflow_dispatch that builds linux/amd64 Docker images for
the current branch and exports them as .tar.gz artifacts downloadable
from the Actions run page. No Docker Hub push, no secrets required.
- build-ui: builds frontend dist, builds weknora-ui image, exports tar.gz
- build-app: builds weknora-app image (CGO + duckdb), exports tar.gz
- Input choice: build both / app only / ui only
- Artifacts retained 7 days
Co-Authored-By: Claude <noreply@anthropic.com>
* ci: add build-test-images workflow for tar.gz artifact export
Manual-only workflow_dispatch that builds linux/amd64 Docker images for a
selected branch and exports them as .tar.gz artifacts downloadable from the
Actions run page. No Docker Hub push, no secrets required.
- build-ui: builds frontend dist, builds weknora-ui image, exports tar.gz
- build-app: builds weknora-app image (CGO + duckdb), exports tar.gz
- Input choice: build both / app only / ui only
- Artifacts retained 7 days
Placed on the default branch so the workflow appears in the Actions list;
trigger it with the branch you want to build (e.g. feat/datasource-feishu-drive).
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(datasource): add feishu shared-blocks extraction design spec
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(datasource): add feishu shared-blocks implementation plan
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(datasource): sync feishu drive docx via blocks API with export fallback
- Extract wiki/drive shared helpers from connector.go into shared.go
- Make fetchDocxWithBlocks a package-level function taking docxFetchInput
- Drive docx now renders via blocks API (Markdown + attachment/image
sub-items), falling back to the export API on blocks errors or empty
renders, mirroring the wiki connector
- fetchDriveFileContent returns item slices and takes multimodalEnabled
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(frontend): label feishu drive knowledge as 飞书云盘 in list
The knowledge list source column (DocumentListView.getSourceInfo) only
whitelisted feishu/notion/yuque/etc., so feishu_drive/lark_drive docs
fell through to the default "上传" label while the wiki connector's
"feishu" showed "飞书". Map feishu_drive → 飞书云盘 and lark_drive →
Lark 云盘 (i18n keys already existed), and add feishu_drive to the
source filter options in KnowledgeBase.vue.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(frontend): polish feishu drive resource-step UI in datasource editor
- Replace the two stacked t-alert banners under the folder_token input:
shareHint becomes an always-visible form-desc line, rootNotSupportedHint
moves into a help-circle tooltip next to the label.
- folder_token is now required: red asterisk on the label, inline error
status + tips on the input (replacing the global MessagePlugin) when
empty on 加载/下一步, cleared on input.
- Step 2 选择范围 no longer scrolls as a whole: the token input stays
fixed and the resource region (placeholder / loading / empty / tree)
fills the remaining drawer height, with the tree scrolling internally.
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(datasource): add feishu drive datasource integration guide
User-facing setup guide for feishu_drive/lark_drive: app creation,
required scopes (drive:drive:readonly / drive:export:readonly /
docx:document:readonly), sharing the folder to the app's group, the
four-step wizard, supported file types, sync semantics and FAQ.
Also clarify in extractDriveFolderToken's comment that pasted folder
URLs are matched by path and work for Lark links too.
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor(datasource): unify feishu wiki/drive sync into a single generic streaming engine
Extract a single generic streaming sync engine (engine.go) shared by the wiki Connector and the Drive DriveConnector. Per-connector differences (node type, listing API, edit-time field, cursor wire format, fetch dispatch, log tag) are isolated behind the NodeOps[N] adapter; FetchAll/FetchIncremental become thin shells over the same engine.
Deliberate behaviour changes (design §2.4): the #2136 failure-doesn't-advance-cursor fix now applies to FetchIncremental too (previously it advanced the cursor before fetching, permanently skipping a node on a transient export failure); logs use 'stream progress/summary' uniformly and the FetchIncremental path gains per-100 progress + tally summary logs.
Structural prep for package split (design §3.1): anonymous Data structs in types.go/blocks.go are named so tests can construct wire types across packages.
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor(datasource): split feishu connector into core/wiki/drive packages
Move shared code (Client, blocks, markdown, types, region, engine, shared helpers) into feishu/core; wiki and drive connectors into their own packages. Export core symbols (capitalize) so wiki/drive can reference them; wiki/drive import core and prefix cross-package references.
container.go registration updated to import core/wiki/drive (NewConnector from wiki, NewDriveConnector from drive, Region* from core).
Tests are NOT migrated yet (left in feishu/ root, package feishu) and will fail to compile until moved + adapted in a follow-up commit. Source builds clean (go build ./...feishu/... passes).
Co-Authored-By: Claude <noreply@anthropic.com>
* test(datasource): migrate feishu tests to core/wiki/drive packages
Move 14 test files to their subpackages per design §4. Adapt package declarations, imports, and capitalized core symbol references. Add TestMain (SSRF whitelist) to core and drive. Add local helpers (writeJSON, makeConfig, txt, blk constructors, recordingHandler) where cross-package sharing was not possible. Fix engine.go log wording (summary) clobbered by the capitalization script.
All tests pass: core 4s, wiki 13s, drive 3s.
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor(datasource): reduce feishu core export surface; add drive cursor round-trip test
Lower-case 87 core symbols that are not referenced cross-package back to unexported (BlocksToMarkdown, CellToString, response types, BlockType constants, etc.), shrinking core's API surface to only what wiki/drive actually use. Restore NodeOps.Fetch capitalization (interface method must match wikiOps/driveOps implementations).
Add TestDriveCursorRoundTrip (design §3.2): driveOps.EncodeCursor/DecodeCursorTimes were new code with no direct test.
All tests pass: core 3.5s, wiki 13s, drive 3s.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(datasource): repair feishu cleanup fallout
Restore core.RegionLarkDrive (cleanup lower-cased it; only container.go references it, outside wiki/drive scan). Restore wiki/connector_realapi_test.go local collectHandler type (cleanup wrongly prefixed core.). Apply gofumpt to helpers_test.go. Add open.feishu.cn/open.larksuite.com to test SSRF whitelist: BaseURL-default tests call ParseFeishuConfig which SSRF-validates the resolved hostname; under a proxy open.feishu.cn resolves to 198.18.0.0/15 restricted range.
All tests pass: core 3.2s, wiki 13s, drive 2.6s. make build-lite passes.
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(frontend): feishu drive data source UI and i18n
Add Drive folder/token picker strings and data source editor entries for the feishu_drive/lark_drive connectors across en-US/zh-CN/ko-KR/ru-RU.
Co-Authored-By: Claude <noreply@anthropic.com>
* chore: add trellis journal merge=union rule
Append-only developer journals merge cleanly across parallel sessions; task state lives in task.json, not the journal.
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor(datasource): rename feishu/drive drive_connector.go to connector.go
Aligns naming with feishu/wiki subpackage (connector.go).
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(frontend): allow data:image base64 URIs in sanitized markdown
DOMPurify's ALLOWED_URI_REGEXP rejected data: URIs, so <img src="data:image/...">
in uploaded markdown files had their src stripped during sanitizeHTML — the file
preview showed broken images while the chunk view (minio:// via
hydrateProtectedFileImages) worked. Add data:image/ to the allowed URI scheme so
base64 images render in preview and in LLM answers that embed base64 images.
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(datasource): add FEISHU_DOCX_PARSE_MODE for feishu docx parse path
The blocks API path renders image blocks as empty ![图片]() placeholders and
fans images into separate knowledge items, breaking image↔document association
across retrieval/wiki/agent. FEISHU_DOCX_PARSE_MODE=export forces the async
export API (.docx binary -> docreader), so images are parsed inline and bound to
the parent document via parent_chunk_id (same as a regular docx upload). Default
(unset / "blocks") keeps the existing blocks-first behaviour. Affects both wiki
and drive connectors since they share FetchDocxWithBlocks.
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(datasource): default FEISHU_DOCX_PARSE_MODE to export
Switch the feishu docx parse default from blocks to export so embedded
images are parsed inline and bound to the parent document via
parent_chunk_id (retrieval / wiki / agent all associate images). Operators
who need the blocks behaviour (faster, keeps docx attachments, no
docreader round-trip) set FEISHU_DOCX_PARSE_MODE=blocks.
- shared.go: default unset -> export; update comment to match
- .env.example / docker-compose.yml: default export
- tests: pin FEISHU_DOCX_PARSE_MODE=blocks on blocks-behaviour tests so
they don't break under the new default
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(datasource): document FEISHU_DOCX_PARSE_MODE and refresh feishu source layout
- 飞书云盘接入说明: add section on docx parse mode (export default vs
blocks), permission differences, export tradeoffs
- 数据源导入开发: add env var + mode comparison
- 数据源导入开发文档: rewrite content fetch flow (blocks/export paths),
add pros/cons table, fix source-file table to core/wiki/drive layout
Co-Authored-By: Claude <noreply@anthropic.com>
* fix: 修复合并main后丢失新增的国际化问题
* fix(i18n): 修复误删的国际化内容
* docs: 删除误提交的文件
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-08-05 11:39:49 +00:00
|
|
|
// Channel decides the knowledge "source" label shown in the UI. Prefer the
|
|
|
|
|
// connector-supplied metadata["channel"] (e.g. Feishu Drive sets it to
|
|
|
|
|
// "feishu" so Drive docs share the wiki's "飞书" label instead of showing
|
|
|
|
|
// "unknown" for the raw ds.Type "feishu_drive"). Fall back to ds.Type so
|
|
|
|
|
// connectors that don't set metadata.channel still get a meaningful label.
|
2026-03-27 07:02:40 +00:00
|
|
|
channel := ds.Type // e.g. "feishu", "notion"
|
feat(feishu-driver): 新增飞书云盘数据源 (#2466)
* feat(datasource): add Feishu/Lark Drive (云盘) connector
Add a new Drive (云盘) data source alongside the existing Feishu wiki
connector, letting users sync documents/files under a user-supplied Drive
folder_token. Shares the feishu connector package (Client/Config/Region/
export/download/error-handling) with the wiki connector; only resource
enumeration and fetch dispatch differ.
Backend:
- types/datasource.go: ConnectorTypeFeishuDrive / ConnectorTypeLarkDrive
- region.go: RegionFeishuDrive / RegionLarkDrive + driveFolderURL
- types.go: driveFile / driveFileListResponse / partialDriveFileListError
/ feishuDriveCursor
- client.go: ListDriveFiles / ListDriveFilesRecursiveFrom (shortcut
expansion via shortcut_info, visited cycle guard, root-folder rejection)
- drive_connector.go: DriveConnector implementing StreamingConnector
(FetchStream) + FetchAll + FetchIncremental fallback paths, mirroring
the wiki connector's three cursor semantics (resume fast-path,
failure-does-not-advance-cursor, toSyncCursor snapshot), plus
ListResources / ResolveResourceAncestors (top-down shared traversal,
best-effort) / fetchDriveFileContent / parseDriveResourceID
- container.go + connector.go: register two Drive instances + metadata
Incremental detection uses modified_time returned directly by the list
API (verified) - no batch_query/metas call needed. Shortcuts are expanded
at list-parse time via shortcut_info; target_type is never "folder".
Frontend:
- DataSourceEditorDialog.vue: connectorDefs for feishu_drive/lark_drive,
Drive root folder_token input + load button before the lazy-load tree,
edit-mode prefill from resource_ids
- datasourceIcons.ts: reuse feishu/lark icons
- i18n (zh-CN/en-US/ko-KR/ru-RU): connector labels, descriptions, drive
input group
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(datasource): refine Feishu Drive connector UI, channel and root folder
A batch of fixes from end-to-end verification of the Feishu/Lark Drive
connector, all aimed at matching the wiki connector's behavior:
Channel (knowledge "source" label):
- Add ChannelFeishuDrive / ChannelLarkDrive constants so Drive docs show
"飞书云盘" / "Lark 云盘" instead of "unknown", distinct from the wiki
connector's "飞书" (ChannelFeishu).
- fetchDriveFileContent / appendDriveFileListFailureItems select the
channel by region via a new driveChannel() helper.
- ingestItem now prefers metadata["channel"] over ds.Type so the
connector-supplied channel value reaches the knowledge base.
- doc-content.vue channelLabelMap maps feishu_drive/lark_drive.
Frontend Drive picker UX:
- loadDriveRoot persists the new folder_token in edit mode too (previously
skipped updates in edit mode, so listResources read the old token).
- The folder_token input is now always visible alongside the tree (not a
switch); the tree area shows a "load a folder first" placeholder until
the first successful load.
- extractDriveFolderToken accepts a bare token or a Feishu Drive folder
URL (https://xxx.feishu.cn/drive/folder/<token>) and extracts the token.
- Edit mode auto-loads when a saved folder_token exists, and reveals
pre-existing selections via revealExistingSelections.
- Classify Drive list errors (403/forbidden, 401/auth, not-found) into
actionable i18n hints.
Root folder name & selection:
- Add GetDriveFolderMeta (GET /drive/explorer/v2/folder/:folderToken/meta)
to resolve the root folder's human-readable name; the list API only
returns children. Best-effort, falls back to the token.
- Fix root folder ExternalID to be the bare rootFolderToken (no ":token"
suffix) so it matches the saved resource_id form and the direct
children's ParentID, which previously broke selection matching on edit.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(datasource): sync a single selected Drive file without folder error
When a user selects a single file (not a folder) in the Drive picker, the
resourceID is "rootFolderToken:fileToken". FetchStream/FetchAll/
FetchIncremental previously passed fileToken straight to
ListDriveFilesRecursiveFrom, which expects a folder token - the Feishu
list API returns 1061002 (params error) for a file token, failing the
whole sync with "all fetched items failed".
The wiki connector resolves a single selected node via GetWikiNode; Drive
has no single-file meta API (folder meta only works on folders, and
metas/batch_query requires doc_type as input - a chicken-and-egg).
Instead, listDriveFilesForResource walks the root folder subtree (the
file's parent) and filters to the selected fileToken, yielding the full
driveFile (type/name/modified_time) needed for fetchDriveFileContent.
A sub-folder selection (fileToken is itself a folder) still walks that
sub-folder directly - ListDriveFilesRecursiveFrom accepts a folder token,
so no filtering is needed there.
Co-Authored-By: Claude <noreply@anthropic.com>
* ci: add build-test-images workflow for tar.gz artifact export
Manual-only workflow_dispatch that builds linux/amd64 Docker images for
the current branch and exports them as .tar.gz artifacts downloadable
from the Actions run page. No Docker Hub push, no secrets required.
- build-ui: builds frontend dist, builds weknora-ui image, exports tar.gz
- build-app: builds weknora-app image (CGO + duckdb), exports tar.gz
- Input choice: build both / app only / ui only
- Artifacts retained 7 days
Co-Authored-By: Claude <noreply@anthropic.com>
* ci: add build-test-images workflow for tar.gz artifact export
Manual-only workflow_dispatch that builds linux/amd64 Docker images for a
selected branch and exports them as .tar.gz artifacts downloadable from the
Actions run page. No Docker Hub push, no secrets required.
- build-ui: builds frontend dist, builds weknora-ui image, exports tar.gz
- build-app: builds weknora-app image (CGO + duckdb), exports tar.gz
- Input choice: build both / app only / ui only
- Artifacts retained 7 days
Placed on the default branch so the workflow appears in the Actions list;
trigger it with the branch you want to build (e.g. feat/datasource-feishu-drive).
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(datasource): add feishu shared-blocks extraction design spec
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(datasource): add feishu shared-blocks implementation plan
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(datasource): sync feishu drive docx via blocks API with export fallback
- Extract wiki/drive shared helpers from connector.go into shared.go
- Make fetchDocxWithBlocks a package-level function taking docxFetchInput
- Drive docx now renders via blocks API (Markdown + attachment/image
sub-items), falling back to the export API on blocks errors or empty
renders, mirroring the wiki connector
- fetchDriveFileContent returns item slices and takes multimodalEnabled
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(frontend): label feishu drive knowledge as 飞书云盘 in list
The knowledge list source column (DocumentListView.getSourceInfo) only
whitelisted feishu/notion/yuque/etc., so feishu_drive/lark_drive docs
fell through to the default "上传" label while the wiki connector's
"feishu" showed "飞书". Map feishu_drive → 飞书云盘 and lark_drive →
Lark 云盘 (i18n keys already existed), and add feishu_drive to the
source filter options in KnowledgeBase.vue.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(frontend): polish feishu drive resource-step UI in datasource editor
- Replace the two stacked t-alert banners under the folder_token input:
shareHint becomes an always-visible form-desc line, rootNotSupportedHint
moves into a help-circle tooltip next to the label.
- folder_token is now required: red asterisk on the label, inline error
status + tips on the input (replacing the global MessagePlugin) when
empty on 加载/下一步, cleared on input.
- Step 2 选择范围 no longer scrolls as a whole: the token input stays
fixed and the resource region (placeholder / loading / empty / tree)
fills the remaining drawer height, with the tree scrolling internally.
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(datasource): add feishu drive datasource integration guide
User-facing setup guide for feishu_drive/lark_drive: app creation,
required scopes (drive:drive:readonly / drive:export:readonly /
docx:document:readonly), sharing the folder to the app's group, the
four-step wizard, supported file types, sync semantics and FAQ.
Also clarify in extractDriveFolderToken's comment that pasted folder
URLs are matched by path and work for Lark links too.
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor(datasource): unify feishu wiki/drive sync into a single generic streaming engine
Extract a single generic streaming sync engine (engine.go) shared by the wiki Connector and the Drive DriveConnector. Per-connector differences (node type, listing API, edit-time field, cursor wire format, fetch dispatch, log tag) are isolated behind the NodeOps[N] adapter; FetchAll/FetchIncremental become thin shells over the same engine.
Deliberate behaviour changes (design §2.4): the #2136 failure-doesn't-advance-cursor fix now applies to FetchIncremental too (previously it advanced the cursor before fetching, permanently skipping a node on a transient export failure); logs use 'stream progress/summary' uniformly and the FetchIncremental path gains per-100 progress + tally summary logs.
Structural prep for package split (design §3.1): anonymous Data structs in types.go/blocks.go are named so tests can construct wire types across packages.
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor(datasource): split feishu connector into core/wiki/drive packages
Move shared code (Client, blocks, markdown, types, region, engine, shared helpers) into feishu/core; wiki and drive connectors into their own packages. Export core symbols (capitalize) so wiki/drive can reference them; wiki/drive import core and prefix cross-package references.
container.go registration updated to import core/wiki/drive (NewConnector from wiki, NewDriveConnector from drive, Region* from core).
Tests are NOT migrated yet (left in feishu/ root, package feishu) and will fail to compile until moved + adapted in a follow-up commit. Source builds clean (go build ./...feishu/... passes).
Co-Authored-By: Claude <noreply@anthropic.com>
* test(datasource): migrate feishu tests to core/wiki/drive packages
Move 14 test files to their subpackages per design §4. Adapt package declarations, imports, and capitalized core symbol references. Add TestMain (SSRF whitelist) to core and drive. Add local helpers (writeJSON, makeConfig, txt, blk constructors, recordingHandler) where cross-package sharing was not possible. Fix engine.go log wording (summary) clobbered by the capitalization script.
All tests pass: core 4s, wiki 13s, drive 3s.
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor(datasource): reduce feishu core export surface; add drive cursor round-trip test
Lower-case 87 core symbols that are not referenced cross-package back to unexported (BlocksToMarkdown, CellToString, response types, BlockType constants, etc.), shrinking core's API surface to only what wiki/drive actually use. Restore NodeOps.Fetch capitalization (interface method must match wikiOps/driveOps implementations).
Add TestDriveCursorRoundTrip (design §3.2): driveOps.EncodeCursor/DecodeCursorTimes were new code with no direct test.
All tests pass: core 3.5s, wiki 13s, drive 3s.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(datasource): repair feishu cleanup fallout
Restore core.RegionLarkDrive (cleanup lower-cased it; only container.go references it, outside wiki/drive scan). Restore wiki/connector_realapi_test.go local collectHandler type (cleanup wrongly prefixed core.). Apply gofumpt to helpers_test.go. Add open.feishu.cn/open.larksuite.com to test SSRF whitelist: BaseURL-default tests call ParseFeishuConfig which SSRF-validates the resolved hostname; under a proxy open.feishu.cn resolves to 198.18.0.0/15 restricted range.
All tests pass: core 3.2s, wiki 13s, drive 2.6s. make build-lite passes.
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(frontend): feishu drive data source UI and i18n
Add Drive folder/token picker strings and data source editor entries for the feishu_drive/lark_drive connectors across en-US/zh-CN/ko-KR/ru-RU.
Co-Authored-By: Claude <noreply@anthropic.com>
* chore: add trellis journal merge=union rule
Append-only developer journals merge cleanly across parallel sessions; task state lives in task.json, not the journal.
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor(datasource): rename feishu/drive drive_connector.go to connector.go
Aligns naming with feishu/wiki subpackage (connector.go).
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(frontend): allow data:image base64 URIs in sanitized markdown
DOMPurify's ALLOWED_URI_REGEXP rejected data: URIs, so <img src="data:image/...">
in uploaded markdown files had their src stripped during sanitizeHTML — the file
preview showed broken images while the chunk view (minio:// via
hydrateProtectedFileImages) worked. Add data:image/ to the allowed URI scheme so
base64 images render in preview and in LLM answers that embed base64 images.
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(datasource): add FEISHU_DOCX_PARSE_MODE for feishu docx parse path
The blocks API path renders image blocks as empty ![图片]() placeholders and
fans images into separate knowledge items, breaking image↔document association
across retrieval/wiki/agent. FEISHU_DOCX_PARSE_MODE=export forces the async
export API (.docx binary -> docreader), so images are parsed inline and bound to
the parent document via parent_chunk_id (same as a regular docx upload). Default
(unset / "blocks") keeps the existing blocks-first behaviour. Affects both wiki
and drive connectors since they share FetchDocxWithBlocks.
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(datasource): default FEISHU_DOCX_PARSE_MODE to export
Switch the feishu docx parse default from blocks to export so embedded
images are parsed inline and bound to the parent document via
parent_chunk_id (retrieval / wiki / agent all associate images). Operators
who need the blocks behaviour (faster, keeps docx attachments, no
docreader round-trip) set FEISHU_DOCX_PARSE_MODE=blocks.
- shared.go: default unset -> export; update comment to match
- .env.example / docker-compose.yml: default export
- tests: pin FEISHU_DOCX_PARSE_MODE=blocks on blocks-behaviour tests so
they don't break under the new default
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(datasource): document FEISHU_DOCX_PARSE_MODE and refresh feishu source layout
- 飞书云盘接入说明: add section on docx parse mode (export default vs
blocks), permission differences, export tradeoffs
- 数据源导入开发: add env var + mode comparison
- 数据源导入开发文档: rewrite content fetch flow (blocks/export paths),
add pros/cons table, fix source-file table to core/wiki/drive layout
Co-Authored-By: Claude <noreply@anthropic.com>
* fix: 修复合并main后丢失新增的国际化问题
* fix(i18n): 修复误删的国际化内容
* docs: 删除误提交的文件
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-08-05 11:39:49 +00:00
|
|
|
if item.Metadata != nil {
|
|
|
|
|
if mc, ok := item.Metadata["channel"]; ok && mc != "" {
|
|
|
|
|
channel = mc
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-03-27 07:02:40 +00:00
|
|
|
|
|
|
|
|
metadata := map[string]string{
|
|
|
|
|
"external_id": item.ExternalID,
|
|
|
|
|
"source_resource_id": item.SourceResourceID,
|
|
|
|
|
"datasource_id": ds.ID,
|
|
|
|
|
}
|
|
|
|
|
for k, v := range item.Metadata {
|
|
|
|
|
metadata[k] = v
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if a knowledge item with this external_id already exists → delete it first (update)
|
|
|
|
|
isUpdate := false
|
|
|
|
|
if item.ExternalID != "" {
|
|
|
|
|
repo := s.knowledgeService.GetRepository()
|
2026-08-13 11:52:44 +00:00
|
|
|
// Scope the lookup to items owned by this data source so identical
|
|
|
|
|
// external IDs from two data sources cannot collide or overwrite each
|
|
|
|
|
// other during updates.
|
|
|
|
|
existing, err := repo.FindByDataSourceExternalID(ctx, ds.TenantID, ds.KnowledgeBaseID, ds.ID, item.ExternalID)
|
2026-03-27 07:02:40 +00:00
|
|
|
if err != nil {
|
|
|
|
|
logger.Warnf(ctx, "failed to check existing knowledge for external_id=%s: %v", item.ExternalID, err)
|
|
|
|
|
// Non-fatal: proceed with creation (may produce duplicate)
|
|
|
|
|
} else if existing != nil {
|
|
|
|
|
logger.Infof(ctx, "found existing knowledge %s for external_id=%s, deleting for update", existing.ID, item.ExternalID)
|
|
|
|
|
if err := s.knowledgeService.DeleteKnowledge(ctx, existing.ID); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "failed to delete existing knowledge %s: %v", existing.ID, err)
|
|
|
|
|
} else {
|
2026-08-13 11:52:44 +00:00
|
|
|
if herr := repo.HardDeleteKnowledge(ctx, ds.TenantID, existing.ID); herr != nil {
|
|
|
|
|
logger.Warnf(ctx, "failed to hard-delete replaced knowledge %s: %v", existing.ID, herr)
|
|
|
|
|
}
|
2026-03-27 07:02:40 +00:00
|
|
|
isUpdate = true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Case 1: content already fetched → build a FileHeader from bytes and call CreateKnowledgeFromFile
|
|
|
|
|
if len(item.Content) > 0 {
|
|
|
|
|
fh, err := bytesToFileHeader(item.Content, item.FileName)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return isUpdate, fmt.Errorf("build file header: %w", err)
|
|
|
|
|
}
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
if _, err := s.knowledgeService.CreateKnowledgeFromFile(
|
2026-03-27 07:02:40 +00:00
|
|
|
ctx,
|
|
|
|
|
ds.KnowledgeBaseID,
|
|
|
|
|
fh,
|
|
|
|
|
metadata,
|
|
|
|
|
nil, // use KB default for multimodal
|
|
|
|
|
item.FileName, // customFileName — must include extension for file-type validation
|
feat: support multi-tag for document knowledge (#1790)
* feat: support multi-tag for document knowledge
- Add knowledge_tag_relations join table for many-to-many tag-knowledge mapping
- Migrate existing single tag_id data to the new table
- Update Knowledge struct, filter, payload types (TagID -> Tags/TagIDs)
- Rewrite repository layer: SetKnowledgeTags, GetKnowledgeTags, ListIDsByTagIDs
- Update tag count references to query knowledge_tag_relations
- Update service/handler layers for multi-tag create/list/batch-update
- Frontend: multi-select tag sidebar, multi-tag chip display, tag toggle in popup
- FAQ tags remain single-tag model (unchanged)
* feat(knowledge): tag edit dialog with dynamic overflow and inline creation
- Add TagEditDialog component with search, multi-select, and confirm
- Replace inline t-popup tag selector with dialog-based editing
- Tags overflow with +N badge, visible count adapts to container width via ResizeObserver
- Date/card layout: fixed date width, tags flex to fill remaining space
- Add persistent new-tag input bar in dialog (Enter to create, auto-select)
- Tag creation emits callback to refresh parent tag list immediately
- Apply same overflow + dialog trigger to both card view and list view
- Add i18n keys: tagEditDialogTitle, tagEditSearch, tagSelectedCount, tagOverflowTip, tagNewPlaceholder
* fix: exclude soft-deleted knowledge from tag reference counts
CountReferences, BatchCountReferences, and DeleteUnusedTags now
JOIN with knowledges table to filter out soft-deleted records
when counting knowledge_tag_relations. Previously they queried
knowledge_tag_relations directly without the deleted_at check,
causing stale tag counts after knowledge deletion.
* fix: refresh tag counts after async knowledge deletion completes
Add a second delayed tag list refresh (2.5s) after tag deletion to capture
updated reference counts for remaining tags. The original immediate refresh
handles removing the deleted tag from the list, while this delayed refresh
ensures other tags' counts are correct after the async deletion finishes.
---------
Co-authored-by: lyingbug <xiayula2014@gmail.com>
2026-06-25 16:18:48 +00:00
|
|
|
tagIDs, // auto-tag from data source
|
2026-03-27 07:02:40 +00:00
|
|
|
channel,
|
2026-06-09 09:49:39 +00:00
|
|
|
nil,
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
); err != nil {
|
|
|
|
|
var dupErr *types.DuplicateKnowledgeError
|
|
|
|
|
if errors.As(err, &dupErr) && dupIsSameNode(dupErr, item) {
|
|
|
|
|
// Identical content is already present in the KB under THIS node's
|
|
|
|
|
// own external_id, so the parent effectively exists — reconcile the
|
|
|
|
|
// subtree so children removed from the doc do not linger.
|
|
|
|
|
s.sweepStaleSubtree(ctx, ds, item)
|
|
|
|
|
}
|
|
|
|
|
return isUpdate, err
|
|
|
|
|
}
|
|
|
|
|
s.sweepStaleSubtree(ctx, ds, item)
|
|
|
|
|
return isUpdate, nil
|
2026-03-27 07:02:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Case 2: only a remote URL — let WeKnora handle downloading and parsing
|
|
|
|
|
if item.URL != "" {
|
2026-08-13 11:52:44 +00:00
|
|
|
created, err := s.knowledgeService.CreateKnowledgeFromURL(
|
2026-03-27 07:02:40 +00:00
|
|
|
ctx,
|
|
|
|
|
ds.KnowledgeBaseID,
|
|
|
|
|
item.URL,
|
|
|
|
|
item.FileName,
|
|
|
|
|
"", // auto-detect file type
|
|
|
|
|
nil, // use KB default for multimodal
|
|
|
|
|
item.Title,
|
feat: support multi-tag for document knowledge (#1790)
* feat: support multi-tag for document knowledge
- Add knowledge_tag_relations join table for many-to-many tag-knowledge mapping
- Migrate existing single tag_id data to the new table
- Update Knowledge struct, filter, payload types (TagID -> Tags/TagIDs)
- Rewrite repository layer: SetKnowledgeTags, GetKnowledgeTags, ListIDsByTagIDs
- Update tag count references to query knowledge_tag_relations
- Update service/handler layers for multi-tag create/list/batch-update
- Frontend: multi-select tag sidebar, multi-tag chip display, tag toggle in popup
- FAQ tags remain single-tag model (unchanged)
* feat(knowledge): tag edit dialog with dynamic overflow and inline creation
- Add TagEditDialog component with search, multi-select, and confirm
- Replace inline t-popup tag selector with dialog-based editing
- Tags overflow with +N badge, visible count adapts to container width via ResizeObserver
- Date/card layout: fixed date width, tags flex to fill remaining space
- Add persistent new-tag input bar in dialog (Enter to create, auto-select)
- Tag creation emits callback to refresh parent tag list immediately
- Apply same overflow + dialog trigger to both card view and list view
- Add i18n keys: tagEditDialogTitle, tagEditSearch, tagSelectedCount, tagOverflowTip, tagNewPlaceholder
* fix: exclude soft-deleted knowledge from tag reference counts
CountReferences, BatchCountReferences, and DeleteUnusedTags now
JOIN with knowledges table to filter out soft-deleted records
when counting knowledge_tag_relations. Previously they queried
knowledge_tag_relations directly without the deleted_at check,
causing stale tag counts after knowledge deletion.
* fix: refresh tag counts after async knowledge deletion completes
Add a second delayed tag list refresh (2.5s) after tag deletion to capture
updated reference counts for remaining tags. The original immediate refresh
handles removing the deleted tag from the list, while this delayed refresh
ensures other tags' counts are correct after the async deletion finishes.
---------
Co-authored-by: lyingbug <xiayula2014@gmail.com>
2026-06-25 16:18:48 +00:00
|
|
|
tagIDs, // auto-tag from data source
|
2026-03-27 07:02:40 +00:00
|
|
|
channel,
|
2026-06-09 09:49:39 +00:00
|
|
|
nil,
|
2026-08-13 11:52:44 +00:00
|
|
|
)
|
|
|
|
|
if err != nil {
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
var dupErr *types.DuplicateKnowledgeError
|
|
|
|
|
if errors.As(err, &dupErr) && dupIsSameNode(dupErr, item) {
|
|
|
|
|
// Identical content is already present in the KB under THIS node's
|
|
|
|
|
// own external_id, so the parent effectively exists — reconcile the
|
|
|
|
|
// subtree so children removed from the doc do not linger.
|
|
|
|
|
s.sweepStaleSubtree(ctx, ds, item)
|
|
|
|
|
}
|
|
|
|
|
return isUpdate, err
|
|
|
|
|
}
|
2026-08-13 11:52:44 +00:00
|
|
|
// URL-created knowledge has no metadata, so a later deletion could
|
|
|
|
|
// never find it. Attach the datasource keys on fresh creation only;
|
|
|
|
|
// the duplicate path reuses an existing row that must not be re-tagged.
|
|
|
|
|
if created != nil {
|
|
|
|
|
metadataBytes, mErr := json.Marshal(metadata)
|
|
|
|
|
if mErr != nil {
|
|
|
|
|
return isUpdate, fmt.Errorf("marshal datasource metadata: %w", mErr)
|
|
|
|
|
}
|
|
|
|
|
created.Metadata = types.JSON(metadataBytes)
|
|
|
|
|
if uErr := s.knowledgeService.GetRepository().UpdateKnowledge(ctx, created); uErr != nil {
|
|
|
|
|
return isUpdate, fmt.Errorf("attach datasource metadata: %w", uErr)
|
|
|
|
|
}
|
|
|
|
|
}
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
s.sweepStaleSubtree(ctx, ds, item)
|
|
|
|
|
return isUpdate, nil
|
2026-03-27 07:02:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return isUpdate, fmt.Errorf("item has neither content nor URL")
|
|
|
|
|
}
|
|
|
|
|
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
// dupIsSameNode reports whether a duplicate-content error means the parent still
|
|
|
|
|
// exists in the KB *under this item's own external_id* — i.e. a content-dedup hit
|
2026-07-29 02:35:21 +00:00
|
|
|
// against this same node, so reconciling its subtree is safe. File deduplication
|
|
|
|
|
// keys on file_hash plus file_type (CheckKnowledgeExists), so an updated node whose rebuilt body
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
// happens to hash-collide with a DIFFERENT knowledge item (another node, or a
|
|
|
|
|
// manually-uploaded file with no external_id) would otherwise sweep this node's
|
|
|
|
|
// children even though its own parent row was just deleted for the update and
|
|
|
|
|
// never recreated — deleting those children with no parent to replace them. In
|
|
|
|
|
// that case the matched row's external_id differs (or is absent), so we skip the
|
|
|
|
|
// sweep and leave the children intact.
|
|
|
|
|
func dupIsSameNode(dupErr *types.DuplicateKnowledgeError, item *types.FetchedItem) bool {
|
|
|
|
|
return dupErr != nil && dupErr.Knowledge != nil &&
|
|
|
|
|
dupErr.Knowledge.GetMetadata()["external_id"] == item.ExternalID
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// sweepStaleSubtree deletes STALE sub-items of item — knowledge whose external_id
|
|
|
|
|
// is prefixed with "<item.ExternalID>#" (e.g. attachment children of a docx node)
|
|
|
|
|
// that is NOT listed in item.SubtreeKeep, i.e. no longer present in the source.
|
|
|
|
|
//
|
|
|
|
|
// It runs only AFTER the parent item exists in the KB (freshly (re)created, or
|
|
|
|
|
// confirmed present via a duplicate-hash error), so a genuinely failed parent
|
|
|
|
|
// write never destroys existing children. Children still present in the source
|
|
|
|
|
// are preserved via SubtreeKeep even when they could not be re-ingested this
|
|
|
|
|
// cycle (e.g. a transient attachment download failure), so a still-present
|
|
|
|
|
// attachment never loses its previously-synced good copy. The "<id>#" prefix
|
|
|
|
|
// never matches the parent's own "<id>" external_id, so the parent is never
|
|
|
|
|
// self-swept.
|
|
|
|
|
func (s *DataSourceService) sweepStaleSubtree(ctx context.Context, ds *types.DataSource, item *types.FetchedItem) {
|
|
|
|
|
if !item.ReplacesSubtree || item.ExternalID == "" {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
repo := s.knowledgeService.GetRepository()
|
|
|
|
|
children, err := repo.FindByMetadataKeyPrefix(ctx, ds.TenantID, ds.KnowledgeBaseID, "external_id", types.SubtreeChildPrefix(item.ExternalID))
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Warnf(ctx, "failed to list subtree of external_id=%s: %v", item.ExternalID, err)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if len(children) == 0 {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
ids := make([]string, 0, len(children))
|
|
|
|
|
for _, child := range children {
|
2026-08-13 11:52:44 +00:00
|
|
|
// Scope to this data source so identical external_id prefixes from
|
|
|
|
|
// another connector in the same KB cannot be swept.
|
|
|
|
|
if child.GetMetadata()["datasource_id"] != ds.ID {
|
|
|
|
|
continue
|
|
|
|
|
}
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
// A child still present in the source is preserved even if it could not be
|
|
|
|
|
// re-ingested this sync; only children that vanished from the source are
|
|
|
|
|
// stale and swept. Every child here was selected by the external_id-prefix
|
|
|
|
|
// query, so its external_id is guaranteed present and readable (a malformed
|
|
|
|
|
// row could not have matched the SQL predicate), and GetMetadata resolves
|
|
|
|
|
// it identically to the keep-set entries the connector built. SubtreeKeep
|
|
|
|
|
// holds one entry per still-present sub-item of this node (a small set), so
|
|
|
|
|
// a linear scan is cheaper than materializing a lookup map.
|
|
|
|
|
if slices.Contains(item.SubtreeKeep, child.GetMetadata()["external_id"]) {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
ids = append(ids, child.ID)
|
|
|
|
|
}
|
|
|
|
|
if len(ids) == 0 {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
// Batch the deletion so a node whose attachment set shrank from N pays one
|
|
|
|
|
// round of the delete fan-out rather than N sequential ones.
|
|
|
|
|
if derr := s.knowledgeService.DeleteKnowledgeList(ctx, ids); derr != nil {
|
|
|
|
|
logger.Warnf(ctx, "failed to delete %d stale sub-item(s) of external_id=%s: %v",
|
|
|
|
|
len(ids), item.ExternalID, derr)
|
2026-08-13 11:52:44 +00:00
|
|
|
} else if herr := repo.HardDeleteKnowledgeList(ctx, ds.TenantID, ids); herr != nil {
|
|
|
|
|
logger.Warnf(ctx, "failed to hard-delete %d stale sub-item(s) of external_id=%s: %v",
|
|
|
|
|
len(ids), item.ExternalID, herr)
|
feat(feishu): sync docx via blocks API with per-type downdrill (#2087)
Rework the Feishu datasource connector from whole-document export to the docx
blocks API, so embedded content that export silently dropped is now ingested,
and add the multi-item ingestion infrastructure it needs.
Feishu connector:
- Embedded online sheets and bitables are read via their APIs and inlined as
Markdown tables — searchable text, instead of being lost or (post-export)
rendered as unsearchable images. Bitable date/datetime cells render in the
table's timezone (configurable via Settings["timezone"], default GMT+8) rather
than a raw epoch-ms integer; a datetime formatter keeps the time component.
- Uploaded attachments (>2KB, parseable types) become standalone knowledge
sub-items so their text is parsed and retrievable.
- Embedded images become standalone sub-items routed through the KB's VLM OCR
pipeline, gated by the KB's multimodal setting: the image's external_id always
stays in SubtreeKeep (toggling VLM off never sweeps a previously-OCR'd image)
but the bytes are only downloaded/ingested when multimodal is enabled.
- Sub-documents (child wiki nodes) sync as their own nodes.
- The three paginated Feishu loops (document blocks, bitable fields, bitable
records) break on an empty page so a malformed has_more response cannot spin
until the task deadline.
Datasource ingestion infrastructure:
- Multi-item subtree reconciliation: a source node fans out into a parent plus
"<parent>#<kind>#<token>" children (types.SubtreeChildID); on re-sync the
sweep deletes prior children absent from SubtreeKeep. A per-child keep-set
means a single failed attachment can't wipe its siblings, and dupIsSameNode
guards the sweep so a file_hash-only dedup collision against a different node
cannot delete this node's children.
- config.MultimodalEnabled mirrors the KB's VLM state to the connector per run
(never persisted); an image a non-VLM KB rejects is skipped, not failed.
- A composite partial expression index (text_pattern_ops) backs the sweep's
metadata external_id prefix scan.
Verified end-to-end against a live Feishu wiki: docx text, native tables,
embedded sheets/bitables (with timezone-correct dates), attachments, images
(VLM OCR), and sub-documents all sync, parse, and are retrievable.
2026-07-24 13:03:04 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-27 07:02:40 +00:00
|
|
|
// bytesToFileHeader wraps a []byte into a *multipart.FileHeader so it can be
|
|
|
|
|
// consumed by KnowledgeService.CreateKnowledgeFromFile.
|
|
|
|
|
func bytesToFileHeader(data []byte, filename string) (*multipart.FileHeader, error) {
|
|
|
|
|
var buf bytes.Buffer
|
|
|
|
|
writer := multipart.NewWriter(&buf)
|
|
|
|
|
|
|
|
|
|
// Create a form file part
|
|
|
|
|
partHeader := make(textproto.MIMEHeader)
|
|
|
|
|
partHeader.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, filename))
|
|
|
|
|
partHeader.Set("Content-Type", "application/octet-stream")
|
|
|
|
|
|
|
|
|
|
part, err := writer.CreatePart(partHeader)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("create multipart part: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if _, err := part.Write(data); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("write data to part: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := writer.Close(); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("close multipart writer: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Parse the multipart data to get a FileHeader
|
|
|
|
|
reader := multipart.NewReader(&buf, writer.Boundary())
|
|
|
|
|
form, err := reader.ReadForm(int64(len(data)) + 1024)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("read multipart form: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
files := form.File["file"]
|
|
|
|
|
if len(files) == 0 {
|
|
|
|
|
return nil, fmt.Errorf("no file in multipart form")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return files[0], nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func timePtr(t time.Time) *time.Time {
|
|
|
|
|
utc := t.UTC()
|
|
|
|
|
return &utc
|
|
|
|
|
}
|