harborrag-runtime 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- harborrag_runtime/__init__.py +22 -0
- harborrag_runtime/application/README.md +39 -0
- harborrag_runtime/application/__init__.py +39 -0
- harborrag_runtime/application/chat/__init__.py +7 -0
- harborrag_runtime/application/chat/citations.py +149 -0
- harborrag_runtime/application/chat/client.py +201 -0
- harborrag_runtime/application/chat/completion.py +92 -0
- harborrag_runtime/application/chat/completion_request.py +130 -0
- harborrag_runtime/application/chat/evidence.py +202 -0
- harborrag_runtime/application/chat/options.py +43 -0
- harborrag_runtime/application/chat/preparation.py +135 -0
- harborrag_runtime/application/chat/presenters.py +130 -0
- harborrag_runtime/application/chat/prompting.py +127 -0
- harborrag_runtime/application/chat/query_scope.py +146 -0
- harborrag_runtime/application/chat/replay.py +141 -0
- harborrag_runtime/application/chat/request_filters.py +134 -0
- harborrag_runtime/application/chat/retrieval.py +127 -0
- harborrag_runtime/application/chat/service.py +371 -0
- harborrag_runtime/application/composition/__init__.py +1 -0
- harborrag_runtime/application/composition/factories.py +106 -0
- harborrag_runtime/application/composition/resources.py +141 -0
- harborrag_runtime/application/composition/selection.py +65 -0
- harborrag_runtime/application/composition/service.py +550 -0
- harborrag_runtime/application/composition/tenant_models.py +45 -0
- harborrag_runtime/application/control_plane/__init__.py +1 -0
- harborrag_runtime/application/control_plane/active_runs.py +38 -0
- harborrag_runtime/application/control_plane/connection_models.py +109 -0
- harborrag_runtime/application/control_plane/connection_testing.py +91 -0
- harborrag_runtime/application/control_plane/connection_writes.py +227 -0
- harborrag_runtime/application/control_plane/connections.py +749 -0
- harborrag_runtime/application/control_plane/effect_recovery.py +235 -0
- harborrag_runtime/application/control_plane/projects.py +313 -0
- harborrag_runtime/application/control_plane/settings_import.py +239 -0
- harborrag_runtime/application/control_plane/settings_service.py +233 -0
- harborrag_runtime/application/control_plane/tenants.py +55 -0
- harborrag_runtime/application/errors.py +110 -0
- harborrag_runtime/application/ingestion/__init__.py +1 -0
- harborrag_runtime/application/ingestion/client.py +65 -0
- harborrag_runtime/application/ingestion/connection_sources.py +96 -0
- harborrag_runtime/application/ingestion/direct.py +120 -0
- harborrag_runtime/application/ingestion/follower.py +83 -0
- harborrag_runtime/application/ingestion/ports.py +174 -0
- harborrag_runtime/application/ingestion/progress_bridge.py +221 -0
- harborrag_runtime/application/ingestion/retry_selection.py +71 -0
- harborrag_runtime/application/ingestion/service.py +564 -0
- harborrag_runtime/application/ingestion/starter.py +78 -0
- harborrag_runtime/application/memory/__init__.py +21 -0
- harborrag_runtime/application/memory/client.py +114 -0
- harborrag_runtime/application/memory/composition.py +90 -0
- harborrag_runtime/application/memory/context.py +45 -0
- harborrag_runtime/application/memory/sessions.py +117 -0
- harborrag_runtime/application/ports.py +133 -0
- harborrag_runtime/application/retrieval/__init__.py +1 -0
- harborrag_runtime/application/retrieval/access.py +26 -0
- harborrag_runtime/application/scheduling/service.py +58 -0
- harborrag_runtime/application/schemas.py +15 -0
- harborrag_runtime/chat/README.md +40 -0
- harborrag_runtime/chat/__init__.py +18 -0
- harborrag_runtime/chat/composition.py +53 -0
- harborrag_runtime/chat/facade.py +46 -0
- harborrag_runtime/chat/service.py +183 -0
- harborrag_runtime/chat/tenant_clients.py +341 -0
- harborrag_runtime/chat/tenant_config.py +235 -0
- harborrag_runtime/chat/tenant_models.py +22 -0
- harborrag_runtime/composition/__init__.py +5 -0
- harborrag_runtime/composition/config_store.py +53 -0
- harborrag_runtime/composition/connection_removal.py +120 -0
- harborrag_runtime/composition/connection_stores.py +107 -0
- harborrag_runtime/composition/control_plane.py +401 -0
- harborrag_runtime/composition/mcp_auth.py +39 -0
- harborrag_runtime/composition/readers.py +113 -0
- harborrag_runtime/composition/resources.py +336 -0
- harborrag_runtime/composition/storage_providers.py +113 -0
- harborrag_runtime/config/__init__.py +84 -0
- harborrag_runtime/config/checkout.py +212 -0
- harborrag_runtime/config/chunking.py +167 -0
- harborrag_runtime/config/connectors/__init__.py +19 -0
- harborrag_runtime/config/connectors/fingerprints.py +54 -0
- harborrag_runtime/config/connectors/importing.py +611 -0
- harborrag_runtime/config/connectors/loader.py +95 -0
- harborrag_runtime/config/connectors/models/__init__.py +30 -0
- harborrag_runtime/config/connectors/models/atlassian.py +199 -0
- harborrag_runtime/config/connectors/models/builder.py +208 -0
- harborrag_runtime/config/connectors/models/common.py +45 -0
- harborrag_runtime/config/connectors/models/fields.py +134 -0
- harborrag_runtime/config/connectors/models/github.py +143 -0
- harborrag_runtime/config/connectors/models/local_file.py +119 -0
- harborrag_runtime/config/connectors/models/registry.py +149 -0
- harborrag_runtime/config/connectors/models/sharepoint.py +186 -0
- harborrag_runtime/config/connectors/models/spec.py +563 -0
- harborrag_runtime/config/connectors/parsing.py +275 -0
- harborrag_runtime/config/connectors/providers.py +177 -0
- harborrag_runtime/config/connectors/schemas.py +215 -0
- harborrag_runtime/config/errors.py +26 -0
- harborrag_runtime/config/graph_build.py +335 -0
- harborrag_runtime/config/graph_build_loading.py +38 -0
- harborrag_runtime/config/loading.py +245 -0
- harborrag_runtime/config/models.py +95 -0
- harborrag_runtime/config/ontology_loading.py +76 -0
- harborrag_runtime/config/parsers/__init__.py +19 -0
- harborrag_runtime/config/parsers/loader.py +85 -0
- harborrag_runtime/config/parsers/parsing.py +285 -0
- harborrag_runtime/config/parsers/providers.py +305 -0
- harborrag_runtime/config/parsers/schemas.py +614 -0
- harborrag_runtime/config/settings.py +378 -0
- harborrag_runtime/config/settings_document.py +133 -0
- harborrag_runtime/config/temporal.py +331 -0
- harborrag_runtime/config/temporal_loading.py +310 -0
- harborrag_runtime/config_store/__init__.py +5 -0
- harborrag_runtime/config_store/defaults.py +47 -0
- harborrag_runtime/config_store/provider.py +153 -0
- harborrag_runtime/config_store/run_settings.py +72 -0
- harborrag_runtime/connections/__init__.py +27 -0
- harborrag_runtime/connections/secrets.py +348 -0
- harborrag_runtime/contracts.py +237 -0
- harborrag_runtime/document_stage_catalog.py +82 -0
- harborrag_runtime/errors.py +64 -0
- harborrag_runtime/events/__init__.py +3 -0
- harborrag_runtime/events/in_process.py +100 -0
- harborrag_runtime/execution/__init__.py +26 -0
- harborrag_runtime/execution/contracts.py +32 -0
- harborrag_runtime/execution/direct.py +169 -0
- harborrag_runtime/execution/gateway.py +97 -0
- harborrag_runtime/execution/source_conversion.py +61 -0
- harborrag_runtime/execution/source_submission.py +278 -0
- harborrag_runtime/execution/submission.py +64 -0
- harborrag_runtime/execution/task_registry.py +387 -0
- harborrag_runtime/execution/temporal.py +165 -0
- harborrag_runtime/ingestion/README.md +79 -0
- harborrag_runtime/ingestion/__init__.py +59 -0
- harborrag_runtime/ingestion/chunking_profile.py +97 -0
- harborrag_runtime/ingestion/composition.py +279 -0
- harborrag_runtime/ingestion/connection_checks.py +239 -0
- harborrag_runtime/ingestion/connections.py +507 -0
- harborrag_runtime/ingestion/document/__init__.py +1 -0
- harborrag_runtime/ingestion/document/normalization.py +14 -0
- harborrag_runtime/ingestion/document/normalizers/__init__.py +9 -0
- harborrag_runtime/ingestion/document/normalizers/builtins.py +39 -0
- harborrag_runtime/ingestion/document/normalizers/transform.py +30 -0
- harborrag_runtime/ingestion/document/run_tools.py +152 -0
- harborrag_runtime/ingestion/failure_classification.py +82 -0
- harborrag_runtime/ingestion/field_indexes.py +56 -0
- harborrag_runtime/ingestion/maintenance/__init__.py +1 -0
- harborrag_runtime/ingestion/maintenance/connection_removal.py +115 -0
- harborrag_runtime/ingestion/maintenance/projection_admin.py +180 -0
- harborrag_runtime/ingestion/maintenance/relation_repair.py +555 -0
- harborrag_runtime/ingestion/maintenance/retention.py +353 -0
- harborrag_runtime/ingestion/observability.py +3 -0
- harborrag_runtime/ingestion/profiles.py +127 -0
- harborrag_runtime/ingestion/runtime_builder.py +339 -0
- harborrag_runtime/ingestion/source/__init__.py +1 -0
- harborrag_runtime/ingestion/source/descriptor_mapping.py +144 -0
- harborrag_runtime/ingestion/source/discovery.py +290 -0
- harborrag_runtime/ingestion/source/documents.py +184 -0
- harborrag_runtime/ingestion/source/finalization.py +288 -0
- harborrag_runtime/ingestion/source/operations.py +175 -0
- harborrag_runtime/ingestion/source/plan.py +413 -0
- harborrag_runtime/ingestion/source/retry.py +150 -0
- harborrag_runtime/ingestion/source/service.py +470 -0
- harborrag_runtime/ingestion/source/skips.py +172 -0
- harborrag_runtime/ingestion_contracts.py +107 -0
- harborrag_runtime/memory/__init__.py +81 -0
- harborrag_runtime/memory/access.py +47 -0
- harborrag_runtime/memory/administration.py +460 -0
- harborrag_runtime/memory/context/__init__.py +5 -0
- harborrag_runtime/memory/context/result.py +20 -0
- harborrag_runtime/memory/directory.py +166 -0
- harborrag_runtime/memory/erasure.py +122 -0
- harborrag_runtime/memory/locks.py +170 -0
- harborrag_runtime/memory/messages.py +202 -0
- harborrag_runtime/memory/presenters.py +117 -0
- harborrag_runtime/memory/projects.py +38 -0
- harborrag_runtime/memory/tiers/__init__.py +1 -0
- harborrag_runtime/memory/tiers/in_memory.py +491 -0
- harborrag_runtime/memory/titles.py +32 -0
- harborrag_runtime/memory/usage.py +131 -0
- harborrag_runtime/observability/__init__.py +1 -0
- harborrag_runtime/observability/connector_metrics.py +14 -0
- harborrag_runtime/observability/discovery_metrics.py +46 -0
- harborrag_runtime/observability/model.py +410 -0
- harborrag_runtime/observability/observability_types.py +47 -0
- harborrag_runtime/observability/stage_observation.py +96 -0
- harborrag_runtime/observability/tool_audit.py +17 -0
- harborrag_runtime/plugins.py +56 -0
- harborrag_runtime/rate_limiting.py +39 -0
- harborrag_runtime/reader_contracts.py +149 -0
- harborrag_runtime/retrieval/__init__.py +1 -0
- harborrag_runtime/retrieval/composition.py +174 -0
- harborrag_runtime/retrieval/facades.py +224 -0
- harborrag_runtime/scheduling/__init__.py +48 -0
- harborrag_runtime/scheduling/config.py +185 -0
- harborrag_runtime/scheduling/errors.py +37 -0
- harborrag_runtime/scheduling/models.py +146 -0
- harborrag_runtime/scheduling/service.py +297 -0
- harborrag_runtime/scheduling/validation.py +213 -0
- harborrag_runtime/sdk/__init__.py +86 -0
- harborrag_runtime/sdk/configuration.py +44 -0
- harborrag_runtime/sdk/facades.py +47 -0
- harborrag_runtime/sdk/runtime.py +242 -0
- harborrag_runtime/security/__init__.py +1 -0
- harborrag_runtime/security/api_key_operations.py +236 -0
- harborrag_runtime/serialization.py +35 -0
- harborrag_runtime/temporal/__init__.py +19 -0
- harborrag_runtime/temporal/activity_observability.py +313 -0
- harborrag_runtime/temporal/client.py +580 -0
- harborrag_runtime/temporal/connection.py +39 -0
- harborrag_runtime/temporal/conversion.py +147 -0
- harborrag_runtime/temporal/dispatch.py +38 -0
- harborrag_runtime/temporal/document_workflow.py +154 -0
- harborrag_runtime/temporal/failure_handling.py +68 -0
- harborrag_runtime/temporal/gateway.py +121 -0
- harborrag_runtime/temporal/heartbeats.py +67 -0
- harborrag_runtime/temporal/identity.py +14 -0
- harborrag_runtime/temporal/ingestion_activities.py +435 -0
- harborrag_runtime/temporal/maintenance_activities.py +251 -0
- harborrag_runtime/temporal/maintenance_schemas.py +88 -0
- harborrag_runtime/temporal/optional.py +19 -0
- harborrag_runtime/temporal/plan_resolver.py +149 -0
- harborrag_runtime/temporal/policies.py +18 -0
- harborrag_runtime/temporal/reindex_workflow.py +71 -0
- harborrag_runtime/temporal/retry_activities.py +147 -0
- harborrag_runtime/temporal/retry_workflow.py +222 -0
- harborrag_runtime/temporal/sandbox.py +51 -0
- harborrag_runtime/temporal/schedules.py +341 -0
- harborrag_runtime/temporal/schemas.py +482 -0
- harborrag_runtime/temporal/source_activities.py +590 -0
- harborrag_runtime/temporal/source_batch_workflow.py +226 -0
- harborrag_runtime/temporal/source_workflow.py +908 -0
- harborrag_runtime/temporal/submission.py +23 -0
- harborrag_runtime/temporal/worker.py +478 -0
- harborrag_runtime/temporal/worker_registry.py +141 -0
- harborrag_runtime/temporal_models.py +227 -0
- harborrag_runtime/testing/chat_fakes.py +309 -0
- harborrag_runtime/testing/chat_service_double.py +126 -0
- harborrag_runtime/testing/connection_fakes.py +278 -0
- harborrag_runtime/testing/memory_fakes.py +128 -0
- harborrag_runtime/topology/__init__.py +1 -0
- harborrag_runtime/topology/budgeted_extractor.py +110 -0
- harborrag_runtime/topology/chunk_runner.py +41 -0
- harborrag_runtime/topology/composition.py +168 -0
- harborrag_runtime/topology/configuration.py +126 -0
- harborrag_runtime/topology/contextual.py +140 -0
- harborrag_runtime/topology/derived.py +238 -0
- harborrag_runtime/topology/derived_coverage.py +5 -0
- harborrag_runtime/topology/derived_dispatch.py +63 -0
- harborrag_runtime/topology/derived_factory.py +175 -0
- harborrag_runtime/topology/derived_models.py +251 -0
- harborrag_runtime/topology/derived_projection.py +127 -0
- harborrag_runtime/topology/description_factory.py +81 -0
- harborrag_runtime/topology/embedding_profile.py +85 -0
- harborrag_runtime/topology/entity_summary_index.py +304 -0
- harborrag_runtime/topology/maintenance.py +126 -0
- harborrag_runtime/topology/operations.py +277 -0
- harborrag_runtime/topology/parent_materializer.py +167 -0
- harborrag_runtime/topology/run_cost.py +43 -0
- harborrag_runtime/topology/security_operations.py +46 -0
- harborrag_runtime/topology/service.py +349 -0
- harborrag_runtime/topology/summary_factory.py +164 -0
- harborrag_runtime/topology/summary_inputs.py +129 -0
- harborrag_runtime/topology/summary_operations.py +128 -0
- harborrag_runtime/topology/summary_policy.py +39 -0
- harborrag_runtime/topology/summary_products.py +43 -0
- harborrag_runtime/topology/summary_service.py +625 -0
- harborrag_runtime/topology/summary_worker.py +129 -0
- harborrag_runtime/topology/summary_workflow.py +32 -0
- harborrag_runtime/topology/worker.py +101 -0
- harborrag_runtime/topology/workflow.py +32 -0
- harborrag_runtime-2.0.0.dist-info/METADATA +267 -0
- harborrag_runtime-2.0.0.dist-info/RECORD +271 -0
- harborrag_runtime-2.0.0.dist-info/WHEEL +4 -0
- harborrag_runtime-2.0.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"""Application service for authenticated, retrieval-grounded chat completion."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import logging
|
|
7
|
+
from collections.abc import AsyncGenerator, AsyncIterator, Callable, Sequence
|
|
8
|
+
from contextlib import asynccontextmanager
|
|
9
|
+
from dataclasses import replace
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
from uuid import uuid4
|
|
12
|
+
|
|
13
|
+
from harborrag_core.contracts.errors import (
|
|
14
|
+
ChatModelUnavailableError,
|
|
15
|
+
HarborConnectionError,
|
|
16
|
+
HarborError,
|
|
17
|
+
HarborNotFoundError,
|
|
18
|
+
HarborUnavailableError,
|
|
19
|
+
HarborValidationError,
|
|
20
|
+
UnknownReferenceError,
|
|
21
|
+
)
|
|
22
|
+
from harborrag_core.domain.identity import MemoryIdentity
|
|
23
|
+
from harborrag_core.models.errors import HarborChatError
|
|
24
|
+
from harborrag_core.ports.control_plane import ProjectRepositoryPort
|
|
25
|
+
from harborrag_core.ports.conversation import (
|
|
26
|
+
ConversationHistoryRepository,
|
|
27
|
+
new_message_id,
|
|
28
|
+
)
|
|
29
|
+
from harborrag_core.ports.usage import ModelUsageRepository
|
|
30
|
+
from harborrag_engine.chat.scope import ConnectionCatalog, RetrievalScope, resolve_scope
|
|
31
|
+
from harborrag_runtime.application.errors import failure_response
|
|
32
|
+
from harborrag_runtime.application.schemas import AppResponse
|
|
33
|
+
from harborrag_runtime.config.settings import RuntimeSettings
|
|
34
|
+
from harborrag_runtime.memory.access import MemoryAccess
|
|
35
|
+
from harborrag_runtime.memory.locks import SessionLocks
|
|
36
|
+
from harborrag_runtime.memory.messages import ExchangeRecord, record_exchange
|
|
37
|
+
from harborrag_runtime.memory.projects import require_project
|
|
38
|
+
from harborrag_runtime.memory.titles import conversation_title
|
|
39
|
+
from harborrag_runtime.memory.usage import ModelCall, record_model_usage
|
|
40
|
+
|
|
41
|
+
from .citations import CitationNumbering
|
|
42
|
+
from .completion import (
|
|
43
|
+
AnswerDelta,
|
|
44
|
+
Completion,
|
|
45
|
+
CompletionUsage,
|
|
46
|
+
RetrievalFound,
|
|
47
|
+
TurnCompleted,
|
|
48
|
+
TurnEvent,
|
|
49
|
+
)
|
|
50
|
+
from .options import ChatExecutionOptions
|
|
51
|
+
from .preparation import ChatTurnResources, PreparedTurn, RuntimeProvider, prepare_turn
|
|
52
|
+
from .query_scope import ScopeCheck, ScopeHistory, check_query_scope, scope_history
|
|
53
|
+
|
|
54
|
+
if TYPE_CHECKING:
|
|
55
|
+
from harborrag_core.models.chat import HarborChatResponse
|
|
56
|
+
from harborrag_core.ports.config_store import ConfigProvider
|
|
57
|
+
|
|
58
|
+
logger = logging.getLogger("harborrag.runtime.application.chat.service")
|
|
59
|
+
|
|
60
|
+
_MODEL_FAILURES = (HarborChatError, HarborConnectionError, HarborUnavailableError)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ChatApplicationService:
|
|
64
|
+
"""Ground chat completions in retrieved evidence and project the result.
|
|
65
|
+
|
|
66
|
+
Completions are serialized per session, so building the context and appending the
|
|
67
|
+
exchange cannot interleave across concurrent requests or SQL-backed workers.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
runtime_provider: Returns the runtime that retrieves and calls the chat model.
|
|
71
|
+
settings: Process settings holding the chat retrieval policy.
|
|
72
|
+
memory: Conversation history store.
|
|
73
|
+
projects: Project lookup; ``None`` skips project checks.
|
|
74
|
+
locks: Per-session locks; built over ``memory`` when omitted.
|
|
75
|
+
usage: Model usage ledger, when the deployment keeps one.
|
|
76
|
+
config: Runtime settings provider for per-project retrieval overrides.
|
|
77
|
+
catalog: Connection catalog that resolves a request's scope.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
def __init__( # noqa: PLR0913 - one keyword-only collaborator per injected port
|
|
81
|
+
self,
|
|
82
|
+
runtime_provider: RuntimeProvider,
|
|
83
|
+
settings: RuntimeSettings,
|
|
84
|
+
*,
|
|
85
|
+
memory: ConversationHistoryRepository,
|
|
86
|
+
projects: ProjectRepositoryPort | None = None,
|
|
87
|
+
locks: SessionLocks | None = None,
|
|
88
|
+
usage: ModelUsageRepository | None = None,
|
|
89
|
+
config: ConfigProvider | None = None,
|
|
90
|
+
catalog: ConnectionCatalog | None = None,
|
|
91
|
+
) -> None:
|
|
92
|
+
self._resources = ChatTurnResources(
|
|
93
|
+
runtime_provider=runtime_provider,
|
|
94
|
+
settings=settings,
|
|
95
|
+
memory=memory,
|
|
96
|
+
usage=usage,
|
|
97
|
+
config=config,
|
|
98
|
+
)
|
|
99
|
+
self._projects = projects
|
|
100
|
+
self._catalog = catalog
|
|
101
|
+
self._locks = locks or SessionLocks(memory)
|
|
102
|
+
|
|
103
|
+
async def validate_model(self, model: str | None, *, tenant_id: str) -> None:
|
|
104
|
+
"""Reject a model name this tenant may not use, before the turn starts.
|
|
105
|
+
|
|
106
|
+
The runtime owns the rule because only it can see both a tenant's own
|
|
107
|
+
catalog and the process-wide one. Callers ask up front so a rejected
|
|
108
|
+
name is a validation failure rather than a provider error mid-stream.
|
|
109
|
+
"""
|
|
110
|
+
await self._resources.runtime().chat.validate_model(model, tenant_id=tenant_id)
|
|
111
|
+
|
|
112
|
+
async def validate_project(self, project_id: str | None, *, tenant_id: str) -> None:
|
|
113
|
+
"""Reject a project this tenant does not have.
|
|
114
|
+
|
|
115
|
+
Raises:
|
|
116
|
+
HarborNotFoundError: ``project_id`` does not exist in ``tenant_id``.
|
|
117
|
+
"""
|
|
118
|
+
await require_project(self._projects, project_id, tenant_id=tenant_id)
|
|
119
|
+
|
|
120
|
+
async def complete(
|
|
121
|
+
self,
|
|
122
|
+
query: str,
|
|
123
|
+
*,
|
|
124
|
+
tenant_id: str,
|
|
125
|
+
principal_id: str,
|
|
126
|
+
options: ChatExecutionOptions,
|
|
127
|
+
) -> AppResponse:
|
|
128
|
+
"""Answer one question and return the explorer completion body.
|
|
129
|
+
|
|
130
|
+
Raises:
|
|
131
|
+
HarborError: As ``answer`` raises; any other failure is answered as an
|
|
132
|
+
unavailable chat service.
|
|
133
|
+
"""
|
|
134
|
+
events = self.answer(query, tenant_id=tenant_id, principal_id=principal_id, options=options)
|
|
135
|
+
try:
|
|
136
|
+
async with contextlib.aclosing(events):
|
|
137
|
+
async for event in events:
|
|
138
|
+
if isinstance(event, TurnCompleted):
|
|
139
|
+
return AppResponse(True, event.completion.data())
|
|
140
|
+
except HarborError:
|
|
141
|
+
raise
|
|
142
|
+
except Exception as exc: # noqa: BLE001 - stable application envelope
|
|
143
|
+
return failure_response(logger, exc, "generate chat completion")
|
|
144
|
+
raise RuntimeError("a chat turn ended without its completion")
|
|
145
|
+
|
|
146
|
+
async def answer(
|
|
147
|
+
self,
|
|
148
|
+
query: str,
|
|
149
|
+
*,
|
|
150
|
+
tenant_id: str,
|
|
151
|
+
principal_id: str,
|
|
152
|
+
options: ChatExecutionOptions,
|
|
153
|
+
validate: Callable[[Completion], object] | None = None,
|
|
154
|
+
) -> AsyncGenerator[TurnEvent, None]:
|
|
155
|
+
"""Run one turn, yielding the passages found, the answer text, then the completion.
|
|
156
|
+
|
|
157
|
+
Classic checks the request's scope with a model call after retrieval and
|
|
158
|
+
observes the graph per settings; instant does neither. In a session the
|
|
159
|
+
exchange is stored under the completion's id before ``TurnCompleted``; a
|
|
160
|
+
one-off question stores nothing. Every check that can refuse the turn runs
|
|
161
|
+
before any model call. ``validate`` sees the completion before it is stored;
|
|
162
|
+
when it raises, nothing is stored and its error propagates.
|
|
163
|
+
|
|
164
|
+
Raises:
|
|
165
|
+
HarborNotFoundError: The session does not exist for this caller.
|
|
166
|
+
HarborValidationError: ``project_ids`` in a session, or a request the
|
|
167
|
+
retrieval or prompt budget refuses.
|
|
168
|
+
UnknownReferenceError: A project or connection does not exist.
|
|
169
|
+
ConnectionOutOfScopeError: A connection sits outside the scope's projects.
|
|
170
|
+
HarborNoIndexedContentError: Nothing is indexed in the scope.
|
|
171
|
+
ConversationTurnBusyError: Another turn is answering in the session.
|
|
172
|
+
ChatModelUnavailableError: The chat model did not answer, or answered nothing.
|
|
173
|
+
HarborConnectionError: The answer could not be stored in the session.
|
|
174
|
+
"""
|
|
175
|
+
trace_id = options.trace_id or uuid4().hex
|
|
176
|
+
options = replace(options, trace_id=trace_id)
|
|
177
|
+
identity, scope = await self._admit(tenant_id, principal_id, options)
|
|
178
|
+
async with self._turn(identity):
|
|
179
|
+
prepared = await prepare_turn(
|
|
180
|
+
self._resources, query, identity, options, filters=scope.filters
|
|
181
|
+
)
|
|
182
|
+
history = await self._scope_history(identity, options)
|
|
183
|
+
yield RetrievalFound(prepared.results)
|
|
184
|
+
check = await self._check_scope(query, identity, options, history)
|
|
185
|
+
refusal = check.refusal if check is not None else None
|
|
186
|
+
response = (
|
|
187
|
+
await self._generate(prepared, identity, options) if refusal is None else None
|
|
188
|
+
)
|
|
189
|
+
numbering = CitationNumbering(() if response is None else prepared.results)
|
|
190
|
+
text = numbering.feed(response.text if response is not None else refusal or "")
|
|
191
|
+
text += numbering.finish()
|
|
192
|
+
if not text.strip():
|
|
193
|
+
raise ChatModelUnavailableError("The chat model returned no answer")
|
|
194
|
+
yield AnswerDelta(text)
|
|
195
|
+
calls = [check.response] if check is not None else []
|
|
196
|
+
if response is not None:
|
|
197
|
+
calls.append(response)
|
|
198
|
+
completion = Completion(
|
|
199
|
+
completion_id=new_message_id(),
|
|
200
|
+
session_id=identity.session_id,
|
|
201
|
+
trace_id=trace_id,
|
|
202
|
+
mode=options.mode,
|
|
203
|
+
answer=text,
|
|
204
|
+
citations=numbering.citations(),
|
|
205
|
+
usage=_usage(options, calls),
|
|
206
|
+
)
|
|
207
|
+
if validate is not None:
|
|
208
|
+
validate(completion)
|
|
209
|
+
answer_tokens = response.usage.completion_tokens if response is not None else None
|
|
210
|
+
await self._remember(query, identity, completion, answer_tokens)
|
|
211
|
+
yield TurnCompleted(completion)
|
|
212
|
+
|
|
213
|
+
async def _admit(
|
|
214
|
+
self, tenant_id: str, principal_id: str, options: ChatExecutionOptions
|
|
215
|
+
) -> tuple[MemoryIdentity, RetrievalScope]:
|
|
216
|
+
"""Find the session and the scope it reads, refusing before any model call."""
|
|
217
|
+
await self.validate_model(options.model, tenant_id=tenant_id)
|
|
218
|
+
if options.session_id is None:
|
|
219
|
+
projects = tuple(dict.fromkeys(options.project_ids))
|
|
220
|
+
for project_id in projects:
|
|
221
|
+
try:
|
|
222
|
+
await require_project(self._projects, project_id, tenant_id=tenant_id)
|
|
223
|
+
except HarborNotFoundError as exc:
|
|
224
|
+
raise UnknownReferenceError(str(exc), {"field": "project_ids"}) from exc
|
|
225
|
+
else:
|
|
226
|
+
projects = await self._session_projects(tenant_id, principal_id, options)
|
|
227
|
+
scope = await resolve_scope(
|
|
228
|
+
self._catalog,
|
|
229
|
+
tenant_id=tenant_id,
|
|
230
|
+
projects=projects,
|
|
231
|
+
connections=options.connections,
|
|
232
|
+
filters=options.filters,
|
|
233
|
+
)
|
|
234
|
+
identity = MemoryIdentity.build(
|
|
235
|
+
tenant_id=tenant_id,
|
|
236
|
+
principal_id=principal_id,
|
|
237
|
+
session_id=options.session_id,
|
|
238
|
+
user_id=options.user_id,
|
|
239
|
+
project_id=scope.project_id,
|
|
240
|
+
)
|
|
241
|
+
return identity, scope
|
|
242
|
+
|
|
243
|
+
async def _session_projects(
|
|
244
|
+
self, tenant_id: str, principal_id: str, options: ChatExecutionOptions
|
|
245
|
+
) -> tuple[str, ...]:
|
|
246
|
+
"""Return the project the session was created for, refusing ``project_ids`` in a session."""
|
|
247
|
+
if options.project_ids:
|
|
248
|
+
raise HarborValidationError(
|
|
249
|
+
"project_ids are for one-off questions; a session reads its own project",
|
|
250
|
+
{"field": "project_ids"},
|
|
251
|
+
)
|
|
252
|
+
assert options.session_id is not None
|
|
253
|
+
owner = MemoryIdentity.build(
|
|
254
|
+
tenant_id=tenant_id,
|
|
255
|
+
principal_id=principal_id,
|
|
256
|
+
session_id=options.session_id,
|
|
257
|
+
user_id=options.user_id,
|
|
258
|
+
).conversation()
|
|
259
|
+
session = await self._resources.memory.get_conversation(owner)
|
|
260
|
+
if session is None:
|
|
261
|
+
raise HarborNotFoundError("Conversation session was not found")
|
|
262
|
+
return (session.project_id,) if session.project_id else ()
|
|
263
|
+
|
|
264
|
+
@asynccontextmanager
|
|
265
|
+
async def _turn(self, identity: MemoryIdentity) -> AsyncIterator[None]:
|
|
266
|
+
"""Hold the session for the turn, refusing at once when another turn holds it."""
|
|
267
|
+
if identity.session_id is None:
|
|
268
|
+
yield
|
|
269
|
+
return
|
|
270
|
+
async with self._locks.hold(identity.conversation(), wait=False):
|
|
271
|
+
yield
|
|
272
|
+
|
|
273
|
+
async def _scope_history(
|
|
274
|
+
self, identity: MemoryIdentity, options: ChatExecutionOptions
|
|
275
|
+
) -> ScopeHistory | None:
|
|
276
|
+
"""Classic only: the history the scope check reads, read before any model call."""
|
|
277
|
+
if options.mode != "classic":
|
|
278
|
+
return None
|
|
279
|
+
return await scope_history(self._resources, _access(identity))
|
|
280
|
+
|
|
281
|
+
async def _check_scope(
|
|
282
|
+
self,
|
|
283
|
+
query: str,
|
|
284
|
+
identity: MemoryIdentity,
|
|
285
|
+
options: ChatExecutionOptions,
|
|
286
|
+
history: ScopeHistory | None,
|
|
287
|
+
) -> ScopeCheck | None:
|
|
288
|
+
"""Classic only: the scope check's call and, out of scope, the refusal to answer with."""
|
|
289
|
+
if history is None:
|
|
290
|
+
return None
|
|
291
|
+
try:
|
|
292
|
+
return await check_query_scope(
|
|
293
|
+
self._resources,
|
|
294
|
+
query,
|
|
295
|
+
_access(identity),
|
|
296
|
+
history=history,
|
|
297
|
+
model=options.model,
|
|
298
|
+
trace_id=options.trace_id,
|
|
299
|
+
)
|
|
300
|
+
except _MODEL_FAILURES as exc:
|
|
301
|
+
raise ChatModelUnavailableError("The chat model is unavailable") from exc
|
|
302
|
+
|
|
303
|
+
async def _generate(
|
|
304
|
+
self, prepared: PreparedTurn, identity: MemoryIdentity, options: ChatExecutionOptions
|
|
305
|
+
) -> HarborChatResponse:
|
|
306
|
+
"""Call the answer model and account for the call, whatever it answered."""
|
|
307
|
+
try:
|
|
308
|
+
response = await self._resources.runtime().chat.complete(
|
|
309
|
+
prepared.request, prompt=options.system
|
|
310
|
+
)
|
|
311
|
+
except _MODEL_FAILURES as exc:
|
|
312
|
+
raise ChatModelUnavailableError("The chat model is unavailable") from exc
|
|
313
|
+
await record_model_usage(self._resources.usage, identity, ModelCall.from_response(response))
|
|
314
|
+
return response
|
|
315
|
+
|
|
316
|
+
async def _remember(
|
|
317
|
+
self,
|
|
318
|
+
query: str,
|
|
319
|
+
identity: MemoryIdentity,
|
|
320
|
+
completion: Completion,
|
|
321
|
+
answer_tokens: int | None,
|
|
322
|
+
) -> None:
|
|
323
|
+
"""Store a session's exchange under the completion's id, with the answer's own tokens."""
|
|
324
|
+
if identity.session_id is None:
|
|
325
|
+
return
|
|
326
|
+
owner = identity.conversation()
|
|
327
|
+
try:
|
|
328
|
+
await record_exchange(
|
|
329
|
+
self._resources.memory,
|
|
330
|
+
owner,
|
|
331
|
+
ExchangeRecord(
|
|
332
|
+
question=query,
|
|
333
|
+
answer=completion.answer,
|
|
334
|
+
mode=completion.mode,
|
|
335
|
+
trace_id=completion.trace_id,
|
|
336
|
+
citations=completion.citations,
|
|
337
|
+
completion_tokens=answer_tokens,
|
|
338
|
+
answer_id=completion.completion_id,
|
|
339
|
+
),
|
|
340
|
+
)
|
|
341
|
+
except HarborError:
|
|
342
|
+
raise
|
|
343
|
+
except Exception as exc:
|
|
344
|
+
raise HarborConnectionError(
|
|
345
|
+
"The answer could not be stored in the session's history"
|
|
346
|
+
) from exc
|
|
347
|
+
await conversation_title(self._resources.memory, owner, prompt=query)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _access(identity: MemoryIdentity) -> MemoryAccess:
|
|
351
|
+
"""Return the memory access key of ``identity``."""
|
|
352
|
+
return MemoryAccess(
|
|
353
|
+
tenant_id=identity.tenant_id,
|
|
354
|
+
principal_id=identity.principal_id,
|
|
355
|
+
user_id=identity.user_id,
|
|
356
|
+
project_id=identity.project_id,
|
|
357
|
+
session_id=identity.session_id,
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _usage(options: ChatExecutionOptions, calls: Sequence[HarborChatResponse]) -> CompletionUsage:
|
|
362
|
+
"""Total the tokens and cost of the turn's model calls; ``cost_usd`` is ``None`` when one is unpriced."""
|
|
363
|
+
costs = [call.estimated_cost_usd for call in calls]
|
|
364
|
+
return CompletionUsage(
|
|
365
|
+
mode=options.mode,
|
|
366
|
+
steps=1,
|
|
367
|
+
prompt_tokens=sum(call.usage.prompt_tokens for call in calls),
|
|
368
|
+
completion_tokens=sum(call.usage.completion_tokens for call in calls),
|
|
369
|
+
reasoning_tokens=sum(call.usage.reasoning_tokens or 0 for call in calls),
|
|
370
|
+
cost_usd=None if None in costs else sum(cost for cost in costs if cost is not None),
|
|
371
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Application-service composition and lifecycle."""
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Typed collaborator factories for application-service composition."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Protocol
|
|
8
|
+
|
|
9
|
+
from harborrag_core.ingestion import IngestionTask, IngestionTaskState
|
|
10
|
+
from harborrag_core.ports.events import EventBusPort
|
|
11
|
+
from harborrag_core.security import AccessContext
|
|
12
|
+
from harborrag_runtime.config.settings import RuntimeSettings
|
|
13
|
+
from harborrag_runtime.events import InProcessEventBus
|
|
14
|
+
from harborrag_runtime.execution.gateway import (
|
|
15
|
+
IngestionGatewayDescription,
|
|
16
|
+
connect_ingestion_gateway,
|
|
17
|
+
connect_schedule_backend,
|
|
18
|
+
describe_ingestion_gateway,
|
|
19
|
+
prepare_configured_source_submission,
|
|
20
|
+
)
|
|
21
|
+
from harborrag_runtime.execution.gateway import (
|
|
22
|
+
connect_temporal_client as connect_temporal_client,
|
|
23
|
+
)
|
|
24
|
+
from harborrag_runtime.execution.task_registry import IngestionTaskRegistry
|
|
25
|
+
from harborrag_runtime.ingestion_contracts import IngestionGateway
|
|
26
|
+
from harborrag_runtime.scheduling import ScheduleBackend
|
|
27
|
+
from harborrag_runtime.sdk import HarborRAG, HarborRAGConfig
|
|
28
|
+
|
|
29
|
+
from ..ingestion.connection_sources import SourcePreparation
|
|
30
|
+
from ..ingestion.ports import PublicTaskStore, SourceInputBuilder
|
|
31
|
+
|
|
32
|
+
type ClientFactory = Callable[
|
|
33
|
+
[RuntimeSettings],
|
|
34
|
+
Awaitable[IngestionGateway],
|
|
35
|
+
]
|
|
36
|
+
type ScheduleBackendFactory = Callable[[RuntimeSettings], Awaitable[ScheduleBackend]]
|
|
37
|
+
type GatewayDescriptionFactory = Callable[[RuntimeSettings], IngestionGatewayDescription]
|
|
38
|
+
type RetrievalRuntimeFactory = Callable[[RuntimeSettings], HarborRAG]
|
|
39
|
+
type EventBusFactory = Callable[[], EventBusPort]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class TaskRegistry(PublicTaskStore, Protocol):
|
|
43
|
+
"""Task registry with the public task store plus the connection run queries."""
|
|
44
|
+
|
|
45
|
+
async def latest_for_connection(
|
|
46
|
+
self, *, tenant_id: str, connection_id: str
|
|
47
|
+
) -> IngestionTask | None:
|
|
48
|
+
"""Return the connection's most recently submitted run, or ``None`` when it has none."""
|
|
49
|
+
|
|
50
|
+
async def active_for_connection(
|
|
51
|
+
self, *, tenant_id: str, connection_id: str
|
|
52
|
+
) -> IngestionTask | None:
|
|
53
|
+
"""Return the connection's run that has not ended, or ``None`` when it has none."""
|
|
54
|
+
|
|
55
|
+
async def connection_document_count(self, *, tenant_id: str, connection_id: str) -> int:
|
|
56
|
+
"""Count the documents the connection's runs have recorded."""
|
|
57
|
+
|
|
58
|
+
async def failure_stages_for_tasks(self, task_ids: Sequence[str]) -> dict[str, dict[str, int]]:
|
|
59
|
+
"""Return failed-document counts by internal failure step for each of ``task_ids``."""
|
|
60
|
+
|
|
61
|
+
async def source_scope_ids_by_connection(
|
|
62
|
+
self, *, tenant_id: str, connection_ids: Sequence[str]
|
|
63
|
+
) -> dict[str, list[str]]:
|
|
64
|
+
"""Return the source scope IDs each of ``connection_ids`` was ingested under."""
|
|
65
|
+
|
|
66
|
+
async def allowed_source_scope_ids(
|
|
67
|
+
self, tenant_id: str, *, access: AccessContext, limit: int = 10000
|
|
68
|
+
) -> tuple[str, ...]:
|
|
69
|
+
"""Return every source scope ``access`` may read in ``tenant_id``."""
|
|
70
|
+
|
|
71
|
+
async def published_connection_ids(
|
|
72
|
+
self, *, tenant_id: str, connection_ids: Sequence[str]
|
|
73
|
+
) -> set[str]:
|
|
74
|
+
"""Return which of ``connection_ids`` have published documents."""
|
|
75
|
+
|
|
76
|
+
async def fail_if_unsubmitted(
|
|
77
|
+
self,
|
|
78
|
+
task_id: str,
|
|
79
|
+
*,
|
|
80
|
+
summary: Mapping[str, object],
|
|
81
|
+
) -> IngestionTaskState | None:
|
|
82
|
+
"""Fail the run when its workflow start was never confirmed; return its state afterwards."""
|
|
83
|
+
|
|
84
|
+
async def close(self) -> None:
|
|
85
|
+
"""Release the registry's database resources."""
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
type TaskRegistryFactory = Callable[[RuntimeSettings], Awaitable[TaskRegistry]]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _retrieval_runtime(settings: RuntimeSettings) -> HarborRAG:
|
|
92
|
+
return HarborRAG(HarborRAGConfig(runtime=settings))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass(frozen=True, slots=True)
|
|
96
|
+
class AppServiceFactories:
|
|
97
|
+
"""Collaborator factories, grouped so composition stays overridable in tests."""
|
|
98
|
+
|
|
99
|
+
client: ClientFactory = connect_ingestion_gateway
|
|
100
|
+
schedule_backend: ScheduleBackendFactory = connect_schedule_backend
|
|
101
|
+
ingestion_description: GatewayDescriptionFactory = describe_ingestion_gateway
|
|
102
|
+
retrieval_runtime: RetrievalRuntimeFactory = _retrieval_runtime
|
|
103
|
+
source_input_builder: SourceInputBuilder | None = None
|
|
104
|
+
source_preparation: SourcePreparation = prepare_configured_source_submission
|
|
105
|
+
task_registry: TaskRegistryFactory = IngestionTaskRegistry.connect
|
|
106
|
+
event_bus: EventBusFactory = InProcessEventBus
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Lazily created, singly closed runtime resources for the application service.
|
|
2
|
+
|
|
3
|
+
Resource lifecycle is a separate reason to change from the use cases that consume the
|
|
4
|
+
resources, so it lives here rather than as private helpers on AppService.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
from harborrag_runtime.composition.connection_removal import ConnectionRemoval
|
|
13
|
+
from harborrag_runtime.config.settings import RuntimeSettings
|
|
14
|
+
from harborrag_runtime.ingestion_contracts import IngestionGateway
|
|
15
|
+
from harborrag_runtime.scheduling import ScheduleBackend
|
|
16
|
+
from harborrag_runtime.sdk import HarborRAG
|
|
17
|
+
|
|
18
|
+
from .tenant_models import tenant_model_sources
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from harborrag_core.ports.events import EventBusPort
|
|
22
|
+
|
|
23
|
+
from ..ingestion.ports import PublicTaskStore
|
|
24
|
+
from .factories import AppServiceFactories, TaskRegistry
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AppResources:
|
|
28
|
+
"""Create each runtime resource at most once and release them together.
|
|
29
|
+
|
|
30
|
+
Whether a tenant may bring its own chat models is a property of this process, not of a
|
|
31
|
+
request, so it is resolved once here rather than per SDK build; ``None`` keeps the single
|
|
32
|
+
process-wide chat client.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
settings: Runtime settings every factory receives.
|
|
36
|
+
factories: Factories that create the gateway, backends, SDK, registry and event bus.
|
|
37
|
+
composition: Composition root the per-tenant chat model ports are read from.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
settings: RuntimeSettings,
|
|
43
|
+
*,
|
|
44
|
+
factories: AppServiceFactories,
|
|
45
|
+
composition: object | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
self._settings = settings
|
|
48
|
+
self._factories = factories
|
|
49
|
+
self._tenant_models = tenant_model_sources(composition, settings)
|
|
50
|
+
self._client: IngestionGateway | None = None
|
|
51
|
+
self._schedule_backend: ScheduleBackend | None = None
|
|
52
|
+
self._retrieval_runtime: HarborRAG | None = None
|
|
53
|
+
self._task_registry: TaskRegistry | None = None
|
|
54
|
+
self._event_bus: EventBusPort | None = None
|
|
55
|
+
self._connection_removal: ConnectionRemoval | None = None
|
|
56
|
+
self._client_lock = asyncio.Lock()
|
|
57
|
+
self._schedule_backend_lock = asyncio.Lock()
|
|
58
|
+
self._task_registry_lock = asyncio.Lock()
|
|
59
|
+
|
|
60
|
+
async def runtime_client(self) -> IngestionGateway:
|
|
61
|
+
"""Return the ingestion gateway, connecting on first use."""
|
|
62
|
+
if self._client is not None:
|
|
63
|
+
return self._client
|
|
64
|
+
async with self._client_lock:
|
|
65
|
+
if self._client is None:
|
|
66
|
+
self._client = await self._factories.client(self._settings)
|
|
67
|
+
return self._client
|
|
68
|
+
|
|
69
|
+
async def schedule_backend(self) -> ScheduleBackend:
|
|
70
|
+
"""Return the schedule backend, connecting on first use."""
|
|
71
|
+
if self._schedule_backend is not None:
|
|
72
|
+
return self._schedule_backend
|
|
73
|
+
async with self._schedule_backend_lock:
|
|
74
|
+
if self._schedule_backend is None:
|
|
75
|
+
self._schedule_backend = await self._factories.schedule_backend(self._settings)
|
|
76
|
+
return self._schedule_backend
|
|
77
|
+
|
|
78
|
+
def runtime_sdk(self) -> HarborRAG:
|
|
79
|
+
"""Build the SDK once, telling chat about tenant catalogs if any are wired.
|
|
80
|
+
|
|
81
|
+
The factory takes settings only -- the catalog and the secret store are
|
|
82
|
+
ports, not configuration -- so they are handed to the SDK right after
|
|
83
|
+
it is constructed and before any turn can reach it.
|
|
84
|
+
"""
|
|
85
|
+
if self._retrieval_runtime is None:
|
|
86
|
+
self._retrieval_runtime = self._factories.retrieval_runtime(self._settings)
|
|
87
|
+
if self._tenant_models is not None:
|
|
88
|
+
self._retrieval_runtime.configure_tenant_models(self._tenant_models)
|
|
89
|
+
return self._retrieval_runtime
|
|
90
|
+
|
|
91
|
+
async def task_registry(self) -> TaskRegistry:
|
|
92
|
+
"""Return the task registry, connecting on first use."""
|
|
93
|
+
if self._task_registry is not None:
|
|
94
|
+
return self._task_registry
|
|
95
|
+
async with self._task_registry_lock:
|
|
96
|
+
if self._task_registry is None:
|
|
97
|
+
self._task_registry = await self._factories.task_registry(self._settings)
|
|
98
|
+
return self._task_registry
|
|
99
|
+
|
|
100
|
+
async def public_task_store(self) -> PublicTaskStore:
|
|
101
|
+
"""Return the task registry as the public task store."""
|
|
102
|
+
return await self.task_registry()
|
|
103
|
+
|
|
104
|
+
def connection_removal(self) -> ConnectionRemoval:
|
|
105
|
+
"""Return the stores connection removals use, built on first use."""
|
|
106
|
+
if self._connection_removal is None:
|
|
107
|
+
self._connection_removal = ConnectionRemoval(self._settings)
|
|
108
|
+
return self._connection_removal
|
|
109
|
+
|
|
110
|
+
def event_bus(self) -> EventBusPort:
|
|
111
|
+
"""Return the event bus, created on first use."""
|
|
112
|
+
if self._event_bus is None:
|
|
113
|
+
self._event_bus = self._factories.event_bus()
|
|
114
|
+
return self._event_bus
|
|
115
|
+
|
|
116
|
+
async def aclose(self) -> None:
|
|
117
|
+
"""Close every resource that was created, then report any failures together.
|
|
118
|
+
|
|
119
|
+
Temporal clients (the ingestion gateway and the schedule backend) expose no close;
|
|
120
|
+
their connections end with the process. Every close runs even when another fails, so
|
|
121
|
+
one failing resource cannot keep its siblings from releasing.
|
|
122
|
+
|
|
123
|
+
Raises:
|
|
124
|
+
ExceptionGroup: One or more resources failed to close.
|
|
125
|
+
"""
|
|
126
|
+
closers = [
|
|
127
|
+
resource
|
|
128
|
+
for resource in (
|
|
129
|
+
self._retrieval_runtime.aclose if self._retrieval_runtime else None,
|
|
130
|
+
self._task_registry.close if self._task_registry else None,
|
|
131
|
+
self._connection_removal.aclose if self._connection_removal else None,
|
|
132
|
+
)
|
|
133
|
+
if resource is not None
|
|
134
|
+
]
|
|
135
|
+
results = await asyncio.gather(
|
|
136
|
+
*(close() for close in closers),
|
|
137
|
+
return_exceptions=True,
|
|
138
|
+
)
|
|
139
|
+
errors = [result for result in results if isinstance(result, Exception)]
|
|
140
|
+
if errors:
|
|
141
|
+
raise ExceptionGroup("application resource close failed", errors)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Selection of the configured application service, free of API-only dependencies.
|
|
2
|
+
|
|
3
|
+
Runtime imports stay inside the functions so importing this module stays cheap.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
|
|
11
|
+
from ..ports import BaseAppService
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from harborrag_runtime.config.settings import RuntimeSettings
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger("harborrag.runtime.application.composition.selection")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def select_app_service() -> tuple[BaseAppService, str]:
|
|
20
|
+
"""Compose the app service for the API after checking the parser catalog.
|
|
21
|
+
|
|
22
|
+
A missing catalog file is logged and left to ingestion to report, so an
|
|
23
|
+
API without ingestion configuration still starts.
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
The app service and the name of its composition mode.
|
|
27
|
+
|
|
28
|
+
Raises:
|
|
29
|
+
ParserConfigurationError: The parser catalog file exists but is invalid.
|
|
30
|
+
"""
|
|
31
|
+
from harborrag_runtime.config import load_parser_catalog
|
|
32
|
+
from harborrag_runtime.config.settings import RuntimeSettings
|
|
33
|
+
|
|
34
|
+
settings = RuntimeSettings()
|
|
35
|
+
if settings.parser_config_path.is_file():
|
|
36
|
+
load_parser_catalog(settings.parser_config_path)
|
|
37
|
+
else:
|
|
38
|
+
logger.warning(
|
|
39
|
+
"Parser catalog %s not found; skipping its startup check",
|
|
40
|
+
settings.parser_config_path,
|
|
41
|
+
)
|
|
42
|
+
return _app_service_from(settings), "production"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def runtime_app_service() -> BaseAppService:
|
|
46
|
+
"""Compose the app service from environment settings, as the CLI does."""
|
|
47
|
+
from harborrag_runtime.config.settings import RuntimeSettings
|
|
48
|
+
|
|
49
|
+
return _app_service_from(RuntimeSettings())
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def get_app_service() -> BaseAppService:
|
|
53
|
+
"""Compose the API's app service without reporting its composition mode."""
|
|
54
|
+
service, _ = select_app_service()
|
|
55
|
+
return service
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _app_service_from(settings: RuntimeSettings) -> BaseAppService:
|
|
59
|
+
"""Build the production composition and the app service on top of it."""
|
|
60
|
+
from harborrag_runtime.composition import CompositionRoot
|
|
61
|
+
|
|
62
|
+
from .service import AppService
|
|
63
|
+
|
|
64
|
+
composition = CompositionRoot.production(settings)
|
|
65
|
+
return AppService(composition, settings)
|