Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

feat(go-syncer): add Airtable connector with lazy fetch and resume (#19032)

mkaaad5217f99c50f7
diff --git a/internal/syncer/connector/airtable.go b/internal/syncer/connector/airtable.go
new file mode 100644
index 0000000000..7296ca2872
--- /dev/null
+++ b/internal/syncer/connector/airtable.go
@@ -0,0 +1,855 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package connector
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "ragflow/internal/utility"
+)
+
+const (
+ airtableDefaultBatchSize = 2
+ airtableDefaultSizeThreshold = 10 * 1024 * 1024
+ airtableAPIBaseURL = "https://api.airtable.com/v0"
+ airtableRequestTimeout = 60 * time.Second
+ airtableRetryCount = 4
+ airtableRetryBaseDelay = 200 * time.Millisecond
+ airtableMaxJSONResponseSize = 32 * 1024 * 1024
+ airtablePageSize = 100
+)
+
+// AirtableConnector reads attachments from an Airtable table through the
+// Airtable REST API using a personal access token.
+type AirtableConnector struct {
+ baseID string
+ tableNameOrID string
+ lastModified string
+ accessToken string
+ batchSize int
+ sizeThreshold int64
+ apiBaseURL string
+ httpClient *http.Client
+
+ listRecords func(ctx context.Context, pageURL string) (airtableRecordPage, error)
+ downloadFile func(ctx context.Context, rawURL string) ([]byte, error)
+}
+
+// NewAirtableConnector creates an Airtable connector from Python-compatible config.
+func NewAirtableConnector(config map[string]any) (*AirtableConnector, error) {
+ credentials := configAnyMap(config["credentials"])
+ batchSize := airtableBatchSize(firstNonEmpty(stringConfig(config["sync_batch_size"]), stringConfig(config["batch_size"])))
+ sizeThreshold := int64(configInt(config["size_threshold"], airtableDefaultSizeThreshold))
+ if sizeThreshold <= 0 {
+ sizeThreshold = airtableDefaultSizeThreshold
+ }
+ return &AirtableConnector{
+ baseID: strings.TrimSpace(stringConfig(config["base_id"])),
+ tableNameOrID: strings.TrimSpace(stringConfig(config["table_name_or_id"])),
+ lastModified: strings.TrimSpace(stringConfig(config["last_modified_field"])),
+ accessToken: strings.TrimSpace(stringConfig(credentials["airtable_access_token"])),
+ batchSize: batchSize,
+ sizeThreshold: sizeThreshold,
+ apiBaseURL: airtableAPIBaseURL,
+ httpClient: &http.Client{Timeout: airtableRequestTimeout},
+ }, nil
+}
+
+func airtableBatchSize(value string) int {
+ if strings.TrimSpace(value) == "" {
+ return airtableDefaultBatchSize
+ }
+ parsed, err := strconv.Atoi(strings.TrimSpace(value))
+ if err != nil {
+ return airtableDefaultBatchSize
+ }
+ return parsed
+}
+
+// Validate validates Airtable config and probes the configured table.
+func (c *AirtableConnector) Validate(ctx context.Context) error {
+ if err := c.validateStatic(); err != nil {
+ return err
+ }
+ if _, err := c.recordPage(ctx, c.recordsURL("", 1)); err != nil {
+ var apiErr *airtableAPIError
+ if errors.As(err, &apiErr) {
+ switch apiErr.status {
+ case http.StatusUnauthorized:
+ return &ConnectorMissingCredentialError{Message: "Airtable access token is invalid or expired."}
+ case http.StatusForbidden:
+ return &ConnectorValidationError{Message: "Airtable token does not have permission to read this base or table."}
+ case http.StatusNotFound:
+ return &ConnectorValidationError{Message: "Airtable base or table was not found."}
+ default:
+ return &ConnectorValidationError{Message: fmt.Sprintf("Airtable validation failed (HTTP %d): %s", apiErr.status, apiErr.body)}
+ }
+ }
+ return &ConnectorValidationError{Message: fmt.Sprintf("Airtable validation error: %v", err)}
+ }
+ return nil
+}
+
+// ValidateConnectorSetting validates an unsaved Airtable config through a
+// candidate connector so request-derived credentials are used.
+func (c *AirtableConnector) ValidateConnectorSetting(ctx context.Context, request map[string]any) error {
+ candidate, err := NewAirtableConnector(request)
+ if err != nil {
+ return err
+ }
+ if c != nil {
+ if c.httpClient != nil {
+ candidate.httpClient = c.httpClient
+ }
+ if c.apiBaseURL != "" {
+ candidate.apiBaseURL = c.apiBaseURL
+ }
+ }
+ ctx, cancel := context.WithTimeout(ctx, connectorSettingValidationTimeout)
+ defer cancel()
+ return candidate.Validate(ctx)
+}
+
+// OpenSync opens one Airtable sync session.
+func (c *AirtableConnector) OpenSync(ctx context.Context, request SyncRequest) (SyncSession, error) {
+ if err := c.validateStatic(); err != nil {
+ return nil, err
+ }
+ session := &airtableSyncSession{
+ connector: c,
+ request: request,
+ batchSize: c.effectiveBatchSize(),
+ }
+ if err := session.applyResume(request.Resume); err != nil {
+ return nil, err
+ }
+ return session, nil
+}
+
+// OpenPrune opens one complete Airtable prune snapshot session.
+func (c *AirtableConnector) OpenPrune(ctx context.Context, request PruneRequest) (PruneSession, error) {
+ if err := c.validateStatic(); err != nil {
+ return nil, err
+ }
+ return &airtablePruneSession{
+ connector: c,
+ batchSize: c.effectiveBatchSize(),
+ }, nil
+}
+
+func (c *AirtableConnector) validateStatic() error {
+ if c == nil {
+ return &ConnectorValidationError{Message: "Airtable connector is nil"}
+ }
+ if c.baseID == "" {
+ return &ConnectorValidationError{Message: "Airtable base_id is required"}
+ }
+ if c.tableNameOrID == "" {
+ return &ConnectorValidationError{Message: "Airtable table_name_or_id is required"}
+ }
+ if c.accessToken == "" {
+ return &ConnectorMissingCredentialError{Message: "Airtable airtable_access_token is required"}
+ }
+ if c.batchSize <= 0 {
+ return &ConnectorValidationError{Message: "Airtable connector batch_size must be a positive integer"}
+ }
+ return nil
+}
+
+func (c *AirtableConnector) effectiveBatchSize() int {
+ if c.batchSize > 0 {
+ return c.batchSize
+ }
+ return airtableDefaultBatchSize
+}
+
+func (c *AirtableConnector) recordsURL(offset string, pageSize int) string {
+ query := url.Values{}
+ if pageSize > 0 {
+ query.Set("pageSize", strconv.Itoa(pageSize))
+ }
+ if offset != "" {
+ query.Set("offset", offset)
+ }
+ base := strings.TrimRight(c.apiBaseURL, "/")
+ return fmt.Sprintf("%s/%s/%s?%s", base, url.PathEscape(c.baseID), url.PathEscape(c.tableNameOrID), query.Encode())
+}
+
+func (c *AirtableConnector) recordPage(ctx context.Context, pageURL string) (airtableRecordPage, error) {
+ if c.listRecords != nil {
+ return c.listRecords(ctx, pageURL)
+ }
+ var page airtableRecordPage
+ err := c.doJSON(ctx, pageURL, &page)
+ return page, err
+}
+
+func (c *AirtableConnector) doJSON(ctx context.Context, apiURL string, out any) error {
+ var lastErr error
+ for attempt := 1; attempt <= airtableRetryCount; attempt++ {
+ requestCtx, cancel := context.WithTimeout(ctx, airtableRequestTimeout)
+ req, err := http.NewRequestWithContext(requestCtx, http.MethodGet, apiURL, nil)
+ if err != nil {
+ cancel()
+ return err
+ }
+ req.Header.Set("Authorization", "Bearer "+c.accessToken)
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ cancel()
+ lastErr = err
+ } else {
+ body, readErr := io.ReadAll(io.LimitReader(resp.Body, airtableMaxJSONResponseSize+1))
+ resp.Body.Close()
+ cancel()
+ if resp.StatusCode >= 400 {
+ lastErr = &airtableAPIError{status: resp.StatusCode, body: strings.TrimSpace(string(body))}
+ if !isAirtableRetryable(resp.StatusCode) {
+ return lastErr
+ }
+ } else {
+ if readErr != nil {
+ return readErr
+ }
+ if int64(len(body)) > airtableMaxJSONResponseSize {
+ return fmt.Errorf("Airtable API response exceeds maximum size of %d bytes", airtableMaxJSONResponseSize)
+ }
+ return json.Unmarshal(body, out)
+ }
+ }
+ if attempt == airtableRetryCount {
+ break
+ }
+ delay := time.Duration(attempt) * airtableRetryBaseDelay
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(delay):
+ }
+ }
+ return lastErr
+}
+
+func isAirtableRetryable(status int) bool {
+ return status == http.StatusTooManyRequests || status == http.StatusRequestTimeout || status >= 500
+}
+
+// Fetch downloads a delayed Airtable attachment.
+func (c *AirtableConnector) Fetch(ctx context.Context, ref FetchReference) ([]byte, error) {
+ var fetch airtableFetchReference
+ if err := json.Unmarshal([]byte(ref.Key), &fetch); err != nil {
+ return nil, err
+ }
+ if fetch.RecordID == "" || fetch.AttachmentID == "" || fetch.URL == "" {
+ return nil, fmt.Errorf("airtable fetch reference is incomplete")
+ }
+ if fetch.Size > c.sizeThreshold {
+ return nil, fmt.Errorf("%s exceeds size threshold of %d", firstNonEmpty(fetch.Filename, fetch.AttachmentID), c.sizeThreshold)
+ }
+ return c.downloadAttachment(ctx, fetch.URL)
+}
+
+func (c *AirtableConnector) downloadAttachment(ctx context.Context, rawURL string) ([]byte, error) {
+ if c.downloadFile != nil {
+ return c.downloadFile(ctx, rawURL)
+ }
+ data, _, _, err := utility.FetchRemoteFileSafely(ctx, rawURL, c.sizeThreshold)
+ return data, err
+}
+
+func (c *AirtableConnector) isAcceptedAttachment(recordID string, attachment airtableAttachment) bool {
+ if recordID == "" || attachment.ID == "" || attachment.URL == "" || attachment.Filename == "" || attachment.CreatedTime == "" {
+ return false
+ }
+ if attachment.Size < 0 || (attachment.Size > 0 && attachment.Size > c.sizeThreshold) {
+ return false
+ }
+ return true
+}
+
+func (c *AirtableConnector) sourceDocument(recordID, fieldName string, attachment airtableAttachment) (SourceDocument, bool) {
+ if !c.isAcceptedAttachment(recordID, attachment) {
+ return SourceDocument{}, false
+ }
+ createdAt := parseOutlookTime(attachment.CreatedTime)
+ if createdAt.IsZero() {
+ return SourceDocument{}, false
+ }
+ fetch, _ := json.Marshal(airtableFetchReference{
+ RecordID: recordID,
+ AttachmentID: attachment.ID,
+ Filename: attachment.Filename,
+ URL: attachment.URL,
+ Size: attachment.Size,
+ })
+ return SourceDocument{
+ SourceID: airtableSourceID(recordID, attachment.ID),
+ SemanticIdentifier: attachment.Filename,
+ Extension: strings.ToLower(filepath.Ext(attachment.Filename)),
+ FetchRef: &FetchReference{Key: string(fetch), SizeHint: attachment.Size},
+ UpdatedAt: createdAt,
+ SizeBytes: attachment.Size,
+ Metadata: map[string]any{
+ "record_id": recordID,
+ "attachment_id": attachment.ID,
+ "field_name": fieldName,
+ "filename": attachment.Filename,
+ "url": attachment.URL,
+ "created_time": createdAt.UTC().Format(time.RFC3339Nano),
+ },
+ Fingerprint: airtableAttachmentFingerprint(recordID, fieldName, attachment),
+ }, true
+}
+
+func (c *AirtableConnector) recordDocument(record airtableRecord) (SourceDocument, bool) {
+ if strings.TrimSpace(record.ID) == "" {
+ return SourceDocument{}, false
+ }
+ updatedAt := c.recordUpdatedAt(record)
+ if updatedAt.IsZero() {
+ return SourceDocument{}, false
+ }
+ blob := airtableRecordBlob(record)
+ createdAt := parseOutlookTime(record.CreatedTime)
+ metadata := map[string]any{
+ "record_id": record.ID,
+ "base_id": c.baseID,
+ "table_name_or_id": c.tableNameOrID,
+ "last_modified": updatedAt.UTC().Format(time.RFC3339Nano),
+ }
+ if !createdAt.IsZero() {
+ metadata["created_time"] = createdAt.UTC().Format(time.RFC3339Nano)
+ }
+ return SourceDocument{
+ SourceID: airtableRecordSourceID(record.ID),
+ SemanticIdentifier: airtableRecordTitle(record),
+ Extension: ".json",
+ Blob: blob,
+ UpdatedAt: updatedAt,
+ SizeBytes: int64(len(blob)),
+ Metadata: metadata,
+ Fingerprint: airtableRecordFingerprint(record),
+ }, true
+}
+
+func (c *AirtableConnector) recordUpdatedAt(record airtableRecord) time.Time {
+ if field := strings.TrimSpace(c.lastModified); field != "" {
+ if raw, ok := record.Fields[field]; ok {
+ if updatedAt := parseOutlookTime(stringConfig(raw)); !updatedAt.IsZero() {
+ return updatedAt
+ }
+ }
+ }
+ return parseOutlookTime(record.CreatedTime)
+}
+
+func airtableRecordBlob(record airtableRecord) []byte {
+ blob, err := json.MarshalIndent(record.Fields, "", " ")
+ if err != nil {
+ return []byte("{}")
+ }
+ return blob
+}
+
+func airtableRecordFingerprint(record airtableRecord) string {
+ return contentFingerprint(airtableRecordBlob(record))
+}
+
+func airtableSourceID(recordID, attachmentID string) string {
+ return "airtable:" + recordID + ":" + attachmentID
+}
+
+func airtableRecordSourceID(recordID string) string {
+ return "airtable:" + recordID
+}
+
+func airtableRecordTitle(record airtableRecord) string {
+ if name := strings.TrimSpace(stringConfig(record.Fields["Name"])); name != "" {
+ return truncateRunes(name, 120)
+ }
+ fieldNames := make([]string, 0, len(record.Fields))
+ for fieldName := range record.Fields {
+ fieldNames = append(fieldNames, fieldName)
+ }
+ sort.Strings(fieldNames)
+ for _, fieldName := range fieldNames {
+ value := strings.TrimSpace(stringConfig(record.Fields[fieldName]))
+ if value != "" && len([]rune(value)) < 100 {
+ return truncateRunes(value, 50)
+ }
+ }
+ return "Record " + record.ID
+}
+
+func airtableAttachmentFingerprint(recordID, fieldName string, attachment airtableAttachment) string {
+ return stableFingerprint(map[string]any{
+ "record_id": recordID,
+ "field_name": fieldName,
+ "attachment_id": attachment.ID,
+ "filename": attachment.Filename,
+ "size": attachment.Size,
+ "type": attachment.Type,
+ "url": attachment.URL,
+ })
+}
+
+func (c *AirtableConnector) includeAirtableRecord(request SyncRequest, record airtableRecord) bool {
+ if request.FromBeginning {
+ return true
+ }
+ updatedAt := c.recordUpdatedAt(record)
+ if updatedAt.IsZero() {
+ return false
+ }
+ if len(request.Fingerprints) > 0 {
+ fingerprint := airtableRecordFingerprint(record)
+ stored, ok := request.Fingerprints[airtableRecordSourceID(record.ID)]
+ return fingerprint == "" || !ok || stored == "" || stored != fingerprint
+ }
+ if request.WindowStart != nil && updatedAt.Before(*request.WindowStart) {
+ return false
+ }
+ if !request.WindowEnd.IsZero() && !updatedAt.Before(request.WindowEnd) {
+ return false
+ }
+ return true
+}
+
+func includeAirtableAttachment(request SyncRequest, recordID string, attachment airtableAttachment) bool {
+ if request.FromBeginning {
+ return true
+ }
+ createdAt := parseOutlookTime(attachment.CreatedTime)
+ if createdAt.IsZero() {
+ return false
+ }
+ if len(request.Fingerprints) > 0 {
+ fingerprint := airtableAttachmentFingerprint(recordID, attachment.FieldName, attachment)
+ stored, ok := request.Fingerprints[airtableSourceID(recordID, attachment.ID)]
+ return fingerprint == "" || !ok || stored == "" || stored != fingerprint
+ }
+ if request.WindowStart != nil && createdAt.Before(*request.WindowStart) {
+ return false
+ }
+ if !request.WindowEnd.IsZero() && !createdAt.Before(request.WindowEnd) {
+ return false
+ }
+ return true
+}
+
+// airtableSyncSession streams Airtable record pages and checkpoints after each
+// emitted attachment.
+type airtableSyncSession struct {
+ connector *AirtableConnector
+ request SyncRequest
+ batchSize int
+
+ pageURL string
+ pending []airtableBufferedDocument
+ resumePageURL string
+ resumeOffset int
+ resumeSourceID string
+ done bool
+}
+
+// NextBatch returns the next Airtable source document batch.
+func (s *airtableSyncSession) NextBatch(ctx context.Context) (SyncBatch, error) {
+ documents := make([]SourceDocument, 0, s.batchSize)
+ var checkpoint *SyncCheckpoint
+ if len(s.pending) > 0 {
+ n := min(s.batchSize, len(s.pending))
+ for _, buffered := range s.pending[:n] {
+ documents = append(documents, buffered.document)
+ checkpoint = buffered.checkpoint
+ }
+ s.pending = s.pending[n:]
+ }
+ for len(documents) < s.batchSize {
+ if len(s.pending) == 0 {
+ if s.done {
+ if len(documents) == 0 {
+ return SyncBatch{}, io.EOF
+ }
+ break
+ }
+ page, nextPageURL, err := s.nextDocumentPage(ctx)
+ if err != nil {
+ return SyncBatch{}, err
+ }
+ s.pending = page
+ if nextPageURL == "" {
+ s.done = true
+ }
+ if len(page) == 0 && !s.done {
+ continue
+ }
+ }
+ remaining := s.batchSize - len(documents)
+ n := min(remaining, len(s.pending))
+ for _, buffered := range s.pending[:n] {
+ documents = append(documents, buffered.document)
+ checkpoint = buffered.checkpoint
+ }
+ s.pending = s.pending[n:]
+ }
+ return SyncBatch{Documents: documents, Checkpoint: checkpoint}, nil
+}
+
+// Close closes the Airtable sync session.
+func (s *airtableSyncSession) Close() error {
+ return nil
+}
+
+// Fetch downloads a delayed Airtable attachment for this sync session.
+func (s *airtableSyncSession) Fetch(ctx context.Context, ref FetchReference) ([]byte, error) {
+ return s.connector.Fetch(ctx, ref)
+}
+
+func (s *airtableSyncSession) nextDocumentPage(ctx context.Context) ([]airtableBufferedDocument, string, error) {
+ pageURL := s.pageURL
+ if pageURL == "" {
+ pageURL = s.connector.recordsURL("", airtablePageSize)
+ }
+ page, err := s.connector.recordPage(ctx, pageURL)
+ if err != nil {
+ return nil, "", err
+ }
+
+ all := make([]airtableBufferedDocument, 0)
+ included := make([]airtableBufferedDocument, 0)
+ offset := 0
+ for _, record := range page.Records {
+ if recordDoc, ok := s.connector.recordDocument(record); ok {
+ offset++
+ buffered := airtableBufferedDocument{
+ document: recordDoc,
+ checkpoint: s.checkpoint(airtableSyncCursor{PageURL: pageURL, Offset: offset, SourceID: recordDoc.SourceID}, recordDoc),
+ offset: offset,
+ }
+ all = append(all, buffered)
+ if s.connector.includeAirtableRecord(s.request, record) {
+ included = append(included, buffered)
+ }
+ }
+ for _, attachment := range airtableAttachments(record) {
+ if !s.connector.isAcceptedAttachment(record.ID, attachment) {
+ continue
+ }
+ doc, ok := s.connector.sourceDocument(record.ID, attachment.FieldName, attachment)
+ if !ok {
+ continue
+ }
+ offset++
+ buffered := airtableBufferedDocument{
+ document: doc,
+ checkpoint: s.checkpoint(airtableSyncCursor{PageURL: pageURL, Offset: offset, SourceID: doc.SourceID}, doc),
+ offset: offset,
+ }
+ all = append(all, buffered)
+ if includeAirtableAttachment(s.request, record.ID, attachment) {
+ included = append(included, buffered)
+ }
+ }
+ }
+
+ documents, err := s.filterResumedDocuments(pageURL, all, included)
+ if err != nil {
+ return nil, "", err
+ }
+ nextPageURL := ""
+ if page.Offset != "" {
+ nextPageURL = s.connector.recordsURL(page.Offset, airtablePageSize)
+ if nextPageURL == pageURL {
+ return nil, "", fmt.Errorf("airtable sync pagination did not advance from %s", pageURL)
+ }
+ }
+ s.pageURL = nextPageURL
+ return documents, nextPageURL, nil
+}
+
+func (s *airtableSyncSession) applyResume(checkpoint *SyncCheckpoint) error {
+ if checkpoint == nil {
+ return nil
+ }
+ if checkpoint.Cursor == "" {
+ return fmt.Errorf("airtable sync cursor is missing: %w", ErrSyncResumeInvalid)
+ }
+ var cursor airtableSyncCursor
+ if err := json.Unmarshal([]byte(checkpoint.Cursor), &cursor); err != nil {
+ return fmt.Errorf("airtable sync cursor is invalid: %w", ErrSyncResumeInvalid)
+ }
+ sourceID := firstNonEmpty(cursor.SourceID, checkpoint.SourceID)
+ if sourceID == "" || cursor.PageURL == "" {
+ return fmt.Errorf("airtable sync checkpoint has no source anchor: %w", ErrSyncResumeInvalid)
+ }
+ s.pageURL = cursor.PageURL
+ s.resumePageURL = cursor.PageURL
+ s.resumeSourceID = sourceID
+ s.resumeOffset = cursor.Offset
+ return nil
+}
+
+func (s *airtableSyncSession) filterResumedDocuments(pageURL string, all, included []airtableBufferedDocument) ([]airtableBufferedDocument, error) {
+ if s.resumeSourceID == "" {
+ return included, nil
+ }
+ if pageURL != s.resumePageURL {
+ return nil, fmt.Errorf("airtable resume page %q no longer matches checkpoint page %q: %w", pageURL, s.resumePageURL, ErrSyncResumeInvalid)
+ }
+ anchorOffset := -1
+ for _, candidate := range all {
+ if candidate.document.SourceID == s.resumeSourceID {
+ anchorOffset = candidate.offset
+ break
+ }
+ }
+ if anchorOffset < 0 {
+ return nil, fmt.Errorf("airtable resume anchor %q was not found on %s: %w", s.resumeSourceID, pageURL, ErrSyncResumeInvalid)
+ }
+ s.clearResumeOffset()
+ filtered := included[:0]
+ for _, candidate := range included {
+ if candidate.offset > anchorOffset {
+ filtered = append(filtered, candidate)
+ }
+ }
+ return filtered, nil
+}
+
+func (s *airtableSyncSession) checkpoint(cursor airtableSyncCursor, doc SourceDocument) *SyncCheckpoint {
+ data, err := json.Marshal(cursor)
+ if err != nil {
+ return nil
+ }
+ updatedAt := doc.UpdatedAt
+ return &SyncCheckpoint{Cursor: string(data), UpdatedAt: &updatedAt, SourceID: doc.SourceID}
+}
+
+func (s *airtableSyncSession) clearResumeOffset() {
+ s.resumePageURL = ""
+ s.resumeSourceID = ""
+ s.resumeOffset = 0
+}
+
+type airtableBufferedDocument struct {
+ document SourceDocument
+ checkpoint *SyncCheckpoint
+ offset int
+}
+
+type airtableSyncCursor struct {
+ PageURL string `json:"page_url"`
+ Offset int `json:"offset,omitempty"`
+ SourceID string `json:"source_id,omitempty"`
+}
+
+// airtablePruneSession streams the complete Airtable slim snapshot.
+type airtablePruneSession struct {
+ connector *AirtableConnector
+ batchSize int
+ pageURL string
+ buffer []SlimDocument
+ done bool
+}
+
+// NextBatch returns the next Airtable prune snapshot batch.
+func (s *airtablePruneSession) NextBatch(ctx context.Context) (PruneBatch, error) {
+ documents := make([]SlimDocument, 0, s.batchSize)
+ if len(s.buffer) > 0 {
+ n := min(s.batchSize, len(s.buffer))
+ documents = append(documents, s.buffer[:n]...)
+ s.buffer = s.buffer[n:]
+ }
+ for len(documents) < s.batchSize {
+ if s.done {
+ if len(documents) == 0 {
+ return PruneBatch{}, io.EOF
+ }
+ break
+ }
+ page, err := s.nextSlimPage(ctx)
+ if err != nil {
+ return PruneBatch{}, err
+ }
+ remaining := s.batchSize - len(documents)
+ if len(page) > remaining {
+ documents = append(documents, page[:remaining]...)
+ s.buffer = append(s.buffer, page[remaining:]...)
+ break
+ }
+ documents = append(documents, page...)
+ }
+ return PruneBatch{Documents: documents}, nil
+}
+
+// Close closes the Airtable prune session.
+func (s *airtablePruneSession) Close() error {
+ return nil
+}
+
+func (s *airtablePruneSession) nextSlimPage(ctx context.Context) ([]SlimDocument, error) {
+ pageURL := s.pageURL
+ if pageURL == "" {
+ pageURL = s.connector.recordsURL("", airtablePageSize)
+ }
+ page, err := s.connector.recordPage(ctx, pageURL)
+ if err != nil {
+ return nil, err
+ }
+ documents := make([]SlimDocument, 0)
+ for _, record := range page.Records {
+ if _, ok := s.connector.recordDocument(record); ok {
+ documents = append(documents, SlimDocument{SourceID: airtableRecordSourceID(record.ID)})
+ }
+ for _, attachment := range airtableAttachments(record) {
+ if s.connector.isAcceptedAttachment(record.ID, attachment) {
+ documents = append(documents, SlimDocument{SourceID: airtableSourceID(record.ID, attachment.ID)})
+ }
+ }
+ }
+ if page.Offset != "" {
+ nextPageURL := s.connector.recordsURL(page.Offset, airtablePageSize)
+ if nextPageURL == pageURL {
+ return nil, fmt.Errorf("airtable prune pagination did not advance from %s", pageURL)
+ }
+ s.pageURL = nextPageURL
+ } else {
+ s.done = true
+ }
+ return documents, nil
+}
+
+func airtableAttachments(record airtableRecord) []airtableAttachment {
+ attachments := []airtableAttachment{}
+ fieldNames := make([]string, 0, len(record.Fields))
+ for fieldName := range record.Fields {
+ fieldNames = append(fieldNames, fieldName)
+ }
+ sort.Strings(fieldNames)
+ for _, fieldName := range fieldNames {
+ raw := record.Fields[fieldName]
+ list, ok := raw.([]any)
+ if !ok {
+ continue
+ }
+ for _, item := range list {
+ obj, ok := item.(map[string]any)
+ if !ok {
+ continue
+ }
+ attachment, ok := airtableAttachmentFromMap(obj)
+ if !ok {
+ continue
+ }
+ attachment.FieldName = fieldName
+ attachment.CreatedTime = record.CreatedTime
+ attachments = append(attachments, attachment)
+ }
+ }
+ return attachments
+}
+
+func airtableAttachmentFromMap(value map[string]any) (airtableAttachment, bool) {
+ attachment := airtableAttachment{
+ ID: stringConfig(value["id"]),
+ URL: stringConfig(value["url"]),
+ Filename: stringConfig(value["filename"]),
+ Type: stringConfig(value["type"]),
+ Size: airtableSizeValue(value["size"]),
+ }
+ if attachment.ID == "" || attachment.URL == "" || attachment.Filename == "" {
+ return airtableAttachment{}, false
+ }
+ return attachment, true
+}
+
+func airtableSizeValue(value any) int64 {
+ switch typed := value.(type) {
+ case int:
+ if typed >= 0 {
+ return int64(typed)
+ }
+ case int64:
+ if typed >= 0 {
+ return typed
+ }
+ case float64:
+ if typed >= 0 && typed == float64(int64(typed)) {
+ return int64(typed)
+ }
+ case json.Number:
+ parsed, err := typed.Int64()
+ if err == nil && parsed >= 0 {
+ return parsed
+ }
+ case string:
+ parsed, err := strconv.ParseInt(strings.TrimSpace(typed), 10, 64)
+ if err == nil && parsed >= 0 {
+ return parsed
+ }
+ }
+ return 0
+}
+
+type airtableRecordPage struct {
+ Records []airtableRecord `json:"records"`
+ Offset string `json:"offset,omitempty"`
+}
+
+type airtableRecord struct {
+ ID string `json:"id"`
+ CreatedTime string `json:"createdTime"`
+ Fields map[string]any `json:"fields"`
+}
+
+type airtableAttachment struct {
+ ID string
+ URL string
+ Filename string
+ Type string
+ Size int64
+ FieldName string
+ CreatedTime string
+}
+
+type airtableFetchReference struct {
+ RecordID string `json:"record_id"`
+ AttachmentID string `json:"attachment_id"`
+ Filename string `json:"filename"`
+ URL string `json:"url"`
+ Size int64 `json:"size"`
+}
+
+type airtableAPIError struct {
+ status int
+ body string
+}
+
+func (e *airtableAPIError) Error() string {
+ return fmt.Sprintf("Airtable API returned HTTP %d: %s", e.status, e.body)
+}
diff --git a/internal/syncer/connector/airtable_test.go b/internal/syncer/connector/airtable_test.go
new file mode 100644
index 0000000000..dab64834b0
--- /dev/null
+++ b/internal/syncer/connector/airtable_test.go
@@ -0,0 +1,637 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package connector
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestNewAirtableConnectorParsesConfig(t *testing.T) {
+ connector, err := NewAirtableConnector(map[string]any{
+ "credentials": map[string]any{
+ "airtable_access_token": "token",
+ },
+ "base_id": "base 1",
+ "table_name_or_id": "My Table",
+ "last_modified_field": "Modified",
+ "batch_size": "0",
+ "sync_batch_size": "3",
+ "size_threshold": "123",
+ })
+ if err != nil {
+ t.Fatalf("NewAirtableConnector failed: %v", err)
+ }
+ if connector.baseID != "base 1" || connector.tableNameOrID != "My Table" || connector.accessToken != "token" {
+ t.Fatalf("config = %q/%q/%q", connector.baseID, connector.tableNameOrID, connector.accessToken)
+ }
+ if connector.batchSize != 3 || connector.sizeThreshold != 123 {
+ t.Fatalf("batch/threshold = %d/%d, want 3/123", connector.batchSize, connector.sizeThreshold)
+ }
+ if connector.lastModified != "Modified" {
+ t.Fatalf("last modified field = %q", connector.lastModified)
+ }
+}
+
+func TestNewAirtableConnectorDefaults(t *testing.T) {
+ connector, err := NewAirtableConnector(nil)
+ if err != nil {
+ t.Fatalf("NewAirtableConnector failed: %v", err)
+ }
+ if connector.batchSize != airtableDefaultBatchSize || connector.sizeThreshold != airtableDefaultSizeThreshold {
+ t.Fatalf("defaults = batch %d threshold %d", connector.batchSize, connector.sizeThreshold)
+ }
+}
+
+func TestAirtableValidateRejectsMissingFields(t *testing.T) {
+ connector := newAirtableTestConnector()
+ connector.accessToken = ""
+ err := connector.Validate(context.Background())
+ var missing *ConnectorMissingCredentialError
+ if !errors.As(err, &missing) {
+ t.Fatalf("Validate error = %v, want ConnectorMissingCredentialError", err)
+ }
+
+ connector = newAirtableTestConnector()
+ connector.baseID = ""
+ if err := connector.Validate(context.Background()); err == nil || !strings.Contains(err.Error(), "base_id") {
+ t.Fatalf("missing base error = %v", err)
+ }
+
+ connector = newAirtableTestConnector()
+ connector.batchSize = 0
+ if err := connector.Validate(context.Background()); err == nil || !strings.Contains(err.Error(), "batch_size") {
+ t.Fatalf("batch error = %v", err)
+ }
+}
+
+func TestAirtableValidateProbesTable(t *testing.T) {
+ connector := newAirtableTestConnector()
+ connector.listRecords = func(ctx context.Context, pageURL string) (airtableRecordPage, error) {
+ if !strings.Contains(pageURL, "pageSize=1") || !strings.Contains(pageURL, "/base%201/My%20Table") {
+ t.Fatalf("validation URL = %q", pageURL)
+ }
+ return airtableRecordPage{}, nil
+ }
+ if err := connector.Validate(context.Background()); err != nil {
+ t.Fatalf("Validate failed: %v", err)
+ }
+}
+
+func TestAirtableValidateClassifiesAPIErrors(t *testing.T) {
+ tests := []struct {
+ status int
+ want any
+ }{
+ {http.StatusUnauthorized, &ConnectorMissingCredentialError{}},
+ {http.StatusForbidden, &ConnectorValidationError{}},
+ {http.StatusNotFound, &ConnectorValidationError{}},
+ {http.StatusBadGateway, &ConnectorValidationError{}},
+ }
+ for _, test := range tests {
+ connector := newAirtableTestConnector()
+ connector.listRecords = func(ctx context.Context, pageURL string) (airtableRecordPage, error) {
+ return airtableRecordPage{}, &airtableAPIError{status: test.status, body: "api error"}
+ }
+ err := connector.Validate(context.Background())
+ switch test.want.(type) {
+ case *ConnectorMissingCredentialError:
+ var missing *ConnectorMissingCredentialError
+ if !errors.As(err, &missing) {
+ t.Fatalf("status %d error = %v, want ConnectorMissingCredentialError", test.status, err)
+ }
+ case *ConnectorValidationError:
+ var validation *ConnectorValidationError
+ if !errors.As(err, &validation) {
+ t.Fatalf("status %d error = %v, want ConnectorValidationError", test.status, err)
+ }
+ }
+ }
+}
+
+func TestAirtableValidateConnectorSettingUsesCandidateConfig(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v0/base/table" || r.URL.Query().Get("pageSize") != "1" {
+ t.Errorf("unexpected validation URL %s", r.URL.String())
+ return
+ }
+ if r.Header.Get("Authorization") != "Bearer request-token" {
+ t.Errorf("authorization = %q", r.Header.Get("Authorization"))
+ return
+ }
+ w.Write([]byte(`{"records":[]}`))
+ }))
+ defer server.Close()
+
+ receiver := &AirtableConnector{
+ apiBaseURL: server.URL + "/v0",
+ httpClient: server.Client(),
+ }
+ err := receiver.ValidateConnectorSetting(context.Background(), map[string]any{
+ "base_id": "base",
+ "table_name_or_id": "table",
+ "credentials": map[string]any{
+ "airtable_access_token": "request-token",
+ },
+ })
+ if err != nil {
+ t.Fatalf("ValidateConnectorSetting failed: %v", err)
+ }
+}
+
+func TestAirtableOpenSyncUsesAttachmentsAndFetch(t *testing.T) {
+ connector := newAirtableTestConnector()
+ connector.batchSize = 3
+ connector.listRecords = func(ctx context.Context, pageURL string) (airtableRecordPage, error) {
+ return airtableRecordPage{Records: []airtableRecord{airtableTestRecord()}}, nil
+ }
+ var fetchedURL string
+ connector.downloadFile = func(ctx context.Context, rawURL string) ([]byte, error) {
+ fetchedURL = rawURL
+ if rawURL != "https://example.test/a.pdf" {
+ t.Fatalf("fetch URL = %q", rawURL)
+ }
+ return []byte("pdf-body"), nil
+ }
+
+ session, err := connector.OpenSync(context.Background(), SyncRequest{FromBeginning: true})
+ if err != nil {
+ t.Fatalf("OpenSync failed: %v", err)
+ }
+ batch, err := session.NextBatch(context.Background())
+ if err != nil {
+ t.Fatalf("NextBatch failed: %v", err)
+ }
+ if len(batch.Documents) != 3 {
+ t.Fatalf("documents len = %d, want 3", len(batch.Documents))
+ }
+ recordDoc := batch.Documents[0]
+ if recordDoc.SourceID != "airtable:rec-1" || recordDoc.Extension != ".json" || len(recordDoc.Blob) == 0 {
+ t.Fatalf("record document = %+v", recordDoc)
+ }
+ doc := batch.Documents[1]
+ if doc.SourceID != "airtable:rec-1:att-1" || doc.SemanticIdentifier != "report.PDF" || doc.Extension != ".pdf" {
+ t.Fatalf("document shape = %+v", doc)
+ }
+ if !doc.UpdatedAt.Equal(mustTime(t, "2026-01-02T03:04:05Z")) {
+ t.Fatalf("updated at = %s", doc.UpdatedAt)
+ }
+ if doc.Fingerprint == "" || doc.FetchRef == nil {
+ t.Fatalf("fingerprint/fetchref = %q/%+v", doc.Fingerprint, doc.FetchRef)
+ }
+ if doc.Metadata["record_id"] != "rec-1" || doc.Metadata["attachment_id"] != "att-1" || doc.Metadata["field_name"] != "Attachments" {
+ t.Fatalf("metadata = %+v", doc.Metadata)
+ }
+
+ fetcher, ok := session.(Fetcher)
+ if !ok {
+ t.Fatalf("session does not implement Fetcher")
+ }
+ blob, err := fetcher.Fetch(context.Background(), *batch.Documents[1].FetchRef)
+ if err != nil {
+ t.Fatalf("Fetch failed: %v", err)
+ }
+ if string(blob) != "pdf-body" || fetchedURL == "" {
+ t.Fatalf("fetch blob = %q, url = %q", blob, fetchedURL)
+ }
+ if err := session.Close(); err != nil {
+ t.Fatalf("Close failed: %v", err)
+ }
+}
+
+func TestAirtableOpenSyncWindowFilter(t *testing.T) {
+ connector := newAirtableTestConnector()
+ connector.batchSize = 10
+ connector.listRecords = func(ctx context.Context, pageURL string) (airtableRecordPage, error) {
+ return airtableRecordPage{Records: []airtableRecord{
+ airtableTestRecordWithIDTime("before", "2026-01-01T00:00:00Z", "before.pdf"),
+ airtableTestRecordWithIDTime("inside", "2026-01-03T00:00:00Z", "inside.pdf"),
+ airtableTestRecordWithIDTime("after", "2026-01-05T00:00:00Z", "after.pdf"),
+ }}, nil
+ }
+ session, err := connector.OpenSync(context.Background(), SyncRequest{
+ WindowStart: airtableMustTimePointer(t, "2026-01-02T00:00:00Z"),
+ WindowEnd: mustTime(t, "2026-01-04T00:00:00Z"),
+ })
+ if err != nil {
+ t.Fatalf("OpenSync failed: %v", err)
+ }
+ batch, err := session.NextBatch(context.Background())
+ if err != nil {
+ t.Fatalf("NextBatch failed: %v", err)
+ }
+ if len(batch.Documents) != 2 {
+ t.Fatalf("documents len = %d, want 2", len(batch.Documents))
+ }
+ got := map[string]bool{}
+ for _, doc := range batch.Documents {
+ got[doc.SourceID] = true
+ }
+ if !got["airtable:inside"] || !got["airtable:inside:att-1"] {
+ t.Fatalf("documents = %+v, want record and attachment", got)
+ }
+}
+
+func TestAirtableOpenSyncWindowUsesLastModifiedField(t *testing.T) {
+ connector := newAirtableTestConnector()
+ connector.lastModified = "Modified"
+ connector.batchSize = 10
+ connector.listRecords = func(ctx context.Context, pageURL string) (airtableRecordPage, error) {
+ inside := airtableTestRecordWithIDTime("inside", "2026-01-01T00:00:00Z", "inside.pdf")
+ inside.Fields["Modified"] = "2026-01-03T00:00:00Z"
+ after := airtableTestRecordWithIDTime("after", "2026-01-01T00:00:00Z", "after.pdf")
+ after.Fields["Modified"] = "2026-01-05T00:00:00Z"
+ fallback := airtableTestRecordWithIDTime("fallback", "2026-01-01T00:00:00Z", "fallback.pdf")
+ return airtableRecordPage{Records: []airtableRecord{inside, after, fallback}}, nil
+ }
+ session, err := connector.OpenSync(context.Background(), SyncRequest{
+ WindowStart: airtableMustTimePointer(t, "2026-01-02T00:00:00Z"),
+ WindowEnd: mustTime(t, "2026-01-04T00:00:00Z"),
+ })
+ if err != nil {
+ t.Fatalf("OpenSync failed: %v", err)
+ }
+ batch, err := session.NextBatch(context.Background())
+ if err != nil {
+ t.Fatalf("NextBatch failed: %v", err)
+ }
+ if len(batch.Documents) != 1 || batch.Documents[0].SourceID != "airtable:inside" {
+ t.Fatalf("documents = %#v, want inside record only", batch.Documents)
+ }
+ if !batch.Documents[0].UpdatedAt.Equal(mustTime(t, "2026-01-03T00:00:00Z")) {
+ t.Fatalf("record updated at = %s, want 2026-01-03T00:00:00Z", batch.Documents[0].UpdatedAt)
+ }
+}
+
+func TestAirtableRecordDocumentFallsBackToCreatedTime(t *testing.T) {
+ connector := newAirtableTestConnector()
+ connector.lastModified = "Modified"
+ withField := airtableRecord{
+ ID: "rec-field",
+ CreatedTime: "2026-01-01T00:00:00Z",
+ Fields: map[string]any{
+ "Modified": "2026-01-03T00:00:00Z",
+ },
+ }
+ doc, ok := connector.recordDocument(withField)
+ if !ok || !doc.UpdatedAt.Equal(mustTime(t, "2026-01-03T00:00:00Z")) {
+ t.Fatalf("recordDocument with field = ok %v, updated %s", ok, doc.UpdatedAt)
+ }
+ if doc.Metadata["last_modified"] != "2026-01-03T00:00:00Z" {
+ t.Fatalf("last_modified metadata = %v", doc.Metadata["last_modified"])
+ }
+
+ withoutField := airtableRecord{
+ ID: "rec-created",
+ CreatedTime: "2026-01-02T00:00:00Z",
+ Fields: map[string]any{},
+ }
+ doc, ok = connector.recordDocument(withoutField)
+ if !ok || !doc.UpdatedAt.Equal(mustTime(t, "2026-01-02T00:00:00Z")) {
+ t.Fatalf("recordDocument fallback = ok %v, updated %s", ok, doc.UpdatedAt)
+ }
+}
+
+func TestAirtableOpenSyncFingerprintFilter(t *testing.T) {
+ connector := newAirtableTestConnector()
+ connector.batchSize = 10
+ connector.listRecords = func(ctx context.Context, pageURL string) (airtableRecordPage, error) {
+ return airtableRecordPage{Records: []airtableRecord{
+ airtableTestRecordWithIDTime("changed", "2026-01-03T00:00:00Z", "changed.pdf"),
+ airtableTestRecordWithIDTime("same", "2026-01-03T00:00:00Z", "same.pdf"),
+ airtableTestRecordWithIDTime("missing", "2026-01-03T00:00:00Z", "missing.pdf"),
+ }}, nil
+ }
+ request := SyncRequest{
+ WindowStart: airtableMustTimePointer(t, "2026-01-02T00:00:00Z"),
+ WindowEnd: mustTime(t, "2026-01-04T00:00:00Z"),
+ Fingerprints: map[string]string{
+ "airtable:changed:att-1": "old",
+ "airtable:same:att-1": airtableAttachmentFingerprint("same", "Attachments", airtableTestAttachment("same.pdf")),
+ },
+ }
+ session, err := connector.OpenSync(context.Background(), request)
+ if err != nil {
+ t.Fatalf("OpenSync failed: %v", err)
+ }
+ batch, err := session.NextBatch(context.Background())
+ if err != nil {
+ t.Fatalf("NextBatch failed: %v", err)
+ }
+ got := []string{}
+ for _, doc := range batch.Documents {
+ got = append(got, doc.SourceID)
+ }
+ if len(got) != 5 {
+ t.Fatalf("documents = %v, want 5", got)
+ }
+ want := map[string]bool{
+ "airtable:changed": true,
+ "airtable:same": true,
+ "airtable:missing": true,
+ "airtable:changed:att-1": true,
+ "airtable:missing:att-1": true,
+ }
+ for _, sourceID := range got {
+ delete(want, sourceID)
+ }
+ if len(want) != 0 {
+ t.Fatalf("documents missing %v; got %v", want, got)
+ }
+}
+
+func TestAirtableOpenSyncResumeWithinPage(t *testing.T) {
+ connector := newAirtableTestConnector()
+ connector.batchSize = 4
+ connector.listRecords = func(ctx context.Context, pageURL string) (airtableRecordPage, error) {
+ return airtableRecordPage{Records: []airtableRecord{
+ airtableTestRecordWithIDTime("rec-1", "2026-01-01T00:00:00Z", "a.pdf"),
+ airtableTestRecordWithIDTime("rec-2", "2026-01-02T00:00:00Z", "b.pdf"),
+ airtableTestRecordWithIDTime("rec-3", "2026-01-03T00:00:00Z", "c.pdf"),
+ }}, nil
+ }
+ first, err := connector.OpenSync(context.Background(), SyncRequest{FromBeginning: true})
+ if err != nil {
+ t.Fatalf("first OpenSync failed: %v", err)
+ }
+ batch, err := first.NextBatch(context.Background())
+ if err != nil {
+ t.Fatalf("first NextBatch failed: %v", err)
+ }
+ if len(batch.Documents) != 4 || batch.Checkpoint == nil || batch.Checkpoint.SourceID != "airtable:rec-2:att-1" {
+ t.Fatalf("first batch = %+v", batch)
+ }
+
+ resumed, err := connector.OpenSync(context.Background(), SyncRequest{FromBeginning: true, Resume: batch.Checkpoint})
+ if err != nil {
+ t.Fatalf("resume OpenSync failed: %v", err)
+ }
+ second, err := resumed.NextBatch(context.Background())
+ if err != nil {
+ t.Fatalf("resume NextBatch failed: %v", err)
+ }
+ if len(second.Documents) != 2 {
+ t.Fatalf("resume documents = %+v, want 2", second.Documents)
+ }
+ got := map[string]bool{}
+ for _, doc := range second.Documents {
+ got[doc.SourceID] = true
+ }
+ if !got["airtable:rec-3"] || !got["airtable:rec-3:att-1"] {
+ t.Fatalf("resume documents = %+v, want rec-3 record and attachment", got)
+ }
+}
+
+func TestAirtableOpenSyncResumeRejectsMissingCheckpoint(t *testing.T) {
+ connector := newAirtableTestConnector()
+ session, err := connector.OpenSync(context.Background(), SyncRequest{FromBeginning: true, Resume: &SyncCheckpoint{}})
+ if session != nil || err == nil || !errors.Is(err, ErrSyncResumeInvalid) {
+ t.Fatalf("resume OpenSync = session %v, err %v, want ErrSyncResumeInvalid", session, err)
+ }
+}
+
+func TestAirtableOpenSyncResumeRejectsMissingAnchor(t *testing.T) {
+ connector := newAirtableTestConnector()
+ connector.listRecords = func(ctx context.Context, pageURL string) (airtableRecordPage, error) {
+ return airtableRecordPage{Records: []airtableRecord{
+ airtableTestRecordWithIDTime("rec-1", "2026-01-01T00:00:00Z", "a.pdf"),
+ airtableTestRecordWithIDTime("rec-3", "2026-01-03T00:00:00Z", "c.pdf"),
+ }}, nil
+ }
+ checkpoint := &SyncCheckpoint{
+ Cursor: `{"page_url":"` + connector.recordsURL("", airtablePageSize) + `","source_id":"airtable:rec-2:att-1"}`,
+ }
+ session, err := connector.OpenSync(context.Background(), SyncRequest{FromBeginning: true, Resume: checkpoint})
+ if err != nil {
+ t.Fatalf("resume OpenSync failed: %v", err)
+ }
+ if _, err := session.NextBatch(context.Background()); err == nil || !errors.Is(err, ErrSyncResumeInvalid) {
+ t.Fatalf("resume NextBatch err = %v, want ErrSyncResumeInvalid", err)
+ }
+}
+
+func TestAirtableOpenPrune(t *testing.T) {
+ connector := newAirtableTestConnector()
+ connector.batchSize = 1
+ connector.listRecords = func(ctx context.Context, pageURL string) (airtableRecordPage, error) {
+ if strings.Contains(pageURL, "offset=next") {
+ return airtableRecordPage{Records: []airtableRecord{
+ airtableTestRecordWithIDTime("rec-2", "2026-01-02T00:00:00Z", "b.pdf"),
+ }}, nil
+ }
+ return airtableRecordPage{
+ Records: []airtableRecord{
+ airtableTestRecordWithIDTime("rec-1", "2026-01-01T00:00:00Z", "a.pdf"),
+ {ID: "rec-invalid", CreatedTime: "2026-01-01T00:00:00Z", Fields: map[string]any{"Attachments": []any{"not-a-map"}}},
+ {ID: "rec-missing", CreatedTime: "2026-01-01T00:00:00Z", Fields: map[string]any{"Attachments": []any{map[string]any{"id": "att-missing", "filename": "missing.pdf"}}}},
+ },
+ Offset: "next",
+ }, nil
+ }
+ session, err := connector.OpenPrune(context.Background(), PruneRequest{})
+ if err != nil {
+ t.Fatalf("OpenPrune failed: %v", err)
+ }
+ var got []string
+ for {
+ batch, err := session.NextBatch(context.Background())
+ if errors.Is(err, io.EOF) {
+ break
+ }
+ if err != nil {
+ t.Fatalf("NextBatch failed: %v", err)
+ }
+ for _, doc := range batch.Documents {
+ got = append(got, doc.SourceID)
+ }
+ }
+ if len(got) != 6 {
+ t.Fatalf("prune documents = %v, want 6", got)
+ }
+ want := map[string]bool{
+ "airtable:rec-1": true,
+ "airtable:rec-1:att-1": true,
+ "airtable:rec-invalid": true,
+ "airtable:rec-missing": true,
+ "airtable:rec-2": true,
+ "airtable:rec-2:att-1": true,
+ }
+ for _, sourceID := range got {
+ delete(want, sourceID)
+ }
+ if len(want) != 0 {
+ t.Fatalf("prune documents missing %v; got %v", want, got)
+ }
+}
+
+func TestAirtablePrunePaginationStall(t *testing.T) {
+ connector := newAirtableTestConnector()
+ connector.listRecords = func(ctx context.Context, url string) (airtableRecordPage, error) {
+ return airtableRecordPage{Offset: "same", Records: []airtableRecord{
+ airtableTestRecordWithIDTime("rec-1", "2026-01-01T00:00:00Z", "a.pdf"),
+ }}, nil
+ }
+ session, err := connector.OpenPrune(context.Background(), PruneRequest{})
+ if err != nil {
+ t.Fatalf("OpenPrune failed: %v", err)
+ }
+ pruneSession := session.(*airtablePruneSession)
+ pruneSession.pageURL = connector.recordsURL("same", airtablePageSize)
+ if _, err := pruneSession.NextBatch(context.Background()); err == nil || !strings.Contains(err.Error(), "did not advance") {
+ t.Fatalf("prune NextBatch err = %v, want stalled pagination error", err)
+ }
+}
+
+func TestAirtableFetch(t *testing.T) {
+ connector := newAirtableTestConnector()
+ connector.sizeThreshold = 5
+ ref := FetchReference{Key: `{"record_id":"rec-1","attachment_id":"att-1","filename":"big.pdf","url":"https://example.test/big","size":10}`}
+ if _, err := connector.Fetch(context.Background(), ref); err == nil || !strings.Contains(err.Error(), "exceeds size threshold") {
+ t.Fatalf("oversize Fetch err = %v", err)
+ }
+
+ var fetchedURL string
+ connector.downloadFile = func(ctx context.Context, rawURL string) ([]byte, error) {
+ fetchedURL = rawURL
+ return []byte("hello"), nil
+ }
+ ref.Key = `{"record_id":"rec-1","attachment_id":"att-1","filename":"ok.pdf","url":"https://example.test/ok","size":5}`
+ blob, err := connector.Fetch(context.Background(), ref)
+ if err != nil {
+ t.Fatalf("Fetch failed: %v", err)
+ }
+ if string(blob) != "hello" || fetchedURL != "https://example.test/ok" {
+ t.Fatalf("fetch blob = %q, url = %q", blob, fetchedURL)
+ }
+}
+
+func TestAirtableRecordsURL(t *testing.T) {
+ connector := newAirtableTestConnector()
+ connector.baseID = "base 1"
+ connector.tableNameOrID = "My Table"
+ got := connector.recordsURL("tok", 100)
+ if !strings.Contains(got, "/base%201/My%20Table?") || !strings.Contains(got, "pageSize=100") || !strings.Contains(got, "offset=tok") {
+ t.Fatalf("records URL = %q", got)
+ }
+}
+
+func TestAirtableDoJSONRetriesTransientStatus(t *testing.T) {
+ calls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ if calls == 1 {
+ w.WriteHeader(http.StatusTooManyRequests)
+ return
+ }
+ w.Write([]byte(`{"records":[]}`))
+ }))
+ defer server.Close()
+
+ connector := newAirtableTestConnector()
+ connector.apiBaseURL = server.URL + "/v0"
+ connector.httpClient = server.Client()
+ var page airtableRecordPage
+ if err := connector.doJSON(context.Background(), connector.recordsURL("", 1), &page); err != nil {
+ t.Fatalf("doJSON failed: %v", err)
+ }
+ if calls != 2 {
+ t.Fatalf("calls = %d, want 2", calls)
+ }
+}
+
+func TestAirtableDoJSONReadsBodyBeforeCancel(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ if flusher, ok := w.(http.Flusher); ok {
+ flusher.Flush()
+ }
+ time.Sleep(50 * time.Millisecond)
+ w.Write([]byte(`{"records":[]}`))
+ }))
+ defer server.Close()
+
+ connector := newAirtableTestConnector()
+ connector.apiBaseURL = server.URL + "/v0"
+ connector.httpClient = server.Client()
+ var page airtableRecordPage
+ if err := connector.doJSON(context.Background(), connector.recordsURL("", 1), &page); err != nil {
+ t.Fatalf("doJSON failed: %v", err)
+ }
+}
+
+func newAirtableTestConnector() *AirtableConnector {
+ return &AirtableConnector{
+ baseID: "base 1",
+ tableNameOrID: "My Table",
+ accessToken: "token",
+ batchSize: airtableDefaultBatchSize,
+ sizeThreshold: airtableDefaultSizeThreshold,
+ apiBaseURL: airtableAPIBaseURL,
+ httpClient: &http.Client{Timeout: time.Second},
+ }
+}
+
+func airtableTestRecord() airtableRecord {
+ return airtableRecord{
+ ID: "rec-1",
+ CreatedTime: "2026-01-02T03:04:05.000Z",
+ Fields: map[string]any{
+ "Attachments": []any{
+ map[string]any{"id": "att-1", "url": "https://example.test/a.pdf", "filename": "report.PDF", "size": float64(5), "type": "application/pdf"},
+ "not-an-attachment",
+ map[string]any{"id": "att-2", "url": "https://example.test/b.txt", "filename": "notes.txt", "size": float64(3)},
+ },
+ "Tags": []any{"one", "two"},
+ },
+ }
+}
+
+func airtableTestRecordWithIDTime(recordID, createdTime, filename string) airtableRecord {
+ return airtableRecord{
+ ID: recordID,
+ CreatedTime: createdTime,
+ Fields: map[string]any{
+ "Attachments": []any{
+ map[string]any{"id": "att-1", "url": "https://example.test/" + filename, "filename": filename, "size": float64(1)},
+ },
+ },
+ }
+}
+
+func airtableTestAttachment(filename string) airtableAttachment {
+ return airtableAttachment{
+ ID: "att-1",
+ URL: "https://example.test/" + filename,
+ Filename: filename,
+ Size: 1,
+ FieldName: "Attachments",
+ CreatedTime: "2026-01-03T00:00:00Z",
+ }
+}
+
+func airtableMustTimePointer(t *testing.T, value string) *time.Time {
+ t.Helper()
+ parsed := mustTime(t, value)
+ return &parsed
+}
diff --git a/internal/syncer/connector/builtin.go b/internal/syncer/connector/builtin.go
index 0a52456fcc..1aa32c2d3b 100644
--- a/internal/syncer/connector/builtin.go
+++ b/internal/syncer/connector/builtin.go
@@ -42,6 +42,7 @@ func RegisterBuiltIns(registry *Registry) {
registerBuiltIn(registry, "oci_storage", NewOCIStorageConnector)
registerBuiltIn(registry, "zendesk", NewZendeskConnector)
registerBuiltIn(registry, "azure_blob", NewAzureBlobStorageConnector)
+ registerBuiltIn(registry, "airtable", NewAirtableConnector)
registerBuiltIn(registry, "r2", NewR2Connector)
registerBuiltIn(registry, "s3", NewS3Connector)
registerBuiltIn(registry, "s3_compatible", NewS3CompatibleConnector)
diff --git a/internal/syncer/connector/outlook.go b/internal/syncer/connector/outlook.go
index 4966d5c459..f4556a5148 100644
--- a/internal/syncer/connector/outlook.go
+++ b/internal/syncer/connector/outlook.go
@@ -213,12 +213,13 @@ func (c *OutlookConnector) getJSON(ctx context.Context, apiURL string, out any)
req.Header.Set("Authorization", "Bearer "+token)
resp, err := c.httpClient.Do(req)
- cancel()
if err != nil {
+ cancel()
lastErr = err
} else {
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 16*1024*1024))
resp.Body.Close()
+ cancel()
if resp.StatusCode < 400 {
if readErr != nil {
return readErr
diff --git a/internal/syncer/connector/outlook_test.go b/internal/syncer/connector/outlook_test.go
index dcb3efd4af..64fc68eeb3 100644
--- a/internal/syncer/connector/outlook_test.go
+++ b/internal/syncer/connector/outlook_test.go
@@ -5,6 +5,7 @@ import (
"errors"
"io"
"net/http"
+ "net/http/httptest"
"strings"
"testing"
"time"
@@ -197,6 +198,34 @@ func TestOutlookGetJSONRetriesTransientStatus(t *testing.T) {
}
}
+func TestOutlookGetJSONReadsBodyBeforeCancel(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ if flusher, ok := w.(http.Flusher); ok {
+ flusher.Flush()
+ }
+ time.Sleep(50 * time.Millisecond)
+ w.Write([]byte(`{"value":[]}`))
+ }))
+ defer server.Close()
+
+ connector := &OutlookConnector{
+ tenantID: "tenant",
+ clientID: "client",
+ clientSecret: "secret",
+ batchSize: 1,
+ httpClient: server.Client(),
+ acquireAccessToken: func(ctx context.Context) (string, error) {
+ return "token", nil
+ },
+ }
+ var page outlookDeltaPage
+ if err := connector.getJSON(context.Background(), server.URL+"/messages", &page); err != nil {
+ t.Fatalf("getJSON failed: %v", err)
+ }
+}
+
func TestOutlookTokenRefreshesExpiredCachedToken(t *testing.T) {
now := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
tokenCalls := 0
diff --git a/internal/syncer/connector/teams.go b/internal/syncer/connector/teams.go
index c7163c0fe5..c33d30ce98 100644
--- a/internal/syncer/connector/teams.go
+++ b/internal/syncer/connector/teams.go
@@ -349,12 +349,13 @@ func (c *TeamsConnector) getJSON(ctx context.Context, apiURL string, out any) er
client := utility.PinnedHTTPClient(hostname, resolvedIP, teamsRequestTimeout)
resp, err := client.Do(req)
- cancel()
if err != nil {
+ cancel()
lastErr = err
} else {
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 32*1024*1024))
resp.Body.Close()
+ cancel()
if resp.StatusCode < 400 {
if readErr != nil {
return readErr
diff --git a/internal/syncer/connector/teams_test.go b/internal/syncer/connector/teams_test.go
index d9b5d40d68..e80b20c587 100644
--- a/internal/syncer/connector/teams_test.go
+++ b/internal/syncer/connector/teams_test.go
@@ -21,9 +21,12 @@ import (
"errors"
"io"
"net/http"
+ "net/http/httptest"
"strings"
"testing"
"time"
+
+ "ragflow/internal/utility"
)
func TestNewTeamsConnectorDefaults(t *testing.T) {
@@ -110,6 +113,39 @@ func TestTeamsConnectorValidateQueriesTeams(t *testing.T) {
}
}
+func TestTeamsGetJSONReadsBodyBeforeCancel(t *testing.T) {
+ previousAllowAnyHost := utility.AllowAnyHostForTest
+ utility.AllowAnyHostForTest = true
+ t.Cleanup(func() { utility.AllowAnyHostForTest = previousAllowAnyHost })
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ if flusher, ok := w.(http.Flusher); ok {
+ flusher.Flush()
+ }
+ time.Sleep(50 * time.Millisecond)
+ w.Write([]byte(`{"value":[]}`))
+ }))
+ defer server.Close()
+
+ connector := &TeamsConnector{
+ tenantID: "tenant",
+ clientID: "client",
+ clientSecret: "secret",
+ batchSize: defaultTeamsBatchSize,
+ httpClient: http.DefaultClient,
+ now: time.Now,
+ acquireAccessToken: func(ctx context.Context) (string, error) {
+ return "token", nil
+ },
+ }
+ var page teamsPage
+ if err := connector.getJSON(context.Background(), server.URL+"/teams", &page); err != nil {
+ t.Fatalf("getJSON failed: %v", err)
+ }
+}
+
func TestTeamsConnectorValidateMapsHTTPStatus(t *testing.T) {
cases := []struct {
name string