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,749 @@
|
|
|
1
|
+
"""Connection use cases: read, write, test, sync and delete one configured data source.
|
|
2
|
+
|
|
3
|
+
``put`` replaces the whole config (secret keep, rotate or clear; ETag preconditions), ``test``
|
|
4
|
+
saves nothing, ``sync`` allows one active ingestion per connection, and ``delete`` removes the
|
|
5
|
+
connection from every store in the background, resumed after a restart. Does not speak HTTP.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import logging
|
|
12
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
13
|
+
from dataclasses import replace
|
|
14
|
+
from typing import TYPE_CHECKING, Any, Final
|
|
15
|
+
from uuid import uuid4
|
|
16
|
+
|
|
17
|
+
from harborrag_adapters.connectors.policies.network import DestinationPolicy
|
|
18
|
+
from harborrag_core.base import utc_now
|
|
19
|
+
from harborrag_core.contracts.errors import (
|
|
20
|
+
HarborAlreadyRunningError,
|
|
21
|
+
HarborCapabilityError,
|
|
22
|
+
HarborConflictError,
|
|
23
|
+
HarborError,
|
|
24
|
+
HarborNotFoundError,
|
|
25
|
+
HarborPreconditionFailedError,
|
|
26
|
+
HarborUnavailableError,
|
|
27
|
+
)
|
|
28
|
+
from harborrag_core.domain.activity import ActivityEntry
|
|
29
|
+
from harborrag_core.domain.connection import Connection, ConnectionStatus, require_connection_id
|
|
30
|
+
from harborrag_core.domain.job import Job, JobStatus
|
|
31
|
+
from harborrag_core.ingestion import IngestionTask
|
|
32
|
+
from harborrag_core.schemas.ids import TenantId
|
|
33
|
+
from harborrag_core.security import AccessContext
|
|
34
|
+
from harborrag_core.security.secret_refs import stored_refs
|
|
35
|
+
from harborrag_engine.control_plane.connection_views import (
|
|
36
|
+
ingestion_view,
|
|
37
|
+
read_connection_views,
|
|
38
|
+
resolve_any_version,
|
|
39
|
+
)
|
|
40
|
+
from harborrag_engine.ingestion.models import IngestionCreateCommand
|
|
41
|
+
from harborrag_runtime.composition import ControlPlaneRepositories
|
|
42
|
+
from harborrag_runtime.config.connectors.models import (
|
|
43
|
+
ConnectionValidationError,
|
|
44
|
+
FieldIssue,
|
|
45
|
+
source_types,
|
|
46
|
+
)
|
|
47
|
+
from harborrag_runtime.config.connectors.models.builder import validate_connection
|
|
48
|
+
from harborrag_runtime.connections import (
|
|
49
|
+
CredentialSecretWriter,
|
|
50
|
+
SecretUnavailableError,
|
|
51
|
+
default_secret_resolver,
|
|
52
|
+
reference_issues,
|
|
53
|
+
)
|
|
54
|
+
from harborrag_runtime.ingestion.connection_checks import ConnectionTestReport
|
|
55
|
+
from harborrag_runtime.ingestion.connections import ConnectionUnavailableError
|
|
56
|
+
|
|
57
|
+
from ..retrieval.access import corpus_mode_for
|
|
58
|
+
from .active_runs import active_run
|
|
59
|
+
from .connection_models import (
|
|
60
|
+
ConnectionKey,
|
|
61
|
+
ConnectionPutResult,
|
|
62
|
+
ConnectionRuns,
|
|
63
|
+
ConnectionWrite,
|
|
64
|
+
IngestionSubmitter,
|
|
65
|
+
WriteOrigin,
|
|
66
|
+
)
|
|
67
|
+
from .connection_testing import run_checks
|
|
68
|
+
from .connection_writes import (
|
|
69
|
+
ConcurrentWriteError,
|
|
70
|
+
build_connection,
|
|
71
|
+
changed_fields,
|
|
72
|
+
check_preconditions,
|
|
73
|
+
effective_credentials,
|
|
74
|
+
merge_secrets,
|
|
75
|
+
plan_credentials,
|
|
76
|
+
refuse_operator_fields,
|
|
77
|
+
secret_sources,
|
|
78
|
+
unchanged,
|
|
79
|
+
validate_write,
|
|
80
|
+
)
|
|
81
|
+
from .effect_recovery import defer_retirement, log_activity, retire_refs
|
|
82
|
+
|
|
83
|
+
if TYPE_CHECKING:
|
|
84
|
+
from harborrag_runtime.composition.connection_removal import ConnectionRemoval
|
|
85
|
+
from harborrag_runtime.config.settings import RuntimeSettings
|
|
86
|
+
|
|
87
|
+
logger = logging.getLogger("harborrag.runtime.application.control_plane.connections")
|
|
88
|
+
|
|
89
|
+
_DELETE_CONNECTION_JOB: Final = "delete_connection"
|
|
90
|
+
SYNC_LEASE_TTL_SECONDS = 5.0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class ConnectionService:
|
|
94
|
+
"""Facade over the connection repository, secrets, ingestion runs and removal.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
control_plane: Returns the control-plane repositories.
|
|
98
|
+
runs: Returns the run registry of connections, which also answers source ACLs.
|
|
99
|
+
ingestions: Starts ingestions and settles runs that ended unrecorded.
|
|
100
|
+
removal: Returns the stores a connection removal clears.
|
|
101
|
+
destination_policy: Hosts a connection test may reach beyond public addresses.
|
|
102
|
+
instance_id: ID of this process, which names the holder of a connection sync lease.
|
|
103
|
+
settings: Settings that choose each tenant's corpus mode.
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
def __init__( # noqa: PLR0913 - the stores and settings the service composes
|
|
107
|
+
self,
|
|
108
|
+
*,
|
|
109
|
+
control_plane: Callable[[], ControlPlaneRepositories],
|
|
110
|
+
runs: Callable[[], Awaitable[ConnectionRuns]],
|
|
111
|
+
ingestions: IngestionSubmitter,
|
|
112
|
+
removal: Callable[[], ConnectionRemoval],
|
|
113
|
+
destination_policy: DestinationPolicy,
|
|
114
|
+
instance_id: str,
|
|
115
|
+
settings: RuntimeSettings,
|
|
116
|
+
) -> None:
|
|
117
|
+
self._control_plane = control_plane
|
|
118
|
+
self._runs = runs
|
|
119
|
+
self._ingestions = ingestions
|
|
120
|
+
self._removal = removal
|
|
121
|
+
self._destination_policy = destination_policy
|
|
122
|
+
self._instance_id = instance_id
|
|
123
|
+
self._settings = settings
|
|
124
|
+
self._background: set[asyncio.Task[None]] = set()
|
|
125
|
+
self._removing: set[tuple[str, str]] = set()
|
|
126
|
+
|
|
127
|
+
async def get(self, key: ConnectionKey) -> tuple[dict[str, Any], int]:
|
|
128
|
+
"""Return a connection's view and version.
|
|
129
|
+
|
|
130
|
+
Raises:
|
|
131
|
+
ConnectionValidationError: ``connection_id`` is malformed.
|
|
132
|
+
HarborNotFoundError: No such connection in the tenant.
|
|
133
|
+
"""
|
|
134
|
+
_require_connection_id(key)
|
|
135
|
+
connection = await self._require(key)
|
|
136
|
+
return await self._view(connection), connection.version
|
|
137
|
+
|
|
138
|
+
async def stored(self, key: ConnectionKey) -> Connection:
|
|
139
|
+
"""Return the stored row with the ``source_key`` runs use; not found as ``get`` raises."""
|
|
140
|
+
return await self._require(key)
|
|
141
|
+
|
|
142
|
+
async def list_page( # noqa: PLR0913 - the spec's list filters plus paging
|
|
143
|
+
self,
|
|
144
|
+
*,
|
|
145
|
+
tenant_id: str,
|
|
146
|
+
project_id: str | None = None,
|
|
147
|
+
source_type: str | None = None,
|
|
148
|
+
status: ConnectionStatus | None = None,
|
|
149
|
+
limit: int = 20,
|
|
150
|
+
cursor: str | None = None,
|
|
151
|
+
) -> tuple[list[dict[str, Any]], str | None]:
|
|
152
|
+
"""Return one page of the tenant's connections, needing attention first."""
|
|
153
|
+
canonical = source_types.canonical(source_type) if source_type else None
|
|
154
|
+
connections, next_cursor = await self._control_plane().connections.list(
|
|
155
|
+
tenant_ids=frozenset({tenant_id}),
|
|
156
|
+
project_id=project_id,
|
|
157
|
+
source_type=canonical or source_type,
|
|
158
|
+
status=status,
|
|
159
|
+
limit=limit,
|
|
160
|
+
cursor=cursor,
|
|
161
|
+
)
|
|
162
|
+
views = await read_connection_views(await self._runs(), connections, batch=True)
|
|
163
|
+
return views, next_cursor
|
|
164
|
+
|
|
165
|
+
async def searchable(
|
|
166
|
+
self, *, tenant_id: str, project_id: str, principal_id: str
|
|
167
|
+
) -> list[dict[str, Any]]:
|
|
168
|
+
"""List the connections of one project the reader can search, as filter chips.
|
|
169
|
+
|
|
170
|
+
Under ``source_acl`` a connection is listed only when the reader may read one of
|
|
171
|
+
its source scopes, so one never ingested is not listed. ``tenant_shared`` lists
|
|
172
|
+
every connection.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
tenant_id: Tenant of the project.
|
|
176
|
+
project_id: Project whose connections to list.
|
|
177
|
+
principal_id: Subject the source ACL checks, such as an API key's owner.
|
|
178
|
+
|
|
179
|
+
Raises:
|
|
180
|
+
HarborNotFoundError: The project does not exist in the tenant.
|
|
181
|
+
HarborConflictError: The reader may read more source scopes than the
|
|
182
|
+
permission store enumerates.
|
|
183
|
+
"""
|
|
184
|
+
control_plane = self._control_plane()
|
|
185
|
+
tenants = frozenset({tenant_id})
|
|
186
|
+
if await control_plane.projects.get(project_id, tenant_ids=tenants) is None:
|
|
187
|
+
raise HarborNotFoundError(f"project {project_id!r} not found")
|
|
188
|
+
connections, _ = await control_plane.connections.list(
|
|
189
|
+
tenant_ids=tenants, project_id=project_id
|
|
190
|
+
)
|
|
191
|
+
runs = await self._runs()
|
|
192
|
+
live = [connection for connection in connections if connection.status != "deleting"]
|
|
193
|
+
readable = await self._readable(runs, tenant_id, principal_id, live)
|
|
194
|
+
return [
|
|
195
|
+
{
|
|
196
|
+
"connection_ref": connection.ref,
|
|
197
|
+
"connection_id": connection.connection_id,
|
|
198
|
+
"source_type": connection.source_type,
|
|
199
|
+
"name": connection.name,
|
|
200
|
+
"documents": await runs.connection_document_count(
|
|
201
|
+
tenant_id=tenant_id, connection_id=connection.source_key
|
|
202
|
+
),
|
|
203
|
+
}
|
|
204
|
+
for connection in readable
|
|
205
|
+
]
|
|
206
|
+
|
|
207
|
+
async def _readable(
|
|
208
|
+
self,
|
|
209
|
+
runs: ConnectionRuns,
|
|
210
|
+
tenant_id: str,
|
|
211
|
+
principal_id: str,
|
|
212
|
+
connections: list[Connection],
|
|
213
|
+
) -> list[Connection]:
|
|
214
|
+
"""Keep the connections with a source scope the reader may read; all under ``tenant_shared``."""
|
|
215
|
+
access = AccessContext(
|
|
216
|
+
principal_id=principal_id,
|
|
217
|
+
tenant_id=TenantId(tenant_id),
|
|
218
|
+
corpus_mode=corpus_mode_for(self._settings, tenant_id),
|
|
219
|
+
)
|
|
220
|
+
if access.corpus_mode == "tenant_shared" or not connections:
|
|
221
|
+
return connections
|
|
222
|
+
allowed = set(await runs.allowed_source_scope_ids(tenant_id, access=access))
|
|
223
|
+
scopes = await runs.source_scope_ids_by_connection(
|
|
224
|
+
tenant_id=tenant_id,
|
|
225
|
+
connection_ids=[connection.source_key for connection in connections],
|
|
226
|
+
)
|
|
227
|
+
return [
|
|
228
|
+
connection
|
|
229
|
+
for connection in connections
|
|
230
|
+
if allowed.intersection(scopes.get(connection.source_key, ()))
|
|
231
|
+
]
|
|
232
|
+
|
|
233
|
+
async def put( # noqa: PLR0913 - one body plus its preconditions
|
|
234
|
+
self,
|
|
235
|
+
key: ConnectionKey,
|
|
236
|
+
write: ConnectionWrite,
|
|
237
|
+
*,
|
|
238
|
+
actor: str,
|
|
239
|
+
expected_version: int | None = None,
|
|
240
|
+
create_only: bool = False,
|
|
241
|
+
sync_now: bool = False,
|
|
242
|
+
origin: WriteOrigin = "api",
|
|
243
|
+
) -> ConnectionPutResult:
|
|
244
|
+
"""Create or overwrite a connection.
|
|
245
|
+
|
|
246
|
+
``config`` is replaced whole, and so is ``tuning`` unless it is left out,
|
|
247
|
+
which keeps the stored tuning. A body that changes nothing stores nothing:
|
|
248
|
+
the version and ``updated_at`` stay. In ``credentials`` an omitted secret keeps
|
|
249
|
+
its value while the auth method and endpoints stay the same, a new value
|
|
250
|
+
rotates it, a ``{"secret_ref"}`` points it elsewhere and ``null`` clears
|
|
251
|
+
it; replaced stored secrets are deleted once no running ingestion still
|
|
252
|
+
uses them. A failed ``sync_now`` keeps the saved connection.
|
|
253
|
+
|
|
254
|
+
Args:
|
|
255
|
+
key: The connection's tenant, project and ``connection_id``.
|
|
256
|
+
write: Source type, name, credentials and config as sent.
|
|
257
|
+
actor: Subject of the caller's token.
|
|
258
|
+
expected_version: ``If-Match`` version, when sent.
|
|
259
|
+
create_only: ``If-None-Match: *`` was sent.
|
|
260
|
+
sync_now: Start an incremental sync after saving.
|
|
261
|
+
origin: ``operator`` lets the write set new ``env:`` references.
|
|
262
|
+
|
|
263
|
+
Returns:
|
|
264
|
+
The stored connection, whether it was created, and the started
|
|
265
|
+
ingestion or the error that kept ``sync_now`` from starting one.
|
|
266
|
+
|
|
267
|
+
Raises:
|
|
268
|
+
HarborNotFoundError: The project does not exist in the tenant.
|
|
269
|
+
ConnectionValidationError: ``connection_id`` is malformed, the type is unknown,
|
|
270
|
+
a field fails its schema, an endpoint changed while a stored secret would
|
|
271
|
+
be kept, or an ``api`` write sets a new ``env:`` reference or changes an
|
|
272
|
+
operator-only field.
|
|
273
|
+
HarborImmutableFieldError: The connection exists with another source type.
|
|
274
|
+
HarborPreconditionFailedError: ``If-Match`` or ``If-None-Match`` does not hold.
|
|
275
|
+
HarborConflictError: Without either, another write landed twice in a row
|
|
276
|
+
between reading the connection and saving it.
|
|
277
|
+
ConnectionUnavailableError: The connection is being deleted.
|
|
278
|
+
"""
|
|
279
|
+
_require_connection_id(key)
|
|
280
|
+
guarded = expected_version is None and not create_only
|
|
281
|
+
for attempt in range(2 if guarded else 1):
|
|
282
|
+
try:
|
|
283
|
+
return await self._put_once(
|
|
284
|
+
key,
|
|
285
|
+
write,
|
|
286
|
+
actor=actor,
|
|
287
|
+
expected_version=expected_version,
|
|
288
|
+
create_only=create_only,
|
|
289
|
+
sync_now=sync_now,
|
|
290
|
+
origin=origin,
|
|
291
|
+
guarded=guarded,
|
|
292
|
+
)
|
|
293
|
+
except ConcurrentWriteError:
|
|
294
|
+
logger.info("connection %s changed while saving; attempt %d", key, attempt + 1)
|
|
295
|
+
raise HarborConflictError(
|
|
296
|
+
"the connection changed while it was being saved; read it and send it again"
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
async def _put_once( # noqa: PLR0913 - one body plus its preconditions
|
|
300
|
+
self,
|
|
301
|
+
key: ConnectionKey,
|
|
302
|
+
write: ConnectionWrite,
|
|
303
|
+
*,
|
|
304
|
+
actor: str,
|
|
305
|
+
expected_version: int | None,
|
|
306
|
+
create_only: bool,
|
|
307
|
+
sync_now: bool,
|
|
308
|
+
origin: WriteOrigin,
|
|
309
|
+
guarded: bool,
|
|
310
|
+
) -> ConnectionPutResult:
|
|
311
|
+
"""Run one save; ``guarded`` writes only over the version read here.
|
|
312
|
+
|
|
313
|
+
Raises:
|
|
314
|
+
ConcurrentWriteError: ``guarded`` and another write landed first.
|
|
315
|
+
"""
|
|
316
|
+
control_plane = self._control_plane()
|
|
317
|
+
await self._require_project(key)
|
|
318
|
+
spec = source_types.get(write.source_type)
|
|
319
|
+
existing = await control_plane.connections.get(
|
|
320
|
+
tenant_id=key.tenant_id, project_id=key.project_id, connection_id=key.connection_id
|
|
321
|
+
)
|
|
322
|
+
expected_version = resolve_any_version(
|
|
323
|
+
expected_version, existing.version if existing else None
|
|
324
|
+
)
|
|
325
|
+
check_preconditions(existing, spec, expected_version, create_only)
|
|
326
|
+
refuse_operator_fields(spec, write, existing, origin)
|
|
327
|
+
sent, keep = plan_credentials(write.credentials, existing, spec)
|
|
328
|
+
validated = validate_write(
|
|
329
|
+
spec, effective_credentials(sent, existing, keep), write, existing, key.tenant_id
|
|
330
|
+
)
|
|
331
|
+
written = await CredentialSecretWriter(
|
|
332
|
+
control_plane.secrets, tenant_id=key.tenant_id, sources=secret_sources(origin)
|
|
333
|
+
).apply(
|
|
334
|
+
sent,
|
|
335
|
+
secret_fields=spec.secret_fields,
|
|
336
|
+
existing=existing.credentials if existing else None,
|
|
337
|
+
keep=keep,
|
|
338
|
+
)
|
|
339
|
+
credentials = merge_secrets(validated.credentials, written.credentials, spec.secret_fields)
|
|
340
|
+
connection = build_connection(key, existing, spec, write, credentials, validated, actor)
|
|
341
|
+
if existing is not None and not written.created and unchanged(existing, connection):
|
|
342
|
+
return await self._result(key, existing, actor, created=False, sync_now=sync_now)
|
|
343
|
+
try:
|
|
344
|
+
stored, outcome = await control_plane.connections.put(
|
|
345
|
+
connection,
|
|
346
|
+
expected_version=existing.version if guarded and existing else expected_version,
|
|
347
|
+
create_only=create_only or (guarded and existing is None),
|
|
348
|
+
)
|
|
349
|
+
except HarborPreconditionFailedError as error:
|
|
350
|
+
await retire_refs(control_plane, written.created, tenant_id=key.tenant_id)
|
|
351
|
+
if guarded:
|
|
352
|
+
raise ConcurrentWriteError from error
|
|
353
|
+
raise
|
|
354
|
+
except Exception:
|
|
355
|
+
await retire_refs(control_plane, written.created, tenant_id=key.tenant_id)
|
|
356
|
+
raise
|
|
357
|
+
await self._retire_replaced(stored, written.retired)
|
|
358
|
+
await self._record(
|
|
359
|
+
stored, "created" if outcome == "created" else "updated", actor, existing
|
|
360
|
+
)
|
|
361
|
+
return await self._result(
|
|
362
|
+
key, stored, actor, created=outcome == "created", sync_now=sync_now
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
async def _result(
|
|
366
|
+
self, key: ConnectionKey, stored: Connection, actor: str, *, created: bool, sync_now: bool
|
|
367
|
+
) -> ConnectionPutResult:
|
|
368
|
+
"""Return the saved connection, after starting the ``sync_now`` ingestion when asked."""
|
|
369
|
+
ingestion: dict[str, Any] | None = None
|
|
370
|
+
sync_error: HarborError | None = None
|
|
371
|
+
if sync_now:
|
|
372
|
+
try:
|
|
373
|
+
ingestion = await self.sync(key, actor=actor)
|
|
374
|
+
except HarborError as error:
|
|
375
|
+
sync_error = error
|
|
376
|
+
except Exception: # noqa: BLE001 - the connection is saved; report, do not fail
|
|
377
|
+
logger.exception("sync_now could not start an ingestion for %s", key)
|
|
378
|
+
sync_error = HarborUnavailableError(
|
|
379
|
+
"the ingestion could not start; the connection was saved"
|
|
380
|
+
)
|
|
381
|
+
return ConnectionPutResult(
|
|
382
|
+
connection=await self._view(stored),
|
|
383
|
+
created=created,
|
|
384
|
+
version=stored.version,
|
|
385
|
+
ingestion=ingestion,
|
|
386
|
+
sync_error=sync_error,
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
async def test(
|
|
390
|
+
self, key: ConnectionKey, write: ConnectionWrite | None, *, origin: WriteOrigin = "api"
|
|
391
|
+
) -> dict[str, Any]:
|
|
392
|
+
"""Check form values, or the saved connection when ``write`` is None; saves nothing.
|
|
393
|
+
|
|
394
|
+
Returns:
|
|
395
|
+
The ``ConnectionTest`` body; ``ok`` is False when a check failed.
|
|
396
|
+
|
|
397
|
+
Raises:
|
|
398
|
+
HarborNotFoundError: No body and no saved connection, or the project is missing.
|
|
399
|
+
ConnectionValidationError: ``connection_id`` is malformed, or the values fail
|
|
400
|
+
the source type's schema, change an endpoint while a stored secret would be
|
|
401
|
+
kept, name a stored secret the field does not hold, or, from ``api``, set a
|
|
402
|
+
new ``env:`` reference or change an operator-only field.
|
|
403
|
+
"""
|
|
404
|
+
_require_connection_id(key)
|
|
405
|
+
control_plane = self._control_plane()
|
|
406
|
+
existing = await control_plane.connections.get(
|
|
407
|
+
tenant_id=key.tenant_id, project_id=key.project_id, connection_id=key.connection_id
|
|
408
|
+
)
|
|
409
|
+
if write is None:
|
|
410
|
+
if existing is None:
|
|
411
|
+
raise HarborNotFoundError(f"connection {key.connection_id!r} not found")
|
|
412
|
+
write = ConnectionWrite(
|
|
413
|
+
existing.source_type, existing.credentials, existing.config, tuning=existing.tuning
|
|
414
|
+
)
|
|
415
|
+
else:
|
|
416
|
+
await self._require_project(key)
|
|
417
|
+
spec = source_types.get(write.source_type)
|
|
418
|
+
sent, keep = plan_credentials(write.credentials, existing, spec)
|
|
419
|
+
effective = effective_credentials(sent, existing, keep)
|
|
420
|
+
refuse_operator_fields(spec, write, existing, origin)
|
|
421
|
+
issues = reference_issues(
|
|
422
|
+
sent, existing.credentials if existing else None, sources=secret_sources(origin)
|
|
423
|
+
)
|
|
424
|
+
if issues:
|
|
425
|
+
raise ConnectionValidationError(issues)
|
|
426
|
+
validated = validate_write(spec, effective, write, existing, key.tenant_id)
|
|
427
|
+
try:
|
|
428
|
+
secret_values = await default_secret_resolver(
|
|
429
|
+
control_plane.secrets
|
|
430
|
+
).resolve_credentials(
|
|
431
|
+
{k: v for k, v in effective.items() if isinstance(v, Mapping)},
|
|
432
|
+
tenant_id=key.tenant_id,
|
|
433
|
+
)
|
|
434
|
+
except SecretUnavailableError as unavailable:
|
|
435
|
+
report = ConnectionTestReport()
|
|
436
|
+
report.passed("schema")
|
|
437
|
+
report.secret_unavailable(unavailable)
|
|
438
|
+
return report.as_dict()
|
|
439
|
+
report = await run_checks(
|
|
440
|
+
spec,
|
|
441
|
+
validated,
|
|
442
|
+
effective,
|
|
443
|
+
secret_values,
|
|
444
|
+
key.tenant_id,
|
|
445
|
+
self._destination_policy,
|
|
446
|
+
)
|
|
447
|
+
return report.as_dict()
|
|
448
|
+
|
|
449
|
+
async def sync( # noqa: PLR0913 - the caller, its type and the run options
|
|
450
|
+
self,
|
|
451
|
+
key: ConnectionKey,
|
|
452
|
+
*,
|
|
453
|
+
actor: str,
|
|
454
|
+
actor_type: str = "user",
|
|
455
|
+
mode: str = "incremental",
|
|
456
|
+
item_refs: tuple[str, ...] = (),
|
|
457
|
+
updated_after: str | None = None,
|
|
458
|
+
) -> dict[str, Any]:
|
|
459
|
+
"""Start an ingestion of the connection, recording ``actor`` and ``actor_type`` on the run.
|
|
460
|
+
|
|
461
|
+
Returns:
|
|
462
|
+
The spec's ``Ingestion`` object of the started run.
|
|
463
|
+
|
|
464
|
+
Raises:
|
|
465
|
+
HarborNotFoundError: No such connection in the tenant.
|
|
466
|
+
HarborAlreadyRunningError: An ingestion is active; ``details.ingestion_id`` names it.
|
|
467
|
+
HarborCapabilityError: ``item_refs`` was sent; per-item syncs are not supported yet.
|
|
468
|
+
ConnectionUnavailableError: The connection is being deleted.
|
|
469
|
+
ConnectionValidationError: The stored values fail the schema or the connector.
|
|
470
|
+
"""
|
|
471
|
+
if item_refs:
|
|
472
|
+
raise HarborCapabilityError("syncing selected items is not supported yet")
|
|
473
|
+
connection = await self._require(key)
|
|
474
|
+
if connection.status == "deleting":
|
|
475
|
+
raise ConnectionUnavailableError(f"connection {connection.ref!r} is being deleted")
|
|
476
|
+
validate_connection(
|
|
477
|
+
source_types.get(connection.source_type),
|
|
478
|
+
connection.credentials,
|
|
479
|
+
connection.config,
|
|
480
|
+
connection.tuning,
|
|
481
|
+
tenant_id=connection.tenant_id,
|
|
482
|
+
)
|
|
483
|
+
runs = await self._runs()
|
|
484
|
+
await self.refuse_if_running(key.tenant_id, connection.source_key)
|
|
485
|
+
lease = f"connection-sync:{key.tenant_id}:{connection.source_key}"
|
|
486
|
+
holder = f"{self._instance_id}:{uuid4().hex}"
|
|
487
|
+
if not await self._control_plane().leases.try_acquire(
|
|
488
|
+
lease, holder, ttl_seconds=SYNC_LEASE_TTL_SECONDS
|
|
489
|
+
):
|
|
490
|
+
await self.refuse_if_running(key.tenant_id, connection.source_key)
|
|
491
|
+
raise HarborAlreadyRunningError(
|
|
492
|
+
"an ingestion is starting for this connection", details={"ingestion_id": None}
|
|
493
|
+
)
|
|
494
|
+
await self.refuse_if_running(key.tenant_id, connection.source_key)
|
|
495
|
+
accepted = await self._ingestions.submit(
|
|
496
|
+
IngestionCreateCommand(
|
|
497
|
+
tenant_id=key.tenant_id,
|
|
498
|
+
connection_id=connection.source_key,
|
|
499
|
+
force_reprocess=mode == "force",
|
|
500
|
+
public_request={
|
|
501
|
+
"connection": connection.ref,
|
|
502
|
+
"mode": mode,
|
|
503
|
+
"updated_after": updated_after,
|
|
504
|
+
"actor": actor,
|
|
505
|
+
},
|
|
506
|
+
updated_after=updated_after,
|
|
507
|
+
actor=actor,
|
|
508
|
+
actor_type=actor_type,
|
|
509
|
+
),
|
|
510
|
+
idempotency_key=None,
|
|
511
|
+
)
|
|
512
|
+
task = await runs.get(str(accepted["task_id"]))
|
|
513
|
+
if task is None:
|
|
514
|
+
raise HarborUnavailableError("the ingestion was accepted but cannot be read back")
|
|
515
|
+
await self._record(connection, "synced", actor, None, summary=f"Started a {mode} sync")
|
|
516
|
+
return ingestion_view(
|
|
517
|
+
task, connection=connection, progress=await runs.progress(task.task_id), mode=mode
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
async def delete(self, key: ConnectionKey, *, actor: str, purge: bool = False) -> str:
|
|
521
|
+
"""Start removing a connection in the background and return the job id.
|
|
522
|
+
|
|
523
|
+
Raises:
|
|
524
|
+
ConnectionValidationError: ``connection_id`` is malformed.
|
|
525
|
+
HarborNotFoundError: No such connection in the tenant.
|
|
526
|
+
HarborAlreadyRunningError: An ingestion of the connection is running.
|
|
527
|
+
"""
|
|
528
|
+
_require_connection_id(key)
|
|
529
|
+
control_plane = self._control_plane()
|
|
530
|
+
connection = await self._require(key)
|
|
531
|
+
active = await self._active_run(key.tenant_id, connection.source_key)
|
|
532
|
+
if active is not None:
|
|
533
|
+
raise HarborAlreadyRunningError(
|
|
534
|
+
"an ingestion is running for this connection",
|
|
535
|
+
details={"ingestion_id": active.task_id},
|
|
536
|
+
)
|
|
537
|
+
job = await self._start_job(connection, actor=actor, purge=purge)
|
|
538
|
+
await control_plane.connections.set_status(
|
|
539
|
+
tenant_id=key.tenant_id,
|
|
540
|
+
source_key=connection.source_key,
|
|
541
|
+
status="deleting",
|
|
542
|
+
detail={"job_id": job.id, "purge": purge},
|
|
543
|
+
)
|
|
544
|
+
await self._record(connection, "deleted", actor, None, summary="Started removal")
|
|
545
|
+
self.spawn(self.finish_deletion(connection, job_id=job.id, purge=purge))
|
|
546
|
+
return job.id
|
|
547
|
+
|
|
548
|
+
async def finish_deletion(self, connection: Connection, *, job_id: str, purge: bool) -> None:
|
|
549
|
+
"""Remove the documents, then the secrets, then the row; idempotent and resumable."""
|
|
550
|
+
marker = (connection.tenant_id, connection.source_key)
|
|
551
|
+
if marker in self._removing:
|
|
552
|
+
return
|
|
553
|
+
self._removing.add(marker)
|
|
554
|
+
try:
|
|
555
|
+
await self._finish_deletion(connection, job_id=job_id, purge=purge)
|
|
556
|
+
finally:
|
|
557
|
+
self._removing.discard(marker)
|
|
558
|
+
|
|
559
|
+
async def _finish_deletion(self, connection: Connection, *, job_id: str, purge: bool) -> None:
|
|
560
|
+
"""Run one removal pass and record its outcome on the job.
|
|
561
|
+
|
|
562
|
+
A connection removed as part of a project cascade leaves the project's
|
|
563
|
+
job running; only the project removal finishes it.
|
|
564
|
+
"""
|
|
565
|
+
control_plane = self._control_plane()
|
|
566
|
+
job = await control_plane.jobs.get(job_id, tenant_ids=frozenset({connection.tenant_id}))
|
|
567
|
+
try:
|
|
568
|
+
await self._removal().remove(
|
|
569
|
+
tenant_id=connection.tenant_id, source_key=connection.source_key, purge=purge
|
|
570
|
+
)
|
|
571
|
+
refs = set(stored_refs(connection.credentials))
|
|
572
|
+
if control_plane.connection_revisions is not None:
|
|
573
|
+
for snapshot in await control_plane.connection_revisions.list_for_source(
|
|
574
|
+
tenant_id=connection.tenant_id, source_key=connection.source_key
|
|
575
|
+
):
|
|
576
|
+
refs.update(ref for ref in snapshot.secret_refs if ref.startswith("secret://"))
|
|
577
|
+
await retire_refs(control_plane, sorted(refs), tenant_id=connection.tenant_id)
|
|
578
|
+
await control_plane.connections.delete(
|
|
579
|
+
tenant_id=connection.tenant_id,
|
|
580
|
+
project_id=connection.project_id,
|
|
581
|
+
connection_id=connection.connection_id,
|
|
582
|
+
)
|
|
583
|
+
except Exception as error:
|
|
584
|
+
logger.warning(
|
|
585
|
+
"Connection removal failed; it will be retried job_id=%s error_type=%s",
|
|
586
|
+
job_id,
|
|
587
|
+
type(error).__name__,
|
|
588
|
+
)
|
|
589
|
+
if job is None:
|
|
590
|
+
return
|
|
591
|
+
if job.job_type == _DELETE_CONNECTION_JOB:
|
|
592
|
+
await control_plane.jobs.save(_finished(job, "failed", type(error).__name__))
|
|
593
|
+
else:
|
|
594
|
+
await control_plane.jobs.save(replace(job, last_error=type(error).__name__))
|
|
595
|
+
return
|
|
596
|
+
if job is not None and job.job_type == _DELETE_CONNECTION_JOB:
|
|
597
|
+
await control_plane.jobs.save(_finished(job, "succeeded"))
|
|
598
|
+
|
|
599
|
+
async def resume_deletions(self) -> int:
|
|
600
|
+
"""Finish every removal a previous process left in ``deleting``."""
|
|
601
|
+
connections, _ = await self._control_plane().connections.list(
|
|
602
|
+
tenant_ids=None, status="deleting"
|
|
603
|
+
)
|
|
604
|
+
for connection in connections:
|
|
605
|
+
detail = connection.status_detail or {}
|
|
606
|
+
await self.finish_deletion(
|
|
607
|
+
connection,
|
|
608
|
+
job_id=str(detail.get("job_id", "")),
|
|
609
|
+
purge=bool(detail.get("purge", False)),
|
|
610
|
+
)
|
|
611
|
+
return len(connections)
|
|
612
|
+
|
|
613
|
+
async def refuse_if_running(self, tenant_id: str, source_key: str) -> None:
|
|
614
|
+
"""Refuse a new ingestion of a connection that has a pending, running or paused one.
|
|
615
|
+
|
|
616
|
+
Raises:
|
|
617
|
+
HarborAlreadyRunningError: An ingestion is active; ``details.ingestion_id`` names it.
|
|
618
|
+
"""
|
|
619
|
+
active = await self._active_run(tenant_id, source_key)
|
|
620
|
+
if active is not None:
|
|
621
|
+
raise HarborAlreadyRunningError(
|
|
622
|
+
"an ingestion is already running", details={"ingestion_id": active.task_id}
|
|
623
|
+
)
|
|
624
|
+
|
|
625
|
+
async def _active_run(self, tenant_id: str, source_key: str) -> IngestionTask | None:
|
|
626
|
+
"""Return the connection's pending, running or paused run, settling ended ones first."""
|
|
627
|
+
return await active_run(
|
|
628
|
+
await self._runs(), self._ingestions, tenant_id=tenant_id, source_key=source_key
|
|
629
|
+
)
|
|
630
|
+
|
|
631
|
+
async def connection_busy(self, tenant_id: str, source_key: str) -> bool:
|
|
632
|
+
"""Report whether an ingestion of the connection is pending, running or paused."""
|
|
633
|
+
return await self._active_run(tenant_id, source_key) is not None
|
|
634
|
+
|
|
635
|
+
async def aclose(self) -> None:
|
|
636
|
+
"""Wait for background removals started by this process."""
|
|
637
|
+
if self._background:
|
|
638
|
+
await asyncio.gather(*self._background, return_exceptions=True)
|
|
639
|
+
|
|
640
|
+
async def _require(self, key: ConnectionKey) -> Connection:
|
|
641
|
+
"""Return the stored connection or raise not found."""
|
|
642
|
+
connection = await self._control_plane().connections.get(
|
|
643
|
+
tenant_id=key.tenant_id, project_id=key.project_id, connection_id=key.connection_id
|
|
644
|
+
)
|
|
645
|
+
if connection is None:
|
|
646
|
+
raise HarborNotFoundError(f"connection {key.connection_id!r} not found")
|
|
647
|
+
return connection
|
|
648
|
+
|
|
649
|
+
async def _require_project(self, key: ConnectionKey) -> None:
|
|
650
|
+
"""Raise not found unless the project exists in the tenant, naming a near match."""
|
|
651
|
+
projects = self._control_plane().projects
|
|
652
|
+
tenants = frozenset({key.tenant_id})
|
|
653
|
+
if await projects.get(key.project_id, tenant_ids=tenants) is not None:
|
|
654
|
+
return
|
|
655
|
+
wanted = key.project_id.casefold()
|
|
656
|
+
match = next(
|
|
657
|
+
(
|
|
658
|
+
project.id
|
|
659
|
+
for project in await projects.list(tenant_ids=tenants)
|
|
660
|
+
if wanted in {project.id.casefold(), project.name.casefold()}
|
|
661
|
+
),
|
|
662
|
+
None,
|
|
663
|
+
)
|
|
664
|
+
hint = f"; did you mean {match!r}?" if match else ""
|
|
665
|
+
raise HarborNotFoundError(f"project {key.project_id!r} not found{hint}")
|
|
666
|
+
|
|
667
|
+
async def _view(self, connection: Connection) -> dict[str, Any]:
|
|
668
|
+
"""Return the API view with the latest run and document count."""
|
|
669
|
+
views = await read_connection_views(await self._runs(), [connection], batch=False)
|
|
670
|
+
return views[0]
|
|
671
|
+
|
|
672
|
+
async def _retire_replaced(self, connection: Connection, refs: list[str]) -> None:
|
|
673
|
+
"""Delete replaced stored secrets now, or once the running ingestion finishes."""
|
|
674
|
+
if not refs:
|
|
675
|
+
return
|
|
676
|
+
control_plane = self._control_plane()
|
|
677
|
+
if await self.connection_busy(connection.tenant_id, connection.source_key):
|
|
678
|
+
await defer_retirement(
|
|
679
|
+
control_plane,
|
|
680
|
+
refs,
|
|
681
|
+
tenant_id=connection.tenant_id,
|
|
682
|
+
source_key=connection.source_key,
|
|
683
|
+
)
|
|
684
|
+
return
|
|
685
|
+
await retire_refs(control_plane, refs, tenant_id=connection.tenant_id)
|
|
686
|
+
|
|
687
|
+
async def _record( # noqa: PLR0913 - one audit entry
|
|
688
|
+
self,
|
|
689
|
+
connection: Connection,
|
|
690
|
+
verb: str,
|
|
691
|
+
actor: str,
|
|
692
|
+
before: Connection | None,
|
|
693
|
+
*,
|
|
694
|
+
summary: str | None = None,
|
|
695
|
+
) -> None:
|
|
696
|
+
"""Append an audit entry naming the changed fields, never their values."""
|
|
697
|
+
changed = changed_fields(before, connection) if before is not None else []
|
|
698
|
+
text = summary or (
|
|
699
|
+
f"{verb.capitalize()} connection {connection.ref!r}"
|
|
700
|
+
+ (f"; changed {', '.join(changed)}" if changed else "")
|
|
701
|
+
)
|
|
702
|
+
await log_activity(
|
|
703
|
+
self._control_plane(),
|
|
704
|
+
ActivityEntry(
|
|
705
|
+
id=f"act_{uuid4().hex}",
|
|
706
|
+
tenant_id=connection.tenant_id,
|
|
707
|
+
actor=actor,
|
|
708
|
+
verb=verb,
|
|
709
|
+
entity_type="connection",
|
|
710
|
+
entity_id=connection.ref,
|
|
711
|
+
summary=text,
|
|
712
|
+
),
|
|
713
|
+
)
|
|
714
|
+
|
|
715
|
+
async def _start_job(self, connection: Connection, *, actor: str, purge: bool) -> Job:
|
|
716
|
+
"""Persist the removal job."""
|
|
717
|
+
job = Job(
|
|
718
|
+
id=f"job_{uuid4().hex[:16]}",
|
|
719
|
+
source_id=connection.id,
|
|
720
|
+
project_id=connection.project_id,
|
|
721
|
+
job_type=_DELETE_CONNECTION_JOB,
|
|
722
|
+
tenant_id=connection.tenant_id,
|
|
723
|
+
status="running",
|
|
724
|
+
payload={"connection": connection.ref, "purge": purge, "actor": actor},
|
|
725
|
+
)
|
|
726
|
+
return await self._control_plane().jobs.save(job)
|
|
727
|
+
|
|
728
|
+
def spawn(self, work: Awaitable[None]) -> None:
|
|
729
|
+
"""Run ``work`` in the background and keep a reference until it ends."""
|
|
730
|
+
task = asyncio.ensure_future(work)
|
|
731
|
+
self._background.add(task)
|
|
732
|
+
task.add_done_callback(self._background.discard)
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def _require_connection_id(key: ConnectionKey) -> None:
|
|
736
|
+
"""Refuse a malformed ``connection_id`` before any lookup, as the HTTP path pattern does.
|
|
737
|
+
|
|
738
|
+
Raises:
|
|
739
|
+
ConnectionValidationError: The id does not match the ``connection_id`` pattern.
|
|
740
|
+
"""
|
|
741
|
+
try:
|
|
742
|
+
require_connection_id(key.connection_id)
|
|
743
|
+
except ValueError as error:
|
|
744
|
+
raise ConnectionValidationError([FieldIssue("connection_id", str(error))]) from error
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def _finished(job: Job, status: JobStatus, error: str | None = None) -> Job:
|
|
748
|
+
"""Return ``job`` marked finished with ``status``."""
|
|
749
|
+
return replace(job, status=status, finished_at=utc_now(), last_error=error)
|