refactor(api): move app-scoped end users behind application services (#41398)

This commit is contained in:
Byron.wang authored and GitHub committed 2026-09-22 11:20:45 +00:00
1 parent 9badde4d65
commit ce2eaab9f7
41 files changed
+1384 -481

No files matched your search

@@ -0,0 +1,61 @@
from datetime import datetime
import pytest
from machinery.context import ServiceApiRequestContext
from services.app_scoped_end_user_query_service import AppScopedEndUserNotFoundError, AppScopedEndUserQueryService
from services.entities.app_scoped_end_user_entities import AppScopedEndUserRecord
def _context() -> ServiceApiRequestContext:
return ServiceApiRequestContext(
tenant_id="workspace-1",
app_id="app-1",
)
def _record() -> AppScopedEndUserRecord:
timestamp = datetime(2026, 1, 1)
return AppScopedEndUserRecord(
id="end-user-1",
tenant_id="workspace-1",
app_id="app-1",
type="service-api",
external_user_id="external-1",
name="Alice",
is_anonymous=False,
session_id="session-1",
created_at=timestamp,
updated_at=timestamp,
)
class RecordingEndUserQuery:
def __init__(self, result: AppScopedEndUserRecord | None) -> None:
self._result = result
self.calls: list[tuple[str, str, str]] = []
def find_by_id(self, *, tenant_id: str, app_id: str, end_user_id: str) -> AppScopedEndUserRecord | None:
self.calls.append((tenant_id, app_id, end_user_id))
return self._result
def test_get_scopes_query_to_admitted_workspace_and_app() -> None:
record = _record()
query = RecordingEndUserQuery(record)
service = AppScopedEndUserQueryService(end_users=query)
result = service.get_by_id(_context(), "end-user-1")
assert result == record
assert query.calls == [("workspace-1", "app-1", "end-user-1")]
def test_get_raises_framework_neutral_not_found_error() -> None:
query = RecordingEndUserQuery(None)
service = AppScopedEndUserQueryService(end_users=query)
with pytest.raises(AppScopedEndUserNotFoundError):
service.get_by_id(_context(), "missing")
assert query.calls == [("workspace-1", "app-1", "missing")]
@@ -0,0 +1,194 @@
from collections.abc import Sequence
from typing import override
from models.enums import DEFAULT_END_USER_SESSION_ID, EndUserType
from services.app_scoped_end_user_service import AppScopedEndUserRepository, AppScopedEndUserService
from services.entities.app_scoped_end_user_entities import NewAppScopedEndUser, StoredAppScopedEndUser
class RecordingEndUserRepository(AppScopedEndUserRepository[str]):
def __init__(
self,
*,
session_candidates: Sequence[StoredAppScopedEndUser[str]] = (),
app_candidates: Sequence[StoredAppScopedEndUser[str]] = (),
) -> None:
self.session_candidates = list(session_candidates)
self.app_candidates = list(app_candidates)
self.find_session_calls: list[tuple[str, str, str]] = []
self.find_apps_calls: list[tuple[str, list[str], str, str]] = []
self.created: list[NewAppScopedEndUser] = []
self.updated_types: list[tuple[str, str]] = []
@override
def find_by_session(
self,
*,
tenant_id: str,
app_id: str,
user_id: str,
) -> Sequence[StoredAppScopedEndUser[str]]:
self.find_session_calls.append((tenant_id, app_id, user_id))
return self.session_candidates
@override
def find_by_apps(
self,
*,
tenant_id: str,
app_ids: Sequence[str],
user_id: str,
type: str,
) -> Sequence[StoredAppScopedEndUser[str]]:
self.find_apps_calls.append((tenant_id, list(app_ids), user_id, type))
return self.app_candidates
@override
def create(self, command: NewAppScopedEndUser) -> StoredAppScopedEndUser[str]:
self.created.append(command)
return StoredAppScopedEndUser(
id=f"new-{command.app_id}",
app_id=command.app_id,
type=command.type,
value="created",
)
@override
def create_batch(
self,
commands: Sequence[NewAppScopedEndUser],
) -> Sequence[StoredAppScopedEndUser[str]]:
self.created.extend(commands)
return [
StoredAppScopedEndUser(
id=f"new-{command.app_id}",
app_id=command.app_id,
type=command.type,
value=command.app_id,
)
for command in commands
]
@override
def update_type(self, end_user_id: str, type: str) -> StoredAppScopedEndUser[str]:
self.updated_types.append((end_user_id, type))
candidate = next(candidate for candidate in self.session_candidates if candidate.id == end_user_id)
return StoredAppScopedEndUser(id=candidate.id, app_id=candidate.app_id, type=type, value=candidate.value)
def _stored(*, id: str, app_id: str = "app-1", type: EndUserType, value: str) -> StoredAppScopedEndUser[str]:
return StoredAppScopedEndUser(id=id, app_id=app_id, type=type.value, value=value)
def _service(repository: RecordingEndUserRepository) -> AppScopedEndUserService[str]:
return AppScopedEndUserService(end_users=repository)
def test_get_or_create_prioritizes_matching_type_in_service() -> None:
repository = RecordingEndUserRepository(
session_candidates=[
_stored(id="legacy", type=EndUserType.BROWSER, value="legacy"),
_stored(id="matching", type=EndUserType.OPENAPI, value="matching"),
]
)
result = _service(repository).get_or_create_end_user_by_type(
EndUserType.OPENAPI,
tenant_id="tenant-1",
app_id="app-1",
user_id="user-1",
)
assert result == "matching"
assert repository.updated_types == []
assert repository.created == []
def test_get_or_create_upgrades_legacy_type() -> None:
repository = RecordingEndUserRepository(
session_candidates=[_stored(id="legacy", type=EndUserType.BROWSER, value="legacy")]
)
result = _service(repository).get_or_create_end_user_by_type(
EndUserType.SERVICE_API,
tenant_id="tenant-1",
app_id="app-1",
user_id="user-1",
)
assert result == "legacy"
assert repository.updated_types == [("legacy", EndUserType.SERVICE_API.value)]
def test_get_or_create_never_retypes_an_app_deploy_end_user() -> None:
repository = RecordingEndUserRepository(
session_candidates=[_stored(id="app-deploy", type=EndUserType.APP_DEPLOY, value="app-deploy")]
)
result = _service(repository).get_or_create_end_user_by_type(
EndUserType.SERVICE_API,
tenant_id="tenant-1",
app_id="app-1",
user_id="user-1",
)
assert result == "created"
assert repository.updated_types == []
assert repository.created == [
NewAppScopedEndUser(
tenant_id="tenant-1",
app_id="app-1",
type=EndUserType.SERVICE_API.value,
is_anonymous=False,
session_id="user-1",
external_user_id="user-1",
)
]
def test_get_or_create_builds_anonymous_creation_command() -> None:
repository = RecordingEndUserRepository()
result = _service(repository).get_or_create_end_user(
tenant_id="tenant-1",
app_id="app-1",
)
assert result == "created"
assert repository.find_session_calls == [("tenant-1", "app-1", DEFAULT_END_USER_SESSION_ID)]
assert repository.created == [
NewAppScopedEndUser(
tenant_id="tenant-1",
app_id="app-1",
type=EndUserType.SERVICE_API.value,
is_anonymous=True,
session_id=DEFAULT_END_USER_SESSION_ID,
external_user_id=DEFAULT_END_USER_SESSION_ID,
)
]
def test_create_batch_deduplicates_apps_and_creates_only_missing_users() -> None:
repository = RecordingEndUserRepository(
app_candidates=[_stored(id="existing", app_id="app-1", type=EndUserType.TRIGGER, value="existing")]
)
result = _service(repository).create_end_user_batch(
EndUserType.TRIGGER,
tenant_id="tenant-1",
app_ids=["app-1", "app-2", "app-1"],
user_id="user-1",
)
assert result == {"app-1": "existing", "app-2": "app-2"}
assert repository.find_apps_calls == [("tenant-1", ["app-1", "app-2"], "user-1", EndUserType.TRIGGER.value)]
assert repository.created == [
NewAppScopedEndUser(
tenant_id="tenant-1",
app_id="app-2",
type=EndUserType.TRIGGER.value,
is_anonymous=False,
session_id="user-1",
external_user_id="user-1",
)
]
@@ -21,6 +21,24 @@ from services.trigger.webhook_service import WebhookService
from tests.unit_tests.model_factories import make_app, make_end_user, make_workflow
class _EndUserServiceStub:
def __init__(self, result: EndUser | Exception) -> None:
self._result = result
self.calls: list[tuple[EndUserType, str, str, str | None]] = []
def get_or_create_end_user_by_type(
self,
type: EndUserType,
tenant_id: str,
app_id: str,
user_id: str | None = None,
) -> EndUser:
self.calls.append((type, tenant_id, app_id, user_id))
if isinstance(self._result, Exception):
raise self._result
return self._result
def _webhook_trigger(
*,
webhook_id: str = "webhook-123",
@@ -229,10 +247,6 @@ class TestWebhookServiceUnit:
caplog.set_level(logging.INFO)
with (
patch(
"services.trigger.webhook_service.EndUserService.get_or_create_end_user_by_type",
return_value=_end_user(),
),
patch("services.trigger.webhook_service.QuotaService.reserve", return_value=quota_charge),
patch(
"services.trigger.webhook_service.AsyncWorkflowService.trigger_workflow_async",
@@ -244,6 +258,7 @@ class TestWebhookServiceUnit:
webhook_trigger,
{"body": {}, "headers": {}, "query_params": {}, "files": {}, "method": "POST"},
workflow,
end_users=_EndUserServiceStub(_end_user()),
)
assert exc_info.value is quota_error
@@ -276,18 +291,18 @@ class TestWebhookServiceUnit:
}
with (
patch.object(
webhook_service_module.EndUserService,
"get_or_create_end_user_by_type",
return_value=end_user,
),
patch.object(webhook_service_module.QuotaService, "reserve", return_value=quota_charge),
patch.object(
webhook_service_module.AsyncWorkflowService,
"trigger_workflow_async",
) as mock_trigger,
):
WebhookService.trigger_workflow_execution(webhook_trigger, webhook_data, workflow)
WebhookService.trigger_workflow_execution(
webhook_trigger,
webhook_data,
workflow,
end_users=_EndUserServiceStub(end_user),
)
call_session = mock_trigger.call_args.kwargs["session"]
assert call_session.get_bind() is sqlite_engine
@@ -299,13 +314,13 @@ class TestWebhookServiceUnit:
workflow = _workflow()
webhook_data = {"method": "POST", "headers": {}, "query_params": {}, "body": {}, "files": {}}
with patch.object(
webhook_service_module.EndUserService,
"get_or_create_end_user_by_type",
side_effect=ValueError("Failed to create end user"),
):
with pytest.raises(ValueError, match="Failed to create end user"):
WebhookService.trigger_workflow_execution(webhook_trigger, webhook_data, workflow)
with pytest.raises(ValueError, match="Failed to create end user"):
WebhookService.trigger_workflow_execution(
webhook_trigger,
webhook_data,
workflow,
end_users=_EndUserServiceStub(ValueError("Failed to create end user")),
)
def test_extract_webhook_data_json(self):
"""Test webhook data extraction from JSON request."""