mirror of
https://github.com/langgenius/dify.git
synced 2026-11-29 08:08:26 +08:00
refactor(logs): clarify export interfaces and task routing
This commit is contained in:
1 parent
4f73cd5bdd
commit
f17536253f
12 files changed
+63
-54
No files matched your search
@@ -89,9 +89,9 @@ class Storage:
|
||||
def save(self, filename: str, data: bytes):
|
||||
self.storage_runner.save(filename, data)
|
||||
|
||||
def save_file(self, filename: str, source: Path) -> None:
|
||||
"""Upload a completed local file through the configured storage backend."""
|
||||
self.storage_runner.save_file(filename, source)
|
||||
def save_from_path(self, key: str, source: Path) -> None:
|
||||
"""Save the contents of a local file to a storage key."""
|
||||
self.storage_runner.save_from_path(key, source)
|
||||
|
||||
@overload
|
||||
def load(self, filename: str, /, *, stream: Literal[False] = False) -> bytes: ...
|
||||
|
||||
@@ -63,12 +63,12 @@ class AwsS3Storage(BaseStorage):
|
||||
self.client.put_object(Bucket=self.bucket_name, Key=filename, Body=data)
|
||||
|
||||
@override
|
||||
def save_file(self, filename: str, source: Path) -> None:
|
||||
def save_from_path(self, key: str, source: Path) -> None:
|
||||
"""Upload a completed local file with one multipart transfer at a time."""
|
||||
self.client.upload_file(
|
||||
str(source),
|
||||
self.bucket_name,
|
||||
filename,
|
||||
key,
|
||||
Config=TransferConfig(multipart_chunksize=8 * 1024 * 1024, max_concurrency=1, use_threads=False),
|
||||
)
|
||||
|
||||
|
||||
@@ -12,9 +12,9 @@ class BaseStorage(ABC):
|
||||
def save(self, filename: str, data: bytes):
|
||||
raise NotImplementedError
|
||||
|
||||
def save_file(self, filename: str, source: Path) -> None:
|
||||
def save_from_path(self, key: str, source: Path) -> None:
|
||||
"""Read a completed local file for backends that implement byte-oriented writes."""
|
||||
self.save(filename, source.read_bytes())
|
||||
self.save(key, source.read_bytes())
|
||||
|
||||
@abstractmethod
|
||||
def load_once(self, filename: str) -> bytes:
|
||||
|
||||
@@ -48,9 +48,9 @@ class OpenDALStorage(BaseStorage):
|
||||
logger.debug("file %s saved", filename)
|
||||
|
||||
@override
|
||||
def save_file(self, filename: str, source: Path) -> None:
|
||||
def save_from_path(self, key: str, source: Path) -> None:
|
||||
"""Copy a completed local file in chunks and finish the object before returning."""
|
||||
with source.open("rb") as input_file, self.op.open(path=filename, mode="wb") as target:
|
||||
with source.open("rb") as input_file, self.op.open(path=key, mode="wb") as target:
|
||||
shutil.copyfileobj(input_file, target, length=8 * 1024 * 1024)
|
||||
|
||||
@override
|
||||
|
||||
@@ -66,6 +66,11 @@ from services.installed_app_access_service import InstalledAppNotFoundError, Ins
|
||||
|
||||
_LOG_IDENTITY_SEARCH_LIMIT = 20
|
||||
_LOG_EXPORT_BATCH_SIZE = 500
|
||||
_CONSOLE_APP_MODES_BY_KIND: dict[ConsoleConversationKind, frozenset[AppMode]] = {
|
||||
"completion": frozenset({AppMode.COMPLETION}),
|
||||
"chat": frozenset({AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}),
|
||||
}
|
||||
_CONSOLE_LOG_APP_MODES = _CONSOLE_APP_MODES_BY_KIND["completion"] | _CONSOLE_APP_MODES_BY_KIND["chat"]
|
||||
|
||||
|
||||
class ConversationRepository:
|
||||
@@ -171,17 +176,17 @@ class ConversationRepository:
|
||||
def get_console_scope(
|
||||
self, context: RequestContext, app_id: str, *, kind: ConsoleConversationKind
|
||||
) -> ConsoleConversationScope:
|
||||
return self._get_console_scope(context, app_id, kind=kind)
|
||||
return self._get_console_scope(context, app_id, allowed_modes=_CONSOLE_APP_MODES_BY_KIND[kind])
|
||||
|
||||
def get_console_log_export_scope(self, context: RequestContext, app_id: str) -> ConsoleConversationScope:
|
||||
"""Resolve the owned conversation app's mode and the caller's time zone for log export."""
|
||||
return self._get_console_scope(context, app_id, kind=None)
|
||||
return self._get_console_scope(context, app_id, allowed_modes=_CONSOLE_LOG_APP_MODES)
|
||||
|
||||
def _get_console_scope(
|
||||
self, context: RequestContext, app_id: str, *, kind: ConsoleConversationKind | None
|
||||
self, context: RequestContext, app_id: str, *, allowed_modes: frozenset[AppMode]
|
||||
) -> ConsoleConversationScope:
|
||||
with self._session_factory() as session:
|
||||
app = self._get_console_app(session=session, context=context, app_id=app_id, kind=kind)
|
||||
app = self._get_console_app(session=session, context=context, app_id=app_id, allowed_modes=allowed_modes)
|
||||
account = session.get(Account, context.account_id)
|
||||
if account is None:
|
||||
raise NoPermissionError("The admitted account no longer exists.")
|
||||
@@ -235,7 +240,9 @@ class ConversationRepository:
|
||||
identity_id = None
|
||||
|
||||
with self._session_factory() as session:
|
||||
app = self._get_console_app(session=session, context=context, app_id=app_id, kind=None)
|
||||
app = self._get_console_app(
|
||||
session=session, context=context, app_id=app_id, allowed_modes=_CONSOLE_LOG_APP_MODES
|
||||
)
|
||||
visible_logs, _ = self._filter_console_conversations(
|
||||
select(Conversation.id),
|
||||
app_id=app.id,
|
||||
@@ -595,7 +602,9 @@ class ConversationRepository:
|
||||
self, context: RequestContext, app_id: str, conversation_id: str, *, kind: ConsoleConversationKind
|
||||
) -> ConsoleConversationDetailSource:
|
||||
with self._session_factory() as session:
|
||||
app = self._get_console_app(session=session, context=context, app_id=app_id, kind=kind)
|
||||
app = self._get_console_app(
|
||||
session=session, context=context, app_id=app_id, allowed_modes=_CONSOLE_APP_MODES_BY_KIND[kind]
|
||||
)
|
||||
conversation = self._get_console_conversation(
|
||||
session=session, app_id=app.id, conversation_id=conversation_id
|
||||
)
|
||||
@@ -641,7 +650,9 @@ class ConversationRepository:
|
||||
self, context: RequestContext, app_id: str, conversation_id: str, *, kind: ConsoleConversationKind
|
||||
) -> None:
|
||||
with self._session_factory.begin() as session:
|
||||
app = self._get_console_app(session=session, context=context, app_id=app_id, kind=kind)
|
||||
app = self._get_console_app(
|
||||
session=session, context=context, app_id=app_id, allowed_modes=_CONSOLE_APP_MODES_BY_KIND[kind]
|
||||
)
|
||||
self._get_console_conversation(session=session, app_id=app.id, conversation_id=conversation_id)
|
||||
session.execute(
|
||||
update(Conversation)
|
||||
@@ -813,7 +824,9 @@ class ConversationRepository:
|
||||
self, context: RequestContext, app_id: str, conversation_id: str, *, kind: ConsoleConversationKind
|
||||
) -> ConversationDeletion:
|
||||
with self._session_factory.begin() as session:
|
||||
app = self._get_console_app(session=session, context=context, app_id=app_id, kind=kind)
|
||||
app = self._get_console_app(
|
||||
session=session, context=context, app_id=app_id, allowed_modes=_CONSOLE_APP_MODES_BY_KIND[kind]
|
||||
)
|
||||
# Console log queries see all users; deletion still requires the
|
||||
# current account's Console conversation, as in the original API.
|
||||
conversation = self._get_conversation(
|
||||
@@ -928,14 +941,9 @@ class ConversationRepository:
|
||||
|
||||
@staticmethod
|
||||
def _get_console_app(
|
||||
*, session: Session, context: RequestContext, app_id: str, kind: ConsoleConversationKind | None
|
||||
*, session: Session, context: RequestContext, app_id: str, allowed_modes: frozenset[AppMode]
|
||||
) -> App:
|
||||
app = find_console_app(session, workspace_id=context.active_workspace_id, app_id=app_id)
|
||||
allowed_modes = {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}
|
||||
if kind == "completion":
|
||||
allowed_modes = {AppMode.COMPLETION}
|
||||
elif kind is None:
|
||||
allowed_modes.add(AppMode.COMPLETION)
|
||||
if app is None:
|
||||
raise ConsoleAppNotFoundError("App not found.")
|
||||
if app.mode not in allowed_modes:
|
||||
|
||||
@@ -18,13 +18,15 @@ from services.retention.log_export_task import (
|
||||
|
||||
|
||||
def dispatch_log_export[FiltersT](task: LogExportTask[FiltersT], *, export_kind: LogExportKind) -> None:
|
||||
"""Send only the IDs required to load a saved task and use its expiration for delivery."""
|
||||
"""Send the saved task's scope and log type, with its expiration for delivery."""
|
||||
from tasks.log_export_tasks import prepare_log_export_task
|
||||
|
||||
kwargs = {"tenant_id": task.tenant_id, "app_id": task.app_id, "task_id": task.task_id}
|
||||
# Keep Conversation submissions readable by workers running the previous version.
|
||||
if export_kind != LogExportKind.CONVERSATION:
|
||||
kwargs["export_kind"] = export_kind.value
|
||||
kwargs = {
|
||||
"tenant_id": task.tenant_id,
|
||||
"app_id": task.app_id,
|
||||
"task_id": task.task_id,
|
||||
"export_kind": export_kind.value,
|
||||
}
|
||||
prepare_log_export_task.apply_async(kwargs=kwargs, task_id=task.task_id, expires=task.expires_at)
|
||||
|
||||
|
||||
@@ -34,7 +36,7 @@ def store_log_export_csv(storage_key: str, write_csv: Callable[[TextIO], int]) -
|
||||
path = Path(directory) / "logs.csv"
|
||||
with path.open("w", encoding="utf-8", newline="") as output:
|
||||
row_count = write_csv(output)
|
||||
storage.save_file(storage_key, path)
|
||||
storage.save_from_path(storage_key, path)
|
||||
return row_count
|
||||
|
||||
|
||||
|
||||
@@ -10,12 +10,9 @@ from services.retention.log_export_task import LogExportKind
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Keep the existing task name and default for Conversation messages already on the queue.
|
||||
@shared_task(name="tasks.conversation_log_export_tasks.prepare_conversation_log_export_task", queue="retention")
|
||||
def prepare_log_export_task(
|
||||
*, tenant_id: str, app_id: str, task_id: str, export_kind: str = LogExportKind.CONVERSATION
|
||||
) -> None:
|
||||
"""Route a saved export to its service. Legacy messages without an export kind are Conversation tasks."""
|
||||
@shared_task(name="tasks.log_export_tasks.prepare_log_export_task", queue="retention")
|
||||
def prepare_log_export_task(*, tenant_id: str, app_id: str, task_id: str, export_kind: str) -> None:
|
||||
"""Route a saved export to the service for its log type."""
|
||||
services = application_services()
|
||||
match export_kind:
|
||||
case LogExportKind.CONVERSATION:
|
||||
|
||||
@@ -178,11 +178,11 @@ def export_client(
|
||||
files: dict[str, str] = {}
|
||||
storage = log_export_storage
|
||||
|
||||
def save_file(key: str, path: Path) -> None:
|
||||
def save_from_path(key: str, path: Path) -> None:
|
||||
"""Read the completed file while it is available for upload."""
|
||||
files[key] = path.read_text(encoding="utf-8-sig")
|
||||
|
||||
storage.save_file.side_effect = save_file
|
||||
storage.save_from_path.side_effect = save_from_path
|
||||
logs = WorkflowAppLogQueryService(logs=WorkflowAppLogQueryRepository(session_factory=sqlite_session_factory))
|
||||
app.extensions["application_services"] = _Services(
|
||||
workflow_app_logs=logs,
|
||||
@@ -380,7 +380,7 @@ def test_workflow_export_worker_uploads_once_and_marks_task_ready(export_client:
|
||||
)
|
||||
assert row["account_id"] == export_client.account_id
|
||||
assert json.loads(row["app_response"]) == {"result": "ready"}
|
||||
export_client.storage.save_file.assert_called_once()
|
||||
export_client.storage.save_from_path.assert_called_once()
|
||||
ready = export_client.get_status(task_id)
|
||||
assert (ready.status_code, ready.json) == (200, {"task_id": task_id, "status": "ready"})
|
||||
assert ready.headers["Cache-Control"] == "no-store"
|
||||
@@ -396,7 +396,7 @@ def test_workflow_export_marks_task_failed_if_publication_fails(export_client: _
|
||||
key = export_client.redis.setex.call_args_list[0].args[0]
|
||||
task = WorkflowLogExportTask.model_validate_json(export_client.redis.get(key))
|
||||
assert task.status is LogExportStatus.FAILED
|
||||
export_client.storage.save_file.assert_not_called()
|
||||
export_client.storage.save_from_path.assert_not_called()
|
||||
assert export_client.get_status(task.task_id).json == {"task_id": task.task_id, "status": "failed"}
|
||||
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ def log_export_redis() -> Iterator[LogExportRedisIo]:
|
||||
class LogExportStorageIo:
|
||||
exists: MagicMock
|
||||
load: MagicMock
|
||||
save_file: MagicMock
|
||||
save_from_path: MagicMock
|
||||
generate_presigned_url: MagicMock
|
||||
|
||||
|
||||
@@ -45,10 +45,10 @@ def log_export_storage() -> Iterator[LogExportStorageIo]:
|
||||
with (
|
||||
patch.object(storage, "exists") as exists,
|
||||
patch.object(storage, "load") as load,
|
||||
patch.object(storage, "save_file") as save_file,
|
||||
patch.object(storage, "save_from_path") as save_from_path,
|
||||
patch.object(storage, "generate_presigned_url") as sign,
|
||||
):
|
||||
yield LogExportStorageIo(exists, load, save_file, sign)
|
||||
yield LogExportStorageIo(exists, load, save_from_path, sign)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -369,8 +369,8 @@ def test_create_agent_log_export_dispatches_utc_filters_and_prepares_the_csv(
|
||||
with path.open(encoding="utf-8-sig", newline="") as csv_file:
|
||||
uploaded[key] = list(DictReader(csv_file))
|
||||
|
||||
save_file = log_export_storage.save_file
|
||||
save_file.side_effect = upload
|
||||
save_from_path = log_export_storage.save_from_path
|
||||
save_from_path.side_effect = upload
|
||||
agent_id, app_id = harness.create_agent()
|
||||
foreign_id, _ = harness.create_agent(tenant_id=str(uuid4()))
|
||||
end_user_id, conversation_id, message_id = (str(uuid4()) for _ in range(3))
|
||||
@@ -495,7 +495,7 @@ def test_create_agent_log_export_dispatches_utc_filters_and_prepares_the_csv(
|
||||
assert row["account_id"] == ""
|
||||
assert rows[account_message_id]["account_id"] == harness.account_id
|
||||
assert rows[account_message_id]["end_user_id"] == ""
|
||||
save_file.assert_called_once()
|
||||
save_from_path.assert_called_once()
|
||||
status = harness.client.get(f"{base}/{task_id}", headers=harness.headers)
|
||||
assert (status.status_code, status.json) == (HTTPStatus.OK, {"task_id": task_id, "status": "ready"})
|
||||
assert status.headers["Cache-Control"] == "no-store"
|
||||
|
||||
@@ -182,7 +182,7 @@ def test_prepare_export_records_only_claimed_work(
|
||||
log_export_redis.get.return_value = task.model_dump_json()
|
||||
log_export_redis.register_script.return_value = transition
|
||||
if outcome == "failed":
|
||||
log_export_storage.save_file.side_effect = OSError("upload failed")
|
||||
log_export_storage.save_from_path.side_effect = OSError("upload failed")
|
||||
|
||||
if outcome == "failed":
|
||||
with pytest.raises(OSError, match="upload failed"):
|
||||
@@ -192,15 +192,15 @@ def test_prepare_export_records_only_claimed_work(
|
||||
|
||||
if outcome == "claim_lost":
|
||||
assert transitions == [("pending", "processing")]
|
||||
log_export_storage.save_file.assert_not_called()
|
||||
log_export_storage.save_from_path.assert_not_called()
|
||||
else:
|
||||
storage_key = f"conversation-log-exports/{task.tenant_id}/{task.app_id}/{task.task_id}.csv"
|
||||
assert transitions == [("pending", "processing"), ("processing", outcome)]
|
||||
assert log_export_storage.save_file.call_args.args[0] == storage_key
|
||||
assert log_export_storage.save_from_path.call_args.args[0] == storage_key
|
||||
assert current.status == outcome
|
||||
assert current.storage_key == (storage_key if outcome == "ready" else None)
|
||||
export.prepare_task(tenant_id=task.tenant_id, app_id=task.app_id, task_id=task.task_id)
|
||||
log_export_storage.save_file.assert_called_once()
|
||||
log_export_storage.save_from_path.assert_called_once()
|
||||
|
||||
|
||||
def test_console_log_csv_exports_all_turns_of_matching_conversations_in_batches(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Check that queued Conversation exports remain compatible with the shared worker."""
|
||||
"""Check that Conversation exports are delivered through the shared task."""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@@ -13,7 +13,7 @@ from tasks import log_export_tasks
|
||||
from tests.helpers.unit.tasks.task_options import task_options
|
||||
|
||||
|
||||
def test_conversation_log_export_keeps_its_original_message(log_export_publish: MagicMock) -> None:
|
||||
def test_conversation_log_export_uses_shared_task(log_export_publish: MagicMock) -> None:
|
||||
task = ConversationLogExportTask.pending(
|
||||
tenant_id="tenant",
|
||||
app_id="app",
|
||||
@@ -29,9 +29,11 @@ def test_conversation_log_export_keeps_its_original_message(log_export_publish:
|
||||
dispatch_log_export(task, export_kind=LogExportKind.CONVERSATION)
|
||||
|
||||
args = {"tenant_id": task.tenant_id, "app_id": task.app_id, "task_id": task.task_id}
|
||||
assert worker.name == "tasks.conversation_log_export_tasks.prepare_conversation_log_export_task"
|
||||
message = {**args, "export_kind": "conversation"}
|
||||
assert worker.name == "tasks.log_export_tasks.prepare_log_export_task"
|
||||
assert task_options(worker)["queue"] == "retention"
|
||||
log_export_publish.assert_called_once_with(kwargs=args, task_id=task.task_id, expires=task.expires_at)
|
||||
log_export_publish.assert_called_once_with(kwargs=message, task_id=task.task_id, expires=task.expires_at)
|
||||
|
||||
with app.app_context(), patch.object(application_services().conversation_log_exports, "prepare_task") as prepare:
|
||||
worker.run(**args)
|
||||
worker.run(**message)
|
||||
prepare.assert_called_once_with(**args)
|
||||
Reference in new issue
Block a user