dify/api/events/event_handlers/create_document_index.py
Harsh Kashyap 31bb8abbf1
fix(api): stop swallowing document indexing errors in create handler (#38192)
Co-authored-by: Harsh Kashyap <Harsh23Kashyap@users.noreply.github.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Harsh Kashyap <harshkashyap@Harshs-MacBook-Pro.local>
Co-authored-by: yunlu.wen <yunlu.wen@dify.ai>
2026-07-02 06:29:56 +00:00

53 lines
1.8 KiB
Python

import logging
import time
import click
from sqlalchemy import select
from werkzeug.exceptions import NotFound
from core.db.session_factory import session_factory
from core.indexing_runner import DocumentIsPausedError, IndexingRunner
from events.document_index_event import document_index_created
from libs.datetime_utils import naive_utc_now
from models.dataset import Document
from models.enums import IndexingStatus
logger = logging.getLogger(__name__)
@document_index_created.connect
def handle(sender, **kwargs):
dataset_id = sender
document_ids = kwargs.get("document_ids", [])
documents = []
start_at = time.perf_counter()
with session_factory.create_session() as session:
for document_id in document_ids:
logger.info(click.style(f"Start process document: {document_id}", fg="green"))
document = session.scalar(
select(Document).where(
Document.id == document_id,
Document.dataset_id == dataset_id,
)
)
if not document:
raise NotFound("Document not found")
document.indexing_status = IndexingStatus.PARSING
document.processing_started_at = naive_utc_now()
documents.append(document)
session.add(document)
session.commit()
try:
indexing_runner = IndexingRunner()
indexing_runner.run(documents)
end_at = time.perf_counter()
logger.info(click.style(f"Processed dataset: {dataset_id} latency: {end_at - start_at}", fg="green"))
except DocumentIsPausedError as ex:
logger.info(click.style(str(ex), fg="yellow"))
except Exception:
logger.exception("Document index event handler failed, dataset_id: %s", dataset_id)