938 lines
33 KiB
Python
938 lines
33 KiB
Python
from __future__ import annotations
|
|
|
|
import base64
|
|
import uuid
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
import app.tasks as task_module
|
|
from app.config import get_settings
|
|
from app.database import SessionLocal
|
|
from app.models import DifySyncRecord, Document, DocumentVersion, Group, Job, User
|
|
from app.services.dify_service import DifyError
|
|
from app.services.storage_service import version_dir
|
|
|
|
|
|
def _seed_document_version(
|
|
*,
|
|
source_filename: str = "policy.docx",
|
|
title: str = "policy",
|
|
convert_status: str = "queued",
|
|
sync_status: str = "unsynced",
|
|
markdown_text: str | None = None,
|
|
) -> tuple[int, int, int, int]:
|
|
db = SessionLocal()
|
|
try:
|
|
admin = db.query(User).filter(User.username == "admin").first()
|
|
assert admin is not None
|
|
|
|
group = Group(name=f"group-{uuid.uuid4().hex[:8]}", description="Task coverage", created_by_id=admin.id, department_id=1)
|
|
db.add(group)
|
|
db.commit()
|
|
db.refresh(group)
|
|
|
|
document = Document(group_id=group.id, title=title, created_by_id=admin.id, is_deleted=False)
|
|
db.add(document)
|
|
db.commit()
|
|
db.refresh(document)
|
|
|
|
source_root = version_dir("original", group.id, document.id, 1)
|
|
source_root.mkdir(parents=True, exist_ok=True)
|
|
source_path = source_root / source_filename
|
|
source_path.write_bytes(b"source document")
|
|
|
|
version = DocumentVersion(
|
|
document_id=document.id,
|
|
version_no=1,
|
|
is_current=True,
|
|
source_filename=source_filename,
|
|
source_ext=Path(source_filename).suffix.lower(),
|
|
source_path=str(source_path),
|
|
source_sha256=uuid.uuid4().hex,
|
|
file_size=source_path.stat().st_size,
|
|
uploader_id=admin.id,
|
|
convert_status=convert_status,
|
|
sync_status=sync_status,
|
|
)
|
|
db.add(version)
|
|
db.commit()
|
|
db.refresh(version)
|
|
|
|
if markdown_text is not None:
|
|
markdown_root = version_dir("markdown", group.id, document.id, version.version_no)
|
|
markdown_root.mkdir(parents=True, exist_ok=True)
|
|
markdown_path = markdown_root / "document.md"
|
|
markdown_path.write_text(markdown_text, encoding="utf-8")
|
|
version.md_path = str(markdown_path)
|
|
db.commit()
|
|
|
|
return group.id, document.id, version.id, admin.id
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def _seed_job(
|
|
*,
|
|
job_type: str,
|
|
group_id: int,
|
|
document_id: int,
|
|
version_id: int,
|
|
created_by_id: int,
|
|
) -> str:
|
|
db = SessionLocal()
|
|
try:
|
|
job = Job(
|
|
id=str(uuid.uuid4()),
|
|
job_type=job_type,
|
|
status="queued",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=created_by_id,
|
|
payload={},
|
|
)
|
|
db.add(job)
|
|
db.commit()
|
|
return job.id
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def _seed_document_for_delete(*, with_remote_sync: bool) -> tuple[int, int, int, int, Path, Path, Path]:
|
|
settings = get_settings()
|
|
db = SessionLocal()
|
|
try:
|
|
admin = db.query(User).filter(User.username == "admin").first()
|
|
assert admin is not None
|
|
|
|
group = Group(
|
|
name=f"delete-{uuid.uuid4().hex[:8]}",
|
|
description="Delete coverage",
|
|
created_by_id=admin.id,
|
|
department_id=1,
|
|
)
|
|
db.add(group)
|
|
db.commit()
|
|
db.refresh(group)
|
|
|
|
document = Document(group_id=group.id, title="manual", created_by_id=admin.id, is_deleted=True)
|
|
db.add(document)
|
|
db.commit()
|
|
db.refresh(document)
|
|
|
|
source_root = version_dir("original", group.id, document.id, 1)
|
|
markdown_root = version_dir("markdown", group.id, document.id, 1)
|
|
assets_root = version_dir("assets", group.id, document.id, 1)
|
|
source_root.mkdir(parents=True, exist_ok=True)
|
|
markdown_root.mkdir(parents=True, exist_ok=True)
|
|
assets_root.mkdir(parents=True, exist_ok=True)
|
|
|
|
source_path = source_root / "manual.docx"
|
|
markdown_path = markdown_root / "document.md"
|
|
asset_path = assets_root / "img_001.png"
|
|
source_path.write_bytes(b"source")
|
|
markdown_path.write_text("# Manual", encoding="utf-8")
|
|
asset_path.write_bytes(b"png")
|
|
|
|
version = DocumentVersion(
|
|
document_id=document.id,
|
|
version_no=1,
|
|
is_current=True,
|
|
source_filename="manual.docx",
|
|
source_ext=".docx",
|
|
source_path=str(source_path),
|
|
source_sha256=uuid.uuid4().hex,
|
|
md_path=str(markdown_path),
|
|
md_public_url="http://testserver/storage/markdown/document.md",
|
|
asset_dir=str(assets_root.relative_to(settings.data_root)),
|
|
file_size=source_path.stat().st_size,
|
|
uploader_id=admin.id,
|
|
convert_status="success",
|
|
sync_status="synced" if with_remote_sync else "unsynced",
|
|
)
|
|
db.add(version)
|
|
db.commit()
|
|
db.refresh(version)
|
|
|
|
if with_remote_sync:
|
|
db.add(
|
|
DifySyncRecord(
|
|
version_id=version.id,
|
|
dataset_id="dataset-001",
|
|
remote_document_id="remote-001",
|
|
status="synced",
|
|
)
|
|
)
|
|
db.commit()
|
|
|
|
return group.id, document.id, version.id, admin.id, source_root, markdown_root, assets_root
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def test_convert_job_success_updates_version_and_job(db_session, monkeypatch):
|
|
group_id, document_id, version_id, admin_id = _seed_document_version()
|
|
job_id = _seed_job(
|
|
job_type="convert",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=admin_id,
|
|
)
|
|
|
|
monkeypatch.setattr(task_module.SystemConfig, "load", staticmethod(lambda _: object()))
|
|
|
|
def fake_build_knowledge(source_path, output_dir, config, cache_dir):
|
|
generated_dir = output_dir / "generated"
|
|
generated_dir.mkdir(parents=True, exist_ok=True)
|
|
(generated_dir / "document.md").write_text("# Policy\n\nConverted content", encoding="utf-8")
|
|
return [{"status": "success"}]
|
|
|
|
monkeypatch.setattr(task_module, "build_knowledge", fake_build_knowledge)
|
|
|
|
task_module.run_convert_job(job_id, version_id)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
|
|
job = db.query(Job).filter(Job.id == job_id).first()
|
|
assert version is not None
|
|
assert job is not None
|
|
assert version.convert_status == "success"
|
|
assert version.sync_status == "unsynced"
|
|
assert version.md_path is not None
|
|
assert Path(version.md_path).exists()
|
|
assert Path(version.md_path).read_text(encoding="utf-8") == "# Policy\n\nConverted content"
|
|
assert version.word_count == 4
|
|
assert version.warnings_json == [{"message": "embedded_images=0"}]
|
|
assert job.status == "success"
|
|
assert job.message == "Conversion completed"
|
|
assert job.result == {
|
|
"md_path": version.md_path,
|
|
"md_public_url": version.md_public_url,
|
|
"image_count": 0,
|
|
}
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def test_convert_job_success_rewrites_embedded_images_to_local_asset_urls(db_session, monkeypatch):
|
|
group_id, document_id, version_id, admin_id = _seed_document_version()
|
|
job_id = _seed_job(
|
|
job_type="convert",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=admin_id,
|
|
)
|
|
|
|
monkeypatch.setattr(task_module.SystemConfig, "load", staticmethod(lambda _: object()))
|
|
|
|
def fake_build_knowledge(source_path, output_dir, config, cache_dir):
|
|
generated_dir = output_dir / "generated"
|
|
generated_dir.mkdir(parents=True, exist_ok=True)
|
|
image_bytes = base64.b64encode(b"fake-image").decode("ascii")
|
|
markdown = f"# Policy\n\n"
|
|
(generated_dir / "document.md").write_text(markdown, encoding="utf-8")
|
|
return [{"status": "success"}]
|
|
|
|
monkeypatch.setattr(task_module, "build_knowledge", fake_build_knowledge)
|
|
|
|
task_module.run_convert_job(job_id, version_id)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
|
|
assert version is not None
|
|
assert version.asset_dir is not None
|
|
assert version.md_path is not None
|
|
markdown = Path(version.md_path).read_text(encoding="utf-8")
|
|
assert "http://testserver/storage/assets/" in markdown
|
|
assert "data:image" not in markdown
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def test_convert_job_failure_marks_job_and_version_failed(db_session, monkeypatch):
|
|
group_id, document_id, version_id, admin_id = _seed_document_version()
|
|
job_id = _seed_job(
|
|
job_type="convert",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=admin_id,
|
|
)
|
|
|
|
monkeypatch.setattr(task_module.SystemConfig, "load", staticmethod(lambda _: object()))
|
|
monkeypatch.setattr(
|
|
task_module,
|
|
"build_knowledge",
|
|
lambda source_path, output_dir, config, cache_dir: [{"status": "failed", "error": "converter exploded"}],
|
|
)
|
|
|
|
with pytest.raises(RuntimeError, match="converter exploded"):
|
|
task_module.run_convert_job(job_id, version_id)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
|
|
job = db.query(Job).filter(Job.id == job_id).first()
|
|
assert version is not None
|
|
assert job is not None
|
|
assert version.convert_status == "failed"
|
|
assert version.failed_reason == "converter exploded"
|
|
assert job.status == "failed"
|
|
assert job.message == "Conversion failed"
|
|
assert job.error == "converter exploded"
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def test_sync_job_success_creates_sync_record_and_marks_document_synced(db_session, monkeypatch):
|
|
group_id, document_id, version_id, admin_id = _seed_document_version(
|
|
convert_status="success",
|
|
sync_status="unsynced",
|
|
markdown_text="# Policy\n\nReady for sync",
|
|
)
|
|
job_id = _seed_job(
|
|
job_type="sync",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=admin_id,
|
|
)
|
|
|
|
class FakeDifyService:
|
|
def ensure_dataset(self, **kwargs):
|
|
return "dataset-001"
|
|
|
|
def create_document_by_text(
|
|
self,
|
|
*,
|
|
dataset_id: str,
|
|
name: str,
|
|
text: str,
|
|
doc_form: str,
|
|
indexing_technique: str,
|
|
) -> dict:
|
|
assert dataset_id == "dataset-001"
|
|
assert name == "policy"
|
|
assert "Ready for sync" in text
|
|
assert indexing_technique == "high_quality"
|
|
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
|
|
|
|
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
|
|
raise AssertionError("update_document_by_text should not be called for a first sync")
|
|
|
|
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
|
|
assert dataset_id == "dataset-001"
|
|
assert batch == "batch-001"
|
|
return {"indexing_status": "completed"}
|
|
|
|
def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict:
|
|
raise AssertionError("get_document_detail should not be called when batch exists")
|
|
|
|
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
|
|
|
|
task_module.run_sync_job(job_id, version_id)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
|
|
group = db.query(Group).filter(Group.id == group_id).first()
|
|
job = db.query(Job).filter(Job.id == job_id).first()
|
|
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all()
|
|
assert version is not None
|
|
assert group is not None
|
|
assert job is not None
|
|
assert group.dify_dataset_id == "dataset-001"
|
|
assert version.sync_status == "synced"
|
|
assert len(records) == 1
|
|
assert records[0].remote_document_id == "remote-001"
|
|
assert records[0].status == "synced"
|
|
assert records[0].last_indexing_status == "completed"
|
|
assert job.status == "success"
|
|
assert job.message == "Dify sync completed"
|
|
assert job.result == {
|
|
"dataset_id": "dataset-001",
|
|
"remote_document_id": "remote-001",
|
|
"batch": "batch-001",
|
|
"indexing_status": "completed",
|
|
}
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def test_sync_job_success_without_batch_waits_for_document_completion(db_session, monkeypatch):
|
|
group_id, document_id, version_id, admin_id = _seed_document_version(
|
|
convert_status="success",
|
|
sync_status="unsynced",
|
|
markdown_text="# Policy\n\nReady for sync",
|
|
)
|
|
job_id = _seed_job(
|
|
job_type="sync",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=admin_id,
|
|
)
|
|
|
|
class FakeDifyService:
|
|
def ensure_dataset(self, **kwargs):
|
|
return "dataset-001"
|
|
|
|
def create_document_by_text(
|
|
self,
|
|
*,
|
|
dataset_id: str,
|
|
name: str,
|
|
text: str,
|
|
doc_form: str,
|
|
indexing_technique: str,
|
|
) -> dict:
|
|
assert dataset_id == "dataset-001"
|
|
assert name == "policy"
|
|
return {"document": {"id": "remote-001"}}
|
|
|
|
def wait_for_document_indexing(self, *, dataset_id: str, document_id: str, timeout_seconds: int = 300) -> dict:
|
|
assert dataset_id == "dataset-001"
|
|
assert document_id == "remote-001"
|
|
return {"indexing_status": "completed"}
|
|
|
|
def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict:
|
|
raise AssertionError("get_document_detail should not be called directly in no-batch mode")
|
|
|
|
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
|
|
|
|
task_module.run_sync_job(job_id, version_id)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
|
|
job = db.query(Job).filter(Job.id == job_id).first()
|
|
record = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).first()
|
|
assert version is not None
|
|
assert job is not None
|
|
assert record is not None
|
|
assert version.sync_status == "synced"
|
|
assert record.status == "synced"
|
|
assert record.batch is None
|
|
assert record.last_indexing_status == "completed"
|
|
assert job.status == "success"
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def test_sync_job_reuses_existing_no_batch_sync_record_and_waits_for_completion(db_session, monkeypatch):
|
|
group_id, document_id, version_id, admin_id = _seed_document_version(
|
|
convert_status="success",
|
|
sync_status="syncing",
|
|
markdown_text="# Policy\n\nReady for sync",
|
|
)
|
|
job_id = _seed_job(
|
|
job_type="sync",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=admin_id,
|
|
)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
db.add(
|
|
DifySyncRecord(
|
|
version_id=version_id,
|
|
dataset_id="dataset-001",
|
|
remote_document_id="remote-existing",
|
|
batch=None,
|
|
status="syncing",
|
|
)
|
|
)
|
|
db.commit()
|
|
finally:
|
|
db.close()
|
|
|
|
class FakeDifyService:
|
|
def ensure_dataset(self, **kwargs):
|
|
return "dataset-001"
|
|
|
|
def create_document_by_text(self, **kwargs) -> dict:
|
|
raise AssertionError("create_document_by_text should not be called when an in-flight sync record exists")
|
|
|
|
def wait_for_document_indexing(self, *, dataset_id: str, document_id: str, timeout_seconds: int = 300) -> dict:
|
|
assert dataset_id == "dataset-001"
|
|
assert document_id == "remote-existing"
|
|
return {"indexing_status": "completed_with_warning"}
|
|
|
|
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
|
|
|
|
task_module.run_sync_job(job_id, version_id)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
|
|
job = db.query(Job).filter(Job.id == job_id).first()
|
|
record = (
|
|
db.query(DifySyncRecord)
|
|
.filter(DifySyncRecord.version_id == version_id)
|
|
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
|
|
.first()
|
|
)
|
|
assert version is not None
|
|
assert job is not None
|
|
assert record is not None
|
|
assert version.sync_status == "synced"
|
|
assert record.status == "synced"
|
|
assert record.last_indexing_status == "completed_with_warning"
|
|
assert job.status == "success"
|
|
assert job.result["remote_document_id"] == "remote-existing"
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def test_delete_document_job_removes_local_storage_and_remote_dify_document(db_session, monkeypatch):
|
|
group_id, document_id, version_id, admin_id, source_root, markdown_root, assets_root = _seed_document_for_delete(
|
|
with_remote_sync=True
|
|
)
|
|
job_id = _seed_job(
|
|
job_type="delete",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=admin_id,
|
|
)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
job = db.query(Job).filter(Job.id == job_id).first()
|
|
assert job is not None
|
|
job.payload = {"delete_dify": True}
|
|
db.commit()
|
|
finally:
|
|
db.close()
|
|
|
|
delete_calls: list[tuple[str, str]] = []
|
|
|
|
class FakeDifyService:
|
|
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
|
|
delete_calls.append((dataset_id, document_id))
|
|
|
|
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
|
|
|
|
task_module.run_delete_document_job(job_id, document_id)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
job = db.query(Job).filter(Job.id == job_id).first()
|
|
assert job is not None
|
|
assert job.status == "success"
|
|
assert job.message == "Document delete completed"
|
|
assert job.result == {"deleted": True, "delete_dify": True, "remote_document_count": 1}
|
|
finally:
|
|
db.close()
|
|
|
|
assert delete_calls == [("dataset-001", "remote-001")]
|
|
assert not source_root.exists()
|
|
assert not markdown_root.exists()
|
|
assert not assets_root.exists()
|
|
|
|
|
|
def test_sync_job_failure_marks_existing_sync_record_failed(db_session, monkeypatch):
|
|
group_id, document_id, version_id, admin_id = _seed_document_version(
|
|
convert_status="success",
|
|
sync_status="unsynced",
|
|
markdown_text="# Policy\n\nReady for sync",
|
|
)
|
|
job_id = _seed_job(
|
|
job_type="sync",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=admin_id,
|
|
)
|
|
|
|
class FakeDifyService:
|
|
def ensure_dataset(self, **kwargs):
|
|
return "dataset-001"
|
|
|
|
def create_document_by_text(
|
|
self,
|
|
*,
|
|
dataset_id: str,
|
|
name: str,
|
|
text: str,
|
|
doc_form: str,
|
|
indexing_technique: str,
|
|
) -> dict:
|
|
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
|
|
|
|
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
|
|
raise AssertionError("update_document_by_text should not be called for a first sync")
|
|
|
|
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
|
|
raise DifyError("Indexing failed with status=failed")
|
|
|
|
def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]:
|
|
assert dataset_id == "dataset-001"
|
|
assert batch == "batch-001"
|
|
return [{"indexing_status": "failed", "display_status": "error"}]
|
|
|
|
def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict:
|
|
raise AssertionError("get_document_detail should not be called when batch exists")
|
|
|
|
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
|
|
|
|
with pytest.raises(DifyError, match="status=failed"):
|
|
task_module.run_sync_job(job_id, version_id)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
|
|
job = db.query(Job).filter(Job.id == job_id).first()
|
|
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all()
|
|
assert version is not None
|
|
assert job is not None
|
|
assert version.sync_status == "sync_failed"
|
|
assert job.status == "failed"
|
|
assert job.message == "Dify sync failed"
|
|
assert "status=failed" in job.error
|
|
assert len(records) == 1
|
|
assert records[0].status == "sync_failed"
|
|
assert "status=failed" in records[0].error
|
|
assert records[0].last_indexing_status == "failed"
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def test_sync_job_keeps_local_asset_urls_when_syncing_to_dify(db_session, monkeypatch):
|
|
local_asset_url = (
|
|
f"http://testserver/storage/assets/group_{1:04d}/document_{1:06d}/v001/img_001_deadbeef.jpg"
|
|
)
|
|
group_id, document_id, version_id, admin_id = _seed_document_version(
|
|
convert_status="success",
|
|
sync_status="unsynced",
|
|
markdown_text=f"# Policy\n\n",
|
|
)
|
|
job_id = _seed_job(
|
|
job_type="sync",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=admin_id,
|
|
)
|
|
|
|
class FakeDifyService:
|
|
def ensure_dataset(self, **kwargs):
|
|
return "dataset-001"
|
|
|
|
def create_document_by_text(self, *, dataset_id, name, text, doc_form, indexing_technique):
|
|
assert local_asset_url in text
|
|
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
|
|
|
|
def wait_for_indexing(self, *, dataset_id, batch, timeout_seconds=300):
|
|
return {"indexing_status": "completed"}
|
|
|
|
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
|
|
|
|
task_module.run_sync_job(job_id, version_id)
|
|
|
|
|
|
def test_sync_job_recreates_remote_document_when_previous_sync_record_exists(db_session, monkeypatch):
|
|
group_id, document_id, version_id, admin_id = _seed_document_version(
|
|
convert_status="success",
|
|
sync_status="sync_failed",
|
|
markdown_text="# Policy\n\nReady for resync",
|
|
)
|
|
job_id = _seed_job(
|
|
job_type="sync",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=admin_id,
|
|
)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
db.add(
|
|
DifySyncRecord(
|
|
version_id=version_id,
|
|
dataset_id="dataset-001",
|
|
remote_document_id="remote-old",
|
|
status="sync_failed",
|
|
)
|
|
)
|
|
db.commit()
|
|
finally:
|
|
db.close()
|
|
|
|
class FakeDifyService:
|
|
def __init__(self):
|
|
self.deleted: list[tuple[str, str]] = []
|
|
|
|
def ensure_dataset(self, **kwargs):
|
|
return "dataset-001"
|
|
|
|
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
|
|
self.deleted.append((dataset_id, document_id))
|
|
|
|
def create_document_by_text(
|
|
self,
|
|
*,
|
|
dataset_id: str,
|
|
name: str,
|
|
text: str,
|
|
doc_form: str,
|
|
indexing_technique: str,
|
|
) -> dict:
|
|
assert dataset_id == "dataset-001"
|
|
assert name == "policy"
|
|
assert "Ready for resync" in text
|
|
return {"document": {"id": "remote-new"}, "batch": "batch-new"}
|
|
|
|
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
|
|
raise AssertionError("update_document_by_text should not be called during resync")
|
|
|
|
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
|
|
assert dataset_id == "dataset-001"
|
|
assert batch == "batch-new"
|
|
return {"indexing_status": "completed"}
|
|
|
|
def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict:
|
|
raise AssertionError("get_document_detail should not be called when batch exists")
|
|
|
|
service = FakeDifyService()
|
|
monkeypatch.setattr(task_module, "DifyService", lambda: service)
|
|
|
|
task_module.run_sync_job(job_id, version_id)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
|
|
job = db.query(Job).filter(Job.id == job_id).first()
|
|
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).order_by(DifySyncRecord.id).all()
|
|
assert version is not None
|
|
assert job is not None
|
|
assert version.sync_status == "synced"
|
|
assert service.deleted == [("dataset-001", "remote-old")]
|
|
assert len(records) == 2
|
|
assert records[-1].remote_document_id == "remote-new"
|
|
assert records[-1].status == "synced"
|
|
assert job.status == "success"
|
|
assert job.result == {
|
|
"dataset_id": "dataset-001",
|
|
"remote_document_id": "remote-new",
|
|
"batch": "batch-new",
|
|
"indexing_status": "completed",
|
|
}
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def test_sync_job_retryable_dify_error_requeues_instead_of_failing(db_session, monkeypatch):
|
|
group_id, document_id, version_id, admin_id = _seed_document_version(
|
|
convert_status="success",
|
|
sync_status="unsynced",
|
|
markdown_text="# Policy\n\nReady for sync",
|
|
)
|
|
job_id = _seed_job(
|
|
job_type="sync",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=admin_id,
|
|
)
|
|
|
|
class SettingsStub:
|
|
task_execution_mode = "rq"
|
|
dify_sync_max_retries = 4
|
|
dify_sync_cooldown_seconds = 20
|
|
|
|
@staticmethod
|
|
def dify_sync_retry_delays():
|
|
return [15, 30, 60]
|
|
|
|
class FakeQueue:
|
|
def __init__(self):
|
|
self.calls: list[tuple[int, str, tuple]] = []
|
|
|
|
def enqueue_in(self, delay, task_name, *args, **kwargs):
|
|
self.calls.append((int(delay.total_seconds()), task_name, args))
|
|
return SimpleNamespace(id="rq-retry-1")
|
|
|
|
class FakeDifyService:
|
|
def ensure_dataset(self, **kwargs):
|
|
return "dataset-001"
|
|
|
|
def create_document_by_text(
|
|
self,
|
|
*,
|
|
dataset_id: str,
|
|
name: str,
|
|
text: str,
|
|
doc_form: str,
|
|
indexing_technique: str,
|
|
) -> dict:
|
|
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
|
|
|
|
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
|
|
raise DifyError("FATAL: sorry, too many clients already")
|
|
|
|
def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]:
|
|
return [{"indexing_status": "waiting", "display_status": "queuing"}]
|
|
|
|
queue = FakeQueue()
|
|
cooldowns: list[tuple[str, int]] = []
|
|
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
|
|
monkeypatch.setattr(task_module, "get_queue", lambda: queue)
|
|
monkeypatch.setattr(task_module, "get_settings", lambda: SettingsStub())
|
|
monkeypatch.setattr(task_module, "get_delay_gate_ttl", lambda name: 0)
|
|
monkeypatch.setattr(task_module, "set_delay_gate", lambda name, ttl: cooldowns.append((name, ttl)))
|
|
|
|
task_module.run_sync_job(job_id, version_id)
|
|
|
|
assert queue.calls == [(15, "app.tasks.run_sync_job", (job_id, version_id))]
|
|
assert cooldowns == [(task_module.DIFY_SYNC_COOLDOWN_GATE, 20)]
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
|
|
job = db.query(Job).filter(Job.id == job_id).first()
|
|
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all()
|
|
assert version is not None
|
|
assert job is not None
|
|
assert version.sync_status == "syncing"
|
|
assert job.status == "queued"
|
|
assert job.queue_job_id == "rq-retry-1"
|
|
assert job.payload["sync_retry_count"] == 1
|
|
assert job.payload["sync_retry_after_seconds"] == 15
|
|
assert "too many clients already" in job.payload["sync_last_error"]
|
|
assert job.message == "Dify busy, retrying in 15s (attempt 1/4)."
|
|
assert job.error is None
|
|
assert len(records) == 1
|
|
assert records[0].status == "syncing"
|
|
assert "too many clients already" in records[0].error
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def test_sync_job_retryable_dify_error_fails_cleanly_in_sync_mode(db_session, monkeypatch):
|
|
group_id, document_id, version_id, admin_id = _seed_document_version(
|
|
convert_status="success",
|
|
sync_status="unsynced",
|
|
markdown_text="# Policy\n\nReady for sync",
|
|
)
|
|
job_id = _seed_job(
|
|
job_type="sync",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=admin_id,
|
|
)
|
|
|
|
class SettingsStub:
|
|
task_execution_mode = "sync"
|
|
dify_sync_max_retries = 4
|
|
dify_sync_cooldown_seconds = 20
|
|
|
|
@staticmethod
|
|
def dify_sync_retry_delays():
|
|
return [15, 30, 60]
|
|
|
|
class FakeDifyService:
|
|
def ensure_dataset(self, **kwargs):
|
|
return "dataset-001"
|
|
|
|
def create_document_by_text(
|
|
self,
|
|
*,
|
|
dataset_id: str,
|
|
name: str,
|
|
text: str,
|
|
doc_form: str,
|
|
indexing_technique: str,
|
|
) -> dict:
|
|
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
|
|
|
|
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
|
|
raise DifyError("FATAL: sorry, too many clients already")
|
|
|
|
def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]:
|
|
return [{"indexing_status": "waiting", "display_status": "queuing"}]
|
|
|
|
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
|
|
monkeypatch.setattr(task_module, "get_settings", lambda: SettingsStub())
|
|
monkeypatch.setattr(task_module, "get_delay_gate_ttl", lambda name: 0)
|
|
|
|
with pytest.raises(DifyError, match="too many clients already"):
|
|
task_module.run_sync_job(job_id, version_id)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
|
|
job = db.query(Job).filter(Job.id == job_id).first()
|
|
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all()
|
|
assert version is not None
|
|
assert job is not None
|
|
assert version.sync_status == "sync_failed"
|
|
assert job.status == "failed"
|
|
assert job.queue_job_id is None
|
|
assert job.error is not None and "too many clients already" in job.error
|
|
assert len(records) == 1
|
|
assert records[0].status == "sync_failed"
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def test_sync_job_defers_during_dify_cooldown_without_calling_dify(db_session, monkeypatch):
|
|
group_id, document_id, version_id, admin_id = _seed_document_version(
|
|
convert_status="success",
|
|
sync_status="syncing",
|
|
markdown_text="# Policy\n\nReady for sync",
|
|
)
|
|
job_id = _seed_job(
|
|
job_type="sync",
|
|
group_id=group_id,
|
|
document_id=document_id,
|
|
version_id=version_id,
|
|
created_by_id=admin_id,
|
|
)
|
|
|
|
class FakeQueue:
|
|
def __init__(self):
|
|
self.calls: list[tuple[int, str, tuple]] = []
|
|
|
|
def enqueue_in(self, delay, task_name, *args, **kwargs):
|
|
self.calls.append((int(delay.total_seconds()), task_name, args))
|
|
return SimpleNamespace(id="rq-retry-2")
|
|
|
|
invoked = {"count": 0}
|
|
|
|
class FakeDifyService:
|
|
def __init__(self):
|
|
invoked["count"] += 1
|
|
|
|
queue = FakeQueue()
|
|
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
|
|
monkeypatch.setattr(task_module, "get_queue", lambda: queue)
|
|
monkeypatch.setattr(task_module, "get_delay_gate_ttl", lambda name: 45)
|
|
|
|
task_module.run_sync_job(job_id, version_id)
|
|
|
|
assert invoked["count"] == 0
|
|
assert queue.calls == [(45, "app.tasks.run_sync_job", (job_id, version_id))]
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
|
|
job = db.query(Job).filter(Job.id == job_id).first()
|
|
assert version is not None
|
|
assert job is not None
|
|
assert version.sync_status == "syncing"
|
|
assert job.status == "queued"
|
|
assert job.queue_job_id == "rq-retry-2"
|
|
assert job.message == "Dify cooldown active, retrying in 45s."
|
|
finally:
|
|
db.close()
|