Skip to content

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

Fix Dataset ingestion overview (#20190)

adws1f835d20635f
diff --git a/internal/dao/document.go b/internal/dao/document.go
index e0f114edba..9a512e5bd3 100644
--- a/internal/dao/document.go
+++ b/internal/dao/document.go
@@ -506,6 +506,19 @@ func (dao *DocumentDAO) CountByTenantID(ctx context.Context, db *gorm.DB, tenant
return count, err
}
+// CountByKBAndSourceTypes counts documents from the selected sources in one dataset.
+func (dao *DocumentDAO) CountByKBAndSourceTypes(ctx context.Context, db *gorm.DB, kbID string, sourceTypes []string) (int64, error) {
+ if len(sourceTypes) == 0 {
+ return 0, nil
+ }
+
+ var count int64
+ err := db.WithContext(ctx).Model(&entity.Document{}).
+ Where("kb_id = ? AND source_type IN ?", kbID, sourceTypes).
+ Count(&count).Error
+ return count, err
+}
+
// SumSizeByDatasetID returns the total document size for a dataset.
func (dao *DocumentDAO) SumSizeByDatasetID(ctx context.Context, db *gorm.DB, datasetID string) (int64, error) {
var total int64
diff --git a/internal/dao/sync_task.go b/internal/dao/sync_task.go
index 8d791a2e7c..17f9a284b6 100644
--- a/internal/dao/sync_task.go
+++ b/internal/dao/sync_task.go
@@ -81,6 +81,34 @@ func (d *SyncTaskDAO) DB() *gorm.DB {
return d.db
}
+// ListDatasetSyncTasks returns running sync tasks and the latest non-scheduled
+// sync task for each connector still linked to the dataset. Newest rows come first.
+func (d *SyncTaskDAO) ListDatasetSyncTasks(ctx context.Context, datasetID string) ([]entity.SyncLogs, error) {
+ var tasks []entity.SyncLogs
+ err := d.db.WithContext(ctx).Raw(`
+ SELECT id, connector_id, kb_id, status, new_docs_indexed, error_count, error_class, update_time
+ FROM (
+ SELECT sync_logs.id, sync_logs.connector_id, sync_logs.kb_id, sync_logs.status,
+ sync_logs.new_docs_indexed, sync_logs.error_count, sync_logs.error_class, sync_logs.update_time,
+ ROW_NUMBER() OVER (
+ PARTITION BY sync_logs.connector_id
+ ORDER BY COALESCE(sync_logs.update_time, 0) DESC, sync_logs.id DESC
+ ) AS row_num
+ FROM sync_logs
+ WHERE sync_logs.kb_id = ? AND sync_logs.task_type = ? AND sync_logs.status <> ?
+ AND EXISTS (
+ SELECT 1 FROM connector2kb
+ WHERE connector2kb.connector_id = sync_logs.connector_id
+ AND connector2kb.kb_id = sync_logs.kb_id
+ )
+ ) AS ranked
+ WHERE status = ? OR row_num = 1
+ ORDER BY COALESCE(update_time, 0) DESC, id DESC`,
+ datasetID, TaskTypeSync, SyncStatusSchedule, SyncStatusRunning).
+ Scan(&tasks).Error
+ return tasks, err
+}
+
type dueSyncTaskRow struct {
entity.SyncLogs
ConnectorRefreshFreq int64 `gorm:"column:connector_refresh_freq"`
diff --git a/internal/dao/sync_task_test.go b/internal/dao/sync_task_test.go
index 5d5b607f39..28a6f99383 100644
--- a/internal/dao/sync_task_test.go
+++ b/internal/dao/sync_task_test.go
@@ -51,6 +51,52 @@ func setupSyncTaskTestDB(t *testing.T) *gorm.DB {
return db
}
+func TestListDatasetSyncTasksKeepsRunningAndLatestPerConnector(t *testing.T) {
+ db := setupSyncTaskTestDB(t)
+ if err := db.AutoMigrate(&entity.Connector2Kb{}); err != nil {
+ t.Fatalf("migrate connector links: %v", err)
+ }
+ links := []entity.Connector2Kb{
+ {ID: "link-a", ConnectorID: "connector-a", KbID: "dataset-1"},
+ {ID: "link-a-duplicate", ConnectorID: "connector-a", KbID: "dataset-1"},
+ {ID: "link-b", ConnectorID: "connector-b", KbID: "dataset-1"},
+ {ID: "link-other", ConnectorID: "connector-unlinked", KbID: "dataset-2"},
+ }
+ if err := db.Create(&links).Error; err != nil {
+ t.Fatalf("create connector links: %v", err)
+ }
+ task := func(id, connectorID, status string, updateTime int64) entity.SyncLogs {
+ return entity.SyncLogs{
+ ID: id, ConnectorID: connectorID, KbID: "dataset-1", TaskType: TaskTypeSync, Status: status,
+ BaseModel: entity.BaseModel{UpdateTime: &updateTime},
+ }
+ }
+ tasks := []entity.SyncLogs{
+ task("a-done-old", "connector-a", SyncStatusDone, 100),
+ task("a-running", "connector-a", SyncStatusRunning, 200),
+ task("a-done-new", "connector-a", SyncStatusDone, 300),
+ task("b-running", "connector-b", SyncStatusRunning, 250),
+ task("unlinked", "connector-unlinked", SyncStatusRunning, 400),
+ }
+ if err := db.Create(&tasks).Error; err != nil {
+ t.Fatalf("create sync tasks: %v", err)
+ }
+
+ got, err := NewSyncTaskDAO(db).ListDatasetSyncTasks(context.Background(), "dataset-1")
+ if err != nil {
+ t.Fatalf("list dataset sync tasks: %v", err)
+ }
+ wantIDs := []string{"a-done-new", "b-running", "a-running"}
+ if len(got) != len(wantIDs) {
+ t.Fatalf("task count = %d, want %d: %+v", len(got), len(wantIDs), got)
+ }
+ for i, wantID := range wantIDs {
+ if got[i].ID != wantID {
+ t.Fatalf("task %d = %q, want %q", i, got[i].ID, wantID)
+ }
+ }
+}
+
func insertRunningSyncTask(t *testing.T, db *gorm.DB, taskID string, errorCount, retryCount int64, errorClass string) {
t.Helper()
if err := db.Create(&entity.SyncLogs{
diff --git a/internal/service/dataset/ingestion.go b/internal/service/dataset/ingestion.go
index 323012da99..16e97ce661 100644
--- a/internal/service/dataset/ingestion.go
+++ b/internal/service/dataset/ingestion.go
@@ -9,6 +9,9 @@ import (
"ragflow/internal/dao"
"ragflow/internal/entity"
"ragflow/internal/service"
+ syncerconnector "ragflow/internal/syncer/connector"
+
+ "go.uber.org/zap"
)
const (
@@ -16,6 +19,16 @@ const (
maxIngestionMessagesLimit = 500
)
+type syncCheckpointLoader interface {
+ LoadSyncCheckpoint(ctx context.Context, taskID string) (*syncerconnector.SyncCheckpointState, error)
+}
+
+type downloadStatus struct {
+ RunningCount int64 `json:"running_count"`
+ DoneCount int64 `json:"done_count"`
+ FailCount int64 `json:"fail_count"`
+}
+
// IngestionMessagesResponse is one immutable run's keyset-paginated event
// stream. IDs are database event IDs and must be returned unchanged by clients
// when requesting adjacent pages.
@@ -49,15 +62,88 @@ func (d *DatasetService) GetIngestionSummary(ctx context.Context, datasetID, use
if err != nil {
return nil, common.CodeServerError, errors.New("database operation failed")
}
+ downloadStatus, err := d.getDownloadStatus(ctx, datasetID)
+ if err != nil {
+ return nil, common.CodeServerError, errors.New("database operation failed")
+ }
return map[string]interface{}{
- "doc_num": kb.DocNum,
- "chunk_num": kb.ChunkNum,
- "token_num": kb.TokenNum,
- "status": status,
+ "doc_num": kb.DocNum,
+ "chunk_num": kb.ChunkNum,
+ "token_num": kb.TokenNum,
+ "status": status,
+ "download_status": downloadStatus,
}, common.CodeSuccess, nil
}
+func (d *DatasetService) getDownloadStatus(ctx context.Context, datasetID string) (downloadStatus, error) {
+ connectors, err := d.connectorDAO.ListByDatasetID(ctx, dao.DB, datasetID)
+ if err != nil {
+ return downloadStatus{}, err
+ }
+ if len(connectors) == 0 {
+ return downloadStatus{}, nil
+ }
+
+ sourceTypes := make([]string, 0, len(connectors))
+ for _, connector := range connectors {
+ sourceTypes = append(sourceTypes, service.SourceType(connector.Source, connector.ID))
+ }
+ doneCount, err := d.documentDAO.CountByKBAndSourceTypes(ctx, dao.DB, datasetID, sourceTypes)
+ if err != nil {
+ return downloadStatus{}, err
+ }
+
+ tasks, err := d.syncTaskDAO.ListDatasetSyncTasks(ctx, datasetID)
+ if err != nil {
+ return downloadStatus{}, err
+ }
+
+ status := downloadStatus{DoneCount: doneCount}
+ latestByConnector := make(map[string]entity.SyncLogs, len(connectors))
+ runningErrors := make(map[string]int64)
+ loadCheckpoints := d.checkpointLoader != nil
+ for _, task := range tasks {
+ if _, ok := latestByConnector[task.ConnectorID]; !ok {
+ latestByConnector[task.ConnectorID] = task
+ }
+ if task.Status != dao.SyncStatusRunning {
+ continue
+ }
+
+ // Go's retry path also increments error_count for source-level errors.
+ // Without a checkpoint, those retries cannot be counted as file failures.
+ if task.ErrorClass == "" {
+ runningErrors[task.ID] = task.ErrorCount
+ }
+ runningCount := task.NewDocsIndexed - runningErrors[task.ID]
+ if runningCount < 0 {
+ runningCount = 0
+ }
+ if loadCheckpoints {
+ checkpoint, loadErr := d.checkpointLoader.LoadSyncCheckpoint(ctx, task.ID)
+ if loadErr != nil {
+ common.Warn("load dataset download checkpoint failed", zap.String("task_id", task.ID), zap.Error(loadErr))
+ loadCheckpoints = false
+ } else if checkpoint != nil && checkpoint.TaskID == task.ID && checkpoint.ConnectorID == task.ConnectorID && checkpoint.KBID == datasetID {
+ runningCount = checkpoint.Added + checkpoint.Updated
+ runningErrors[task.ID] = checkpoint.ErrorCount
+ }
+ }
+ status.RunningCount += runningCount
+ }
+
+ for _, task := range latestByConnector {
+ switch task.Status {
+ case dao.SyncStatusRunning:
+ status.FailCount += runningErrors[task.ID]
+ case dao.SyncStatusDone:
+ status.FailCount += task.ErrorCount
+ }
+ }
+ return status, nil
+}
+
// ListIngestionMessages returns events owned by the requested immutable
// pipeline log.
func (d *DatasetService) ListIngestionMessages(ctx context.Context, datasetID, userID, logID string, limit int, afterID, beforeID *int) (*IngestionMessagesResponse, common.ErrorCode, error) {
diff --git a/internal/service/dataset/ingestion_summary_test.go b/internal/service/dataset/ingestion_summary_test.go
new file mode 100644
index 0000000000..14fa0a70ab
--- /dev/null
+++ b/internal/service/dataset/ingestion_summary_test.go
@@ -0,0 +1,97 @@
+package dataset
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "ragflow/internal/dao"
+ "ragflow/internal/entity"
+ syncerconnector "ragflow/internal/syncer/connector"
+)
+
+type fakeSyncCheckpointLoader struct {
+ states map[string]*syncerconnector.SyncCheckpointState
+ err error
+}
+
+func (f fakeSyncCheckpointLoader) LoadSyncCheckpoint(_ context.Context, taskID string) (*syncerconnector.SyncCheckpointState, error) {
+ return f.states[taskID], f.err
+}
+
+func TestGetDownloadStatusAggregatesLinkedConnectorFiles(t *testing.T) {
+ db := setupServiceTestDB(t)
+ pushServiceDB(t, db)
+
+ connectors := []entity.Connector{
+ {ID: "connector-checkpoint", TenantID: "tenant-1", Name: "checkpoint", Source: "rss", InputType: "poll", Config: entity.JSONMap{}, Status: dao.SyncStatusSchedule},
+ {ID: "connector-fallback", TenantID: "tenant-1", Name: "fallback", Source: "s3", InputType: "poll", Config: entity.JSONMap{}, Status: dao.SyncStatusSchedule},
+ {ID: "connector-source-fail", TenantID: "tenant-1", Name: "source-fail", Source: "notion", InputType: "poll", Config: entity.JSONMap{}, Status: dao.SyncStatusSchedule},
+ {ID: "connector-unlinked", TenantID: "tenant-1", Name: "unlinked", Source: "webdav", InputType: "poll", Config: entity.JSONMap{}, Status: dao.SyncStatusSchedule},
+ }
+ if err := db.Create(&connectors).Error; err != nil {
+ t.Fatalf("create connectors: %v", err)
+ }
+ mappings := []entity.Connector2Kb{
+ {ID: "mapping-checkpoint", ConnectorID: "connector-checkpoint", KbID: "dataset-1"},
+ {ID: "mapping-fallback", ConnectorID: "connector-fallback", KbID: "dataset-1"},
+ {ID: "mapping-source-fail", ConnectorID: "connector-source-fail", KbID: "dataset-1"},
+ }
+ if err := db.Create(&mappings).Error; err != nil {
+ t.Fatalf("create connector mappings: %v", err)
+ }
+
+ documents := []entity.Document{
+ {ID: "doc-rss", KbID: "dataset-1", ParserID: "naive", ParserConfig: entity.JSONMap{}, SourceType: "rss/connector-checkpoint", Type: "text", CreatedBy: "tenant-1", Name: sptr("rss.txt"), Suffix: "txt"},
+ {ID: "doc-s3", KbID: "dataset-1", ParserID: "naive", ParserConfig: entity.JSONMap{}, SourceType: "s3/connector-fallback", Type: "text", CreatedBy: "tenant-1", Name: sptr("s3.txt"), Suffix: "txt"},
+ {ID: "doc-local", KbID: "dataset-1", ParserID: "naive", ParserConfig: entity.JSONMap{}, SourceType: "local", Type: "text", CreatedBy: "tenant-1", Name: sptr("local.txt"), Suffix: "txt"},
+ {ID: "doc-unlinked", KbID: "dataset-1", ParserID: "naive", ParserConfig: entity.JSONMap{}, SourceType: "webdav/connector-unlinked", Type: "text", CreatedBy: "tenant-1", Name: sptr("unlinked.txt"), Suffix: "txt"},
+ }
+ if err := db.Create(&documents).Error; err != nil {
+ t.Fatalf("create documents: %v", err)
+ }
+
+ tasks := []entity.SyncLogs{
+ {ID: "task-checkpoint", ConnectorID: "connector-checkpoint", KbID: "dataset-1", TaskType: dao.TaskTypeSync, Status: dao.SyncStatusRunning, NewDocsIndexed: 1, BaseModel: entity.BaseModel{UpdateTime: downloadInt64Pointer(600)}},
+ {ID: "task-fallback", ConnectorID: "connector-fallback", KbID: "dataset-1", TaskType: dao.TaskTypeSync, Status: dao.SyncStatusRunning, NewDocsIndexed: 5, ErrorCount: 2, BaseModel: entity.BaseModel{UpdateTime: downloadInt64Pointer(500)}},
+ {ID: "task-source-retry", ConnectorID: "connector-source-fail", KbID: "dataset-1", TaskType: dao.TaskTypeSync, Status: dao.SyncStatusRunning, ErrorCount: 9, ErrorClass: "transient", BaseModel: entity.BaseModel{UpdateTime: downloadInt64Pointer(450)}},
+ {ID: "task-source-fail", ConnectorID: "connector-source-fail", KbID: "dataset-1", TaskType: dao.TaskTypeSync, Status: dao.SyncStatusFail, ErrorCount: 9, BaseModel: entity.BaseModel{UpdateTime: downloadInt64Pointer(400)}},
+ {ID: "task-scheduled", ConnectorID: "connector-checkpoint", KbID: "dataset-1", TaskType: dao.TaskTypeSync, Status: dao.SyncStatusSchedule, NewDocsIndexed: 100, BaseModel: entity.BaseModel{UpdateTime: downloadInt64Pointer(900)}},
+ {ID: "task-prune", ConnectorID: "connector-fallback", KbID: "dataset-1", TaskType: dao.TaskTypePrune, Status: dao.SyncStatusRunning, NewDocsIndexed: 100, BaseModel: entity.BaseModel{UpdateTime: downloadInt64Pointer(800)}},
+ }
+ if err := db.Create(&tasks).Error; err != nil {
+ t.Fatalf("create sync tasks: %v", err)
+ }
+
+ svc := NewDatasetService()
+ svc.checkpointLoader = fakeSyncCheckpointLoader{states: map[string]*syncerconnector.SyncCheckpointState{
+ "task-checkpoint": {
+ TaskID: "task-checkpoint",
+ ConnectorID: "connector-checkpoint",
+ KBID: "dataset-1",
+ Added: 2,
+ Updated: 1,
+ },
+ }}
+
+ status, err := svc.getDownloadStatus(context.Background(), "dataset-1")
+ if err != nil {
+ t.Fatalf("get download status: %v", err)
+ }
+ if status.RunningCount != 6 || status.DoneCount != 2 || status.FailCount != 2 {
+ t.Fatalf("download status = %+v, want running=6 done=2 fail=2", status)
+ }
+
+ svc.checkpointLoader = fakeSyncCheckpointLoader{err: errors.New("checkpoint unavailable")}
+ status, err = svc.getDownloadStatus(context.Background(), "dataset-1")
+ if err != nil {
+ t.Fatalf("get download status after checkpoint error: %v", err)
+ }
+ if status.RunningCount != 4 || status.DoneCount != 2 || status.FailCount != 2 {
+ t.Fatalf("fallback download status = %+v, want running=4 done=2 fail=2", status)
+ }
+}
+
+func downloadInt64Pointer(value int64) *int64 {
+ return &value
+}
diff --git a/internal/service/dataset/service.go b/internal/service/dataset/service.go
index 4cc6774b6d..9249006472 100644
--- a/internal/service/dataset/service.go
+++ b/internal/service/dataset/service.go
@@ -11,16 +11,18 @@ import (
// DatasetService implements the RESTful dataset APIs.
type DatasetService struct {
- kbDAO *dao.KnowledgebaseDAO
- documentDAO *dao.DocumentDAO
- connectorDAO *dao.ConnectorDAO
- tenantDAO *dao.TenantDAO
- pipelineLogDAO *dao.PipelineOperationLogDAO
- userTenantDAO *dao.UserTenantDAO
- taskDAO *dao.TaskDAO
- searchService *service.SearchService
- docEngine engine.DocEngine
- embeddingCache *utility.EmbeddingLRU
+ kbDAO *dao.KnowledgebaseDAO
+ documentDAO *dao.DocumentDAO
+ connectorDAO *dao.ConnectorDAO
+ tenantDAO *dao.TenantDAO
+ pipelineLogDAO *dao.PipelineOperationLogDAO
+ userTenantDAO *dao.UserTenantDAO
+ taskDAO *dao.TaskDAO
+ syncTaskDAO *dao.SyncTaskDAO
+ searchService *service.SearchService
+ docEngine engine.DocEngine
+ embeddingCache *utility.EmbeddingLRU
+ checkpointLoader syncCheckpointLoader
// tagVocabularyLoader resolves the selectable-tag vocabulary for a tag
// source file (parser_config.tags.tag_file_id). It is a field so tests can
// inject a fake; in production it defaults to
@@ -32,7 +34,7 @@ type DatasetService struct {
// NewDatasetService creates a new datasets service.
func NewDatasetService() *DatasetService {
- return &DatasetService{
+ datasetService := &DatasetService{
kbDAO: dao.NewKnowledgebaseDAO(),
documentDAO: dao.NewDocumentDAO(),
connectorDAO: dao.NewConnectorDAO(),
@@ -40,8 +42,13 @@ func NewDatasetService() *DatasetService {
pipelineLogDAO: dao.NewPipelineOperationLogDAO(),
userTenantDAO: dao.NewUserTenantDAO(),
taskDAO: dao.NewTaskDAO(),
+ syncTaskDAO: dao.NewSyncTaskDAO(nil),
searchService: service.NewSearchService(),
docEngine: engine.Get(),
embeddingCache: utility.NewEmbeddingLRU(1000),
}
+ if loader, ok := engine.GetMessageQueueEngine().(syncCheckpointLoader); ok {
+ datasetService.checkpointLoader = loader
+ }
+ return datasetService
}
diff --git a/test/testcases/restful_api/test_document_raw_routes.py b/test/testcases/restful_api/test_document_raw_routes.py
index 41d53599f4..a4c7d48c66 100644
--- a/test/testcases/restful_api/test_document_raw_routes.py
+++ b/test/testcases/restful_api/test_document_raw_routes.py
@@ -15,6 +15,7 @@
#
import pytest
+
from test.testcases.configs import INVALID_API_TOKEN, IS_GO_PROXY
from test.testcases.restful_api.helpers.assertions import assert_auth_error
from test.testcases.restful_api.helpers.client import RestClient
diff --git a/web/src/pages/dataset/dataset-overview/__tests__/utils.test.ts b/web/src/pages/dataset/dataset-overview/__tests__/utils.test.ts
new file mode 100644
index 0000000000..61eae771da
--- /dev/null
+++ b/web/src/pages/dataset/dataset-overview/__tests__/utils.test.ts
@@ -0,0 +1,54 @@
+import type { IFileLogList } from '../interface';
+import { buildDatasetOverviewStats, hasActiveIngestionLogs } from '../utils';
+
+const Summary = {
+ doc_num: 9,
+ chunk_num: 20,
+ token_num: 200,
+ status: {
+ unstart_count: 1,
+ running_count: 2,
+ cancel_count: 1,
+ done_count: 4,
+ fail_count: 1,
+ },
+};
+
+describe('dataset overview helpers', () => {
+ it('maps the summary and defaults missing download counts to zero', () => {
+ expect(
+ buildDatasetOverviewStats({
+ ...Summary,
+ download_status: {
+ running_count: 3,
+ done_count: 5,
+ fail_count: 2,
+ },
+ }),
+ ).toEqual({
+ totalFiles: 9,
+ downloads: { value: 3, success: 5, failed: 2 },
+ processing: { value: 2, success: 4, failed: 1 },
+ });
+ expect(buildDatasetOverviewStats(Summary).downloads).toEqual({
+ value: 0,
+ success: 0,
+ failed: 0,
+ });
+ });
+
+ it('recognizes active ingestion logs', () => {
+ expect(
+ hasActiveIngestionLogs({
+ logs: [{ operation_status: 'RUNNING' } as IFileLogList['logs'][number]],
+ total: 1,
+ }),
+ ).toBe(true);
+ expect(
+ hasActiveIngestionLogs({
+ logs: [{ operation_status: 'DONE' } as IFileLogList['logs'][number]],
+ total: 1,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/web/src/pages/dataset/dataset-overview/hook.ts b/web/src/pages/dataset/dataset-overview/hook.ts
index 3e451e304f..0270f1c6c5 100644
--- a/web/src/pages/dataset/dataset-overview/hook.ts
+++ b/web/src/pages/dataset/dataset-overview/hook.ts
@@ -12,18 +12,35 @@ import { useCallback, useState } from 'react';
import { useParams, useSearchParams } from 'react-router';
import { LogTabs } from './dataset-common';
import { IFileLogList, IOverviewTotal } from './interface';
+import { DatasetOverviewKeys, hasActiveIngestionLogs } from './utils';
+
+const PollIntervalMs = 5000;
+const EmptyOverviewSummary: IOverviewTotal = {
+ doc_num: 0,
+ chunk_num: 0,
+ token_num: 0,
+ status: {
+ unstart_count: 0,
+ running_count: 0,
+ cancel_count: 0,
+ done_count: 0,
+ fail_count: 0,
+ },
+};
const useFetchOverviewTotal = () => {
const [searchParams] = useSearchParams();
const { id } = useParams();
const knowledgeBaseId = searchParams.get('id') || id;
const { data } = useQuery<IOverviewTotal>({
- queryKey: ['overviewTotal'],
+ queryKey: DatasetOverviewKeys.summary(knowledgeBaseId),
+ enabled: !!knowledgeBaseId,
+ refetchInterval: PollIntervalMs,
queryFn: async () => {
const { data: res = {} } = await getKnowledgeBasicInfo(
knowledgeBaseId || '',
);
- return res.data || [];
+ return res.data || EmptyOverviewSummary;
},
});
return { data };
@@ -42,21 +59,23 @@ const useFetchFileLogList = () => {
const knowledgeBaseId = searchParams.get('id') || id;
const logType = active === LogTabs.DATASET_LOGS ? 'dataset' : 'file';
const { data } = useQuery<IFileLogList>({
- queryKey: [
- 'fileLogList',
+ queryKey: DatasetOverviewKeys.logs(
knowledgeBaseId,
- pagination,
+ pagination.current,
+ pagination.pageSize,
searchString,
active,
filterValue,
- ],
+ ),
placeholderData: (previousData) => {
if (previousData === undefined) {
return { logs: [], total: 0 };
}
return previousData;
},
- enabled: true,
+ enabled: !!knowledgeBaseId,
+ refetchInterval: (query) =>
+ hasActiveIngestionLogs(query.state.data) ? PollIntervalMs : false,
queryFn: async () => {
const { data: res = {} } = await listDataPipelineLogDocument(
knowledgeBaseId || '',
@@ -68,7 +87,7 @@ const useFetchFileLogList = () => {
...filterValue,
},
);
- return res.data || [];
+ return res.data || { logs: [], total: 0 };
},
});
const onInputChange: React.ChangeEventHandler<HTMLInputElement> = useCallback(
@@ -82,7 +101,7 @@ const useFetchFileLogList = () => {
data,
searchString,
handleInputChange: onInputChange,
- pagination: { ...pagination, total: data?.total },
+ pagination: { ...pagination, total: data?.total ?? 0 },
setPagination,
active,
setActive,
diff --git a/web/src/pages/dataset/dataset-overview/index.tsx b/web/src/pages/dataset/dataset-overview/index.tsx
index 3826ee2572..7b8ccd2c53 100644
--- a/web/src/pages/dataset/dataset-overview/index.tsx
+++ b/web/src/pages/dataset/dataset-overview/index.tsx
@@ -11,8 +11,7 @@ import {
import WhatIsThis from '@/components/what-is-this';
import { RunningStatusMap, RunningStatusOld } from '@/constants/knowledge';
-import { useFetchDocumentList } from '@/hooks/use-document-request';
-import { FC, useEffect, useMemo, useState } from 'react';
+import { FC, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { RunningStatus } from '../dataset/constant';
import { LogTabs } from './dataset-common';
@@ -20,6 +19,7 @@ import { DatasetFilter } from './dataset-filter';
import { useFetchFileLogList, useFetchOverviewTotal } from './hook';
import { DocumentLog, IFileLogItem } from './interface';
import FileLogsTable from './overview-table';
+import { buildDatasetOverviewStats } from './utils';
interface StatCardProps {
title: string;
@@ -116,56 +116,8 @@ const CardFooterProcess: FC<CardFooterProcessProps> = ({
const FileLogsPage: FC = () => {
const { t } = useTranslation();
-
- const [topAllData, setTopAllData] = useState({
- totalFiles: {
- value: 0,
- precent: 0,
- },
- downloads: {
- value: 0,
- success: 0,
- failed: 0,
- },
- processing: {
- value: 0,
- success: 0,
- failed: 0,
- },
- });
const { data: topData } = useFetchOverviewTotal();
- const {
- pagination: { total: fileTotal },
- } = useFetchDocumentList(false);
-
- useEffect(() => {
- setTopAllData((prev) => {
- return {
- ...prev,
- downloads: {
- ...prev.downloads,
- success: topData?.downloaded || 0,
- },
- processing: {
- value: topData?.processing || 0,
- success: topData?.finished || 0,
- failed: topData?.failed || 0,
- },
- };
- });
- }, [topData]);
-
- useEffect(() => {
- setTopAllData((prev) => {
- return {
- ...prev,
- totalFiles: {
- value: fileTotal || 0,
- precent: 0,
- },
- };
- });
- }, [fileTotal]);
+ const overviewStats = buildDatasetOverviewStats(topData);
const {
data: tableOriginData,
@@ -213,7 +165,7 @@ const FileLogsPage: FC = () => {
return filterCollection;
}
if (active === LogTabs.DATASET_LOGS) {
- const list = filterCollection.filter((item, index) => index === 0);
+ const list = filterCollection.filter((_, index) => index === 0);
return list;
}
return [];
@@ -262,7 +214,7 @@ const FileLogsPage: FC = () => {
<div className="grid grid-cols-3 md:grid-cols-3 gap-7 mb-6">
<StatCard
title={t('datasetOverview.totalFiles')}
- value={topAllData.totalFiles.value}
+ value={overviewStats.totalFiles}
icon={
isDark ? (
<SvgIcon name="data-flow/total-files-icon" width={40} />
@@ -272,10 +224,7 @@ const FileLogsPage: FC = () => {
}
>
<div className="text-xs">
- <span className="text-accent-primary">
- {topAllData.totalFiles.precent > 0 ? '+' : ''}
- {topAllData.totalFiles.precent}%{' '}
- </span>
+ <span className="text-accent-primary">0% </span>
<span className="font-normal text-text-secondary">
{t('knowledgeConfiguration.lastWeek')}
</span>
@@ -283,7 +232,7 @@ const FileLogsPage: FC = () => {
</StatCard>
<StatCard
title={t('datasetOverview.downloading')}
- value={topAllData.downloads.value}
+ value={overviewStats.downloads.value}
icon={
isDark ? (
<SvgIcon name="data-flow/data-icon" width={40} />
@@ -294,15 +243,15 @@ const FileLogsPage: FC = () => {
tooltip={t('datasetOverview.downloadTip')}
>
<CardFooterProcess
- success={topAllData.downloads.success}
+ success={overviewStats.downloads.success}
successTip={t('datasetOverview.downloadSuccessTip')}
- failed={topAllData.downloads.failed}
+ failed={overviewStats.downloads.failed}
failedTip={t('datasetOverview.downloadFailedTip')}
/>
</StatCard>
<StatCard
title={t('datasetOverview.processing')}
- value={topAllData.processing.value}
+ value={overviewStats.processing.value}
icon={
isDark ? (
<SvgIcon name="data-flow/processing-icon" width={40} />
@@ -313,9 +262,9 @@ const FileLogsPage: FC = () => {
tooltip={t('datasetOverview.processingTip')}
>
<CardFooterProcess
- success={topAllData.processing.success}
+ success={overviewStats.processing.success}
successTip={t('datasetOverview.processingSuccessTip')}
- failed={topAllData.processing.failed}
+ failed={overviewStats.processing.failed}
failedTip={t('datasetOverview.processingFailedTip')}
/>
</StatCard>
diff --git a/web/src/pages/dataset/dataset-overview/interface.ts b/web/src/pages/dataset/dataset-overview/interface.ts
index 2071740adc..52641a9798 100644
--- a/web/src/pages/dataset/dataset-overview/interface.ts
+++ b/web/src/pages/dataset/dataset-overview/interface.ts
@@ -22,11 +22,21 @@ export interface FileLogsTableProps {
}
export interface IOverviewTotal {
- cancelled: number;
- failed: number;
- finished: number;
- processing: number;
- downloaded: number;
+ doc_num: number;
+ chunk_num: number;
+ token_num: number;
+ status: {
+ unstart_count: number;
+ running_count: number;
+ cancel_count: number;
+ done_count: number;
+ fail_count: number;
+ };
+ download_status?: {
+ running_count: number;
+ done_count: number;
+ fail_count: number;
+ };
}
export interface IFileLogItem {
diff --git a/web/src/pages/dataset/dataset-overview/utils.ts b/web/src/pages/dataset/dataset-overview/utils.ts
new file mode 100644
index 0000000000..508ce96776
--- /dev/null
+++ b/web/src/pages/dataset/dataset-overview/utils.ts
@@ -0,0 +1,52 @@
+import { LogTabs } from './dataset-common';
+import { IFileLogList, IOverviewTotal } from './interface';
+
+const ActiveLogStatuses = new Set([
+ 'UNSTART',
+ 'RUNNING',
+ 'SCHEDULE',
+ '0',
+ '1',
+ '5',
+]);
+
+export const DatasetOverviewKeys = {
+ summary: (datasetId?: string) =>
+ ['datasetOverview', datasetId, 'summary'] as const,
+ logs: (
+ datasetId: string | undefined,
+ page: number | undefined,
+ pageSize: number | undefined,
+ searchString: string,
+ active: (typeof LogTabs)[keyof typeof LogTabs],
+ filterValue: Record<string, unknown>,
+ ) =>
+ [
+ 'datasetOverview',
+ datasetId,
+ 'logs',
+ page,
+ pageSize,
+ searchString,
+ active,
+ filterValue,
+ ] as const,
+};
+
+export const buildDatasetOverviewStats = (summary?: IOverviewTotal) => ({
+ totalFiles: summary?.doc_num ?? 0,
+ downloads: {
+ value: summary?.download_status?.running_count ?? 0,
+ success: summary?.download_status?.done_count ?? 0,
+ failed: summary?.download_status?.fail_count ?? 0,
+ },
+ processing: {
+ value: summary?.status.running_count ?? 0,
+ success: summary?.status.done_count ?? 0,
+ failed: summary?.status.fail_count ?? 0,
+ },
+});
+
+export const hasActiveIngestionLogs = (logs?: IFileLogList) =>
+ logs?.logs.some((log) => ActiveLogStatuses.has(log.operation_status)) ??
+ false;