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.
Files changed (271) hide show
  1. harborrag_runtime/__init__.py +22 -0
  2. harborrag_runtime/application/README.md +39 -0
  3. harborrag_runtime/application/__init__.py +39 -0
  4. harborrag_runtime/application/chat/__init__.py +7 -0
  5. harborrag_runtime/application/chat/citations.py +149 -0
  6. harborrag_runtime/application/chat/client.py +201 -0
  7. harborrag_runtime/application/chat/completion.py +92 -0
  8. harborrag_runtime/application/chat/completion_request.py +130 -0
  9. harborrag_runtime/application/chat/evidence.py +202 -0
  10. harborrag_runtime/application/chat/options.py +43 -0
  11. harborrag_runtime/application/chat/preparation.py +135 -0
  12. harborrag_runtime/application/chat/presenters.py +130 -0
  13. harborrag_runtime/application/chat/prompting.py +127 -0
  14. harborrag_runtime/application/chat/query_scope.py +146 -0
  15. harborrag_runtime/application/chat/replay.py +141 -0
  16. harborrag_runtime/application/chat/request_filters.py +134 -0
  17. harborrag_runtime/application/chat/retrieval.py +127 -0
  18. harborrag_runtime/application/chat/service.py +371 -0
  19. harborrag_runtime/application/composition/__init__.py +1 -0
  20. harborrag_runtime/application/composition/factories.py +106 -0
  21. harborrag_runtime/application/composition/resources.py +141 -0
  22. harborrag_runtime/application/composition/selection.py +65 -0
  23. harborrag_runtime/application/composition/service.py +550 -0
  24. harborrag_runtime/application/composition/tenant_models.py +45 -0
  25. harborrag_runtime/application/control_plane/__init__.py +1 -0
  26. harborrag_runtime/application/control_plane/active_runs.py +38 -0
  27. harborrag_runtime/application/control_plane/connection_models.py +109 -0
  28. harborrag_runtime/application/control_plane/connection_testing.py +91 -0
  29. harborrag_runtime/application/control_plane/connection_writes.py +227 -0
  30. harborrag_runtime/application/control_plane/connections.py +749 -0
  31. harborrag_runtime/application/control_plane/effect_recovery.py +235 -0
  32. harborrag_runtime/application/control_plane/projects.py +313 -0
  33. harborrag_runtime/application/control_plane/settings_import.py +239 -0
  34. harborrag_runtime/application/control_plane/settings_service.py +233 -0
  35. harborrag_runtime/application/control_plane/tenants.py +55 -0
  36. harborrag_runtime/application/errors.py +110 -0
  37. harborrag_runtime/application/ingestion/__init__.py +1 -0
  38. harborrag_runtime/application/ingestion/client.py +65 -0
  39. harborrag_runtime/application/ingestion/connection_sources.py +96 -0
  40. harborrag_runtime/application/ingestion/direct.py +120 -0
  41. harborrag_runtime/application/ingestion/follower.py +83 -0
  42. harborrag_runtime/application/ingestion/ports.py +174 -0
  43. harborrag_runtime/application/ingestion/progress_bridge.py +221 -0
  44. harborrag_runtime/application/ingestion/retry_selection.py +71 -0
  45. harborrag_runtime/application/ingestion/service.py +564 -0
  46. harborrag_runtime/application/ingestion/starter.py +78 -0
  47. harborrag_runtime/application/memory/__init__.py +21 -0
  48. harborrag_runtime/application/memory/client.py +114 -0
  49. harborrag_runtime/application/memory/composition.py +90 -0
  50. harborrag_runtime/application/memory/context.py +45 -0
  51. harborrag_runtime/application/memory/sessions.py +117 -0
  52. harborrag_runtime/application/ports.py +133 -0
  53. harborrag_runtime/application/retrieval/__init__.py +1 -0
  54. harborrag_runtime/application/retrieval/access.py +26 -0
  55. harborrag_runtime/application/scheduling/service.py +58 -0
  56. harborrag_runtime/application/schemas.py +15 -0
  57. harborrag_runtime/chat/README.md +40 -0
  58. harborrag_runtime/chat/__init__.py +18 -0
  59. harborrag_runtime/chat/composition.py +53 -0
  60. harborrag_runtime/chat/facade.py +46 -0
  61. harborrag_runtime/chat/service.py +183 -0
  62. harborrag_runtime/chat/tenant_clients.py +341 -0
  63. harborrag_runtime/chat/tenant_config.py +235 -0
  64. harborrag_runtime/chat/tenant_models.py +22 -0
  65. harborrag_runtime/composition/__init__.py +5 -0
  66. harborrag_runtime/composition/config_store.py +53 -0
  67. harborrag_runtime/composition/connection_removal.py +120 -0
  68. harborrag_runtime/composition/connection_stores.py +107 -0
  69. harborrag_runtime/composition/control_plane.py +401 -0
  70. harborrag_runtime/composition/mcp_auth.py +39 -0
  71. harborrag_runtime/composition/readers.py +113 -0
  72. harborrag_runtime/composition/resources.py +336 -0
  73. harborrag_runtime/composition/storage_providers.py +113 -0
  74. harborrag_runtime/config/__init__.py +84 -0
  75. harborrag_runtime/config/checkout.py +212 -0
  76. harborrag_runtime/config/chunking.py +167 -0
  77. harborrag_runtime/config/connectors/__init__.py +19 -0
  78. harborrag_runtime/config/connectors/fingerprints.py +54 -0
  79. harborrag_runtime/config/connectors/importing.py +611 -0
  80. harborrag_runtime/config/connectors/loader.py +95 -0
  81. harborrag_runtime/config/connectors/models/__init__.py +30 -0
  82. harborrag_runtime/config/connectors/models/atlassian.py +199 -0
  83. harborrag_runtime/config/connectors/models/builder.py +208 -0
  84. harborrag_runtime/config/connectors/models/common.py +45 -0
  85. harborrag_runtime/config/connectors/models/fields.py +134 -0
  86. harborrag_runtime/config/connectors/models/github.py +143 -0
  87. harborrag_runtime/config/connectors/models/local_file.py +119 -0
  88. harborrag_runtime/config/connectors/models/registry.py +149 -0
  89. harborrag_runtime/config/connectors/models/sharepoint.py +186 -0
  90. harborrag_runtime/config/connectors/models/spec.py +563 -0
  91. harborrag_runtime/config/connectors/parsing.py +275 -0
  92. harborrag_runtime/config/connectors/providers.py +177 -0
  93. harborrag_runtime/config/connectors/schemas.py +215 -0
  94. harborrag_runtime/config/errors.py +26 -0
  95. harborrag_runtime/config/graph_build.py +335 -0
  96. harborrag_runtime/config/graph_build_loading.py +38 -0
  97. harborrag_runtime/config/loading.py +245 -0
  98. harborrag_runtime/config/models.py +95 -0
  99. harborrag_runtime/config/ontology_loading.py +76 -0
  100. harborrag_runtime/config/parsers/__init__.py +19 -0
  101. harborrag_runtime/config/parsers/loader.py +85 -0
  102. harborrag_runtime/config/parsers/parsing.py +285 -0
  103. harborrag_runtime/config/parsers/providers.py +305 -0
  104. harborrag_runtime/config/parsers/schemas.py +614 -0
  105. harborrag_runtime/config/settings.py +378 -0
  106. harborrag_runtime/config/settings_document.py +133 -0
  107. harborrag_runtime/config/temporal.py +331 -0
  108. harborrag_runtime/config/temporal_loading.py +310 -0
  109. harborrag_runtime/config_store/__init__.py +5 -0
  110. harborrag_runtime/config_store/defaults.py +47 -0
  111. harborrag_runtime/config_store/provider.py +153 -0
  112. harborrag_runtime/config_store/run_settings.py +72 -0
  113. harborrag_runtime/connections/__init__.py +27 -0
  114. harborrag_runtime/connections/secrets.py +348 -0
  115. harborrag_runtime/contracts.py +237 -0
  116. harborrag_runtime/document_stage_catalog.py +82 -0
  117. harborrag_runtime/errors.py +64 -0
  118. harborrag_runtime/events/__init__.py +3 -0
  119. harborrag_runtime/events/in_process.py +100 -0
  120. harborrag_runtime/execution/__init__.py +26 -0
  121. harborrag_runtime/execution/contracts.py +32 -0
  122. harborrag_runtime/execution/direct.py +169 -0
  123. harborrag_runtime/execution/gateway.py +97 -0
  124. harborrag_runtime/execution/source_conversion.py +61 -0
  125. harborrag_runtime/execution/source_submission.py +278 -0
  126. harborrag_runtime/execution/submission.py +64 -0
  127. harborrag_runtime/execution/task_registry.py +387 -0
  128. harborrag_runtime/execution/temporal.py +165 -0
  129. harborrag_runtime/ingestion/README.md +79 -0
  130. harborrag_runtime/ingestion/__init__.py +59 -0
  131. harborrag_runtime/ingestion/chunking_profile.py +97 -0
  132. harborrag_runtime/ingestion/composition.py +279 -0
  133. harborrag_runtime/ingestion/connection_checks.py +239 -0
  134. harborrag_runtime/ingestion/connections.py +507 -0
  135. harborrag_runtime/ingestion/document/__init__.py +1 -0
  136. harborrag_runtime/ingestion/document/normalization.py +14 -0
  137. harborrag_runtime/ingestion/document/normalizers/__init__.py +9 -0
  138. harborrag_runtime/ingestion/document/normalizers/builtins.py +39 -0
  139. harborrag_runtime/ingestion/document/normalizers/transform.py +30 -0
  140. harborrag_runtime/ingestion/document/run_tools.py +152 -0
  141. harborrag_runtime/ingestion/failure_classification.py +82 -0
  142. harborrag_runtime/ingestion/field_indexes.py +56 -0
  143. harborrag_runtime/ingestion/maintenance/__init__.py +1 -0
  144. harborrag_runtime/ingestion/maintenance/connection_removal.py +115 -0
  145. harborrag_runtime/ingestion/maintenance/projection_admin.py +180 -0
  146. harborrag_runtime/ingestion/maintenance/relation_repair.py +555 -0
  147. harborrag_runtime/ingestion/maintenance/retention.py +353 -0
  148. harborrag_runtime/ingestion/observability.py +3 -0
  149. harborrag_runtime/ingestion/profiles.py +127 -0
  150. harborrag_runtime/ingestion/runtime_builder.py +339 -0
  151. harborrag_runtime/ingestion/source/__init__.py +1 -0
  152. harborrag_runtime/ingestion/source/descriptor_mapping.py +144 -0
  153. harborrag_runtime/ingestion/source/discovery.py +290 -0
  154. harborrag_runtime/ingestion/source/documents.py +184 -0
  155. harborrag_runtime/ingestion/source/finalization.py +288 -0
  156. harborrag_runtime/ingestion/source/operations.py +175 -0
  157. harborrag_runtime/ingestion/source/plan.py +413 -0
  158. harborrag_runtime/ingestion/source/retry.py +150 -0
  159. harborrag_runtime/ingestion/source/service.py +470 -0
  160. harborrag_runtime/ingestion/source/skips.py +172 -0
  161. harborrag_runtime/ingestion_contracts.py +107 -0
  162. harborrag_runtime/memory/__init__.py +81 -0
  163. harborrag_runtime/memory/access.py +47 -0
  164. harborrag_runtime/memory/administration.py +460 -0
  165. harborrag_runtime/memory/context/__init__.py +5 -0
  166. harborrag_runtime/memory/context/result.py +20 -0
  167. harborrag_runtime/memory/directory.py +166 -0
  168. harborrag_runtime/memory/erasure.py +122 -0
  169. harborrag_runtime/memory/locks.py +170 -0
  170. harborrag_runtime/memory/messages.py +202 -0
  171. harborrag_runtime/memory/presenters.py +117 -0
  172. harborrag_runtime/memory/projects.py +38 -0
  173. harborrag_runtime/memory/tiers/__init__.py +1 -0
  174. harborrag_runtime/memory/tiers/in_memory.py +491 -0
  175. harborrag_runtime/memory/titles.py +32 -0
  176. harborrag_runtime/memory/usage.py +131 -0
  177. harborrag_runtime/observability/__init__.py +1 -0
  178. harborrag_runtime/observability/connector_metrics.py +14 -0
  179. harborrag_runtime/observability/discovery_metrics.py +46 -0
  180. harborrag_runtime/observability/model.py +410 -0
  181. harborrag_runtime/observability/observability_types.py +47 -0
  182. harborrag_runtime/observability/stage_observation.py +96 -0
  183. harborrag_runtime/observability/tool_audit.py +17 -0
  184. harborrag_runtime/plugins.py +56 -0
  185. harborrag_runtime/rate_limiting.py +39 -0
  186. harborrag_runtime/reader_contracts.py +149 -0
  187. harborrag_runtime/retrieval/__init__.py +1 -0
  188. harborrag_runtime/retrieval/composition.py +174 -0
  189. harborrag_runtime/retrieval/facades.py +224 -0
  190. harborrag_runtime/scheduling/__init__.py +48 -0
  191. harborrag_runtime/scheduling/config.py +185 -0
  192. harborrag_runtime/scheduling/errors.py +37 -0
  193. harborrag_runtime/scheduling/models.py +146 -0
  194. harborrag_runtime/scheduling/service.py +297 -0
  195. harborrag_runtime/scheduling/validation.py +213 -0
  196. harborrag_runtime/sdk/__init__.py +86 -0
  197. harborrag_runtime/sdk/configuration.py +44 -0
  198. harborrag_runtime/sdk/facades.py +47 -0
  199. harborrag_runtime/sdk/runtime.py +242 -0
  200. harborrag_runtime/security/__init__.py +1 -0
  201. harborrag_runtime/security/api_key_operations.py +236 -0
  202. harborrag_runtime/serialization.py +35 -0
  203. harborrag_runtime/temporal/__init__.py +19 -0
  204. harborrag_runtime/temporal/activity_observability.py +313 -0
  205. harborrag_runtime/temporal/client.py +580 -0
  206. harborrag_runtime/temporal/connection.py +39 -0
  207. harborrag_runtime/temporal/conversion.py +147 -0
  208. harborrag_runtime/temporal/dispatch.py +38 -0
  209. harborrag_runtime/temporal/document_workflow.py +154 -0
  210. harborrag_runtime/temporal/failure_handling.py +68 -0
  211. harborrag_runtime/temporal/gateway.py +121 -0
  212. harborrag_runtime/temporal/heartbeats.py +67 -0
  213. harborrag_runtime/temporal/identity.py +14 -0
  214. harborrag_runtime/temporal/ingestion_activities.py +435 -0
  215. harborrag_runtime/temporal/maintenance_activities.py +251 -0
  216. harborrag_runtime/temporal/maintenance_schemas.py +88 -0
  217. harborrag_runtime/temporal/optional.py +19 -0
  218. harborrag_runtime/temporal/plan_resolver.py +149 -0
  219. harborrag_runtime/temporal/policies.py +18 -0
  220. harborrag_runtime/temporal/reindex_workflow.py +71 -0
  221. harborrag_runtime/temporal/retry_activities.py +147 -0
  222. harborrag_runtime/temporal/retry_workflow.py +222 -0
  223. harborrag_runtime/temporal/sandbox.py +51 -0
  224. harborrag_runtime/temporal/schedules.py +341 -0
  225. harborrag_runtime/temporal/schemas.py +482 -0
  226. harborrag_runtime/temporal/source_activities.py +590 -0
  227. harborrag_runtime/temporal/source_batch_workflow.py +226 -0
  228. harborrag_runtime/temporal/source_workflow.py +908 -0
  229. harborrag_runtime/temporal/submission.py +23 -0
  230. harborrag_runtime/temporal/worker.py +478 -0
  231. harborrag_runtime/temporal/worker_registry.py +141 -0
  232. harborrag_runtime/temporal_models.py +227 -0
  233. harborrag_runtime/testing/chat_fakes.py +309 -0
  234. harborrag_runtime/testing/chat_service_double.py +126 -0
  235. harborrag_runtime/testing/connection_fakes.py +278 -0
  236. harborrag_runtime/testing/memory_fakes.py +128 -0
  237. harborrag_runtime/topology/__init__.py +1 -0
  238. harborrag_runtime/topology/budgeted_extractor.py +110 -0
  239. harborrag_runtime/topology/chunk_runner.py +41 -0
  240. harborrag_runtime/topology/composition.py +168 -0
  241. harborrag_runtime/topology/configuration.py +126 -0
  242. harborrag_runtime/topology/contextual.py +140 -0
  243. harborrag_runtime/topology/derived.py +238 -0
  244. harborrag_runtime/topology/derived_coverage.py +5 -0
  245. harborrag_runtime/topology/derived_dispatch.py +63 -0
  246. harborrag_runtime/topology/derived_factory.py +175 -0
  247. harborrag_runtime/topology/derived_models.py +251 -0
  248. harborrag_runtime/topology/derived_projection.py +127 -0
  249. harborrag_runtime/topology/description_factory.py +81 -0
  250. harborrag_runtime/topology/embedding_profile.py +85 -0
  251. harborrag_runtime/topology/entity_summary_index.py +304 -0
  252. harborrag_runtime/topology/maintenance.py +126 -0
  253. harborrag_runtime/topology/operations.py +277 -0
  254. harborrag_runtime/topology/parent_materializer.py +167 -0
  255. harborrag_runtime/topology/run_cost.py +43 -0
  256. harborrag_runtime/topology/security_operations.py +46 -0
  257. harborrag_runtime/topology/service.py +349 -0
  258. harborrag_runtime/topology/summary_factory.py +164 -0
  259. harborrag_runtime/topology/summary_inputs.py +129 -0
  260. harborrag_runtime/topology/summary_operations.py +128 -0
  261. harborrag_runtime/topology/summary_policy.py +39 -0
  262. harborrag_runtime/topology/summary_products.py +43 -0
  263. harborrag_runtime/topology/summary_service.py +625 -0
  264. harborrag_runtime/topology/summary_worker.py +129 -0
  265. harborrag_runtime/topology/summary_workflow.py +32 -0
  266. harborrag_runtime/topology/worker.py +101 -0
  267. harborrag_runtime/topology/workflow.py +32 -0
  268. harborrag_runtime-2.0.0.dist-info/METADATA +267 -0
  269. harborrag_runtime-2.0.0.dist-info/RECORD +271 -0
  270. harborrag_runtime-2.0.0.dist-info/WHEEL +4 -0
  271. harborrag_runtime-2.0.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,235 @@
1
+ """Durable retry queue for control-plane secret retirement and audit logging.
2
+
3
+ Connection and project writes call ``retire_refs``/``log_activity`` here instead
4
+ of touching ``control_plane.secrets``/``activity`` directly, so a failure after
5
+ their write already committed is queued for retry rather than raised -- never
6
+ turning a successful write into an API error. ``recover_pending_control_plane_effects``
7
+ drains that queue later. Both replayed actions are safe to retry blindly: secret
8
+ deletion is a no-op on an already-gone ref, and a requeued activity entry keeps
9
+ its original id, so it can't double-write.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ from collections.abc import Awaitable, Callable
16
+ from datetime import datetime
17
+ from typing import Any
18
+ from uuid import uuid4
19
+
20
+ from harborrag_core.domain.activity import ActivityEntry
21
+ from harborrag_core.domain.pending_effect import PendingControlPlaneEffect
22
+ from harborrag_core.invariants import HarborInvariantError
23
+ from harborrag_runtime.composition import ControlPlaneRepositories
24
+
25
+ logger = logging.getLogger("harborrag.runtime.application.control_plane.effect_recovery")
26
+
27
+ _RETIRE_SECRET_KIND = "retire_secret"
28
+ _RETIRE_WHEN_IDLE_KIND = "retire_secret_when_idle"
29
+ _LOG_ACTIVITY_KIND = "log_activity"
30
+
31
+ type ConnectionBusy = Callable[[str, str], Awaitable[bool]]
32
+ LEGACY_SECRET_TENANT_ID = "DEFAULT"
33
+ """Tenant migration 0032 gives a legacy secret that no source row still owns."""
34
+
35
+ EFFECT_RECOVERY_LEASE_NAME = "control_plane_effect_recovery"
36
+ """Lease ``AppService.recover_pending_control_plane_effects`` runs its drain under.
37
+
38
+ It mirrors the ingestion progress bridge's ``LEASE_NAME``. Without it every API
39
+ process or replica drains the same queue on its own timer and can replay the same
40
+ pending effect concurrently. ``retire_secret`` is idempotent either way, but
41
+ ``log_activity`` is not: two processes replaying one entry ID both attempt an insert,
42
+ and only a unique-ID constraint or the repository's idempotent-append guard stops
43
+ the double entry.
44
+ """
45
+ EFFECT_RECOVERY_LEASE_TTL_SECONDS = 120.0
46
+ """Lease lifetime of a few drain intervals, so a crashed holder's lease lapses quickly."""
47
+
48
+
49
+ async def retire_refs(
50
+ control_plane: ControlPlaneRepositories,
51
+ refs: list[str],
52
+ *,
53
+ tenant_id: str,
54
+ ) -> None:
55
+ """Delete each of one tenant's refs; a failed delete is queued, never raised.
56
+
57
+ The tenant travels with the queued effect because secret refs are
58
+ tenant-scoped: a replay that presented the ref alone would address
59
+ nothing and silently leave the secret behind.
60
+ """
61
+ for ref in refs:
62
+ try:
63
+ await control_plane.secrets.delete(ref, tenant_id=tenant_id)
64
+ except Exception:
65
+ logger.exception("secret retirement failed ref=%r; queued for retry", ref)
66
+ await _queue_effect(
67
+ control_plane,
68
+ _RETIRE_SECRET_KIND,
69
+ {"ref": ref, "tenant_id": tenant_id},
70
+ )
71
+
72
+
73
+ async def log_activity(control_plane: ControlPlaneRepositories, entry: ActivityEntry) -> None:
74
+ """Append one audit row; a failed append is queued for retry, never raised."""
75
+ try:
76
+ await control_plane.activity.append(entry)
77
+ except Exception:
78
+ logger.exception("activity logging failed entry_id=%r; queued for retry", entry.id)
79
+ await _queue_effect(control_plane, _LOG_ACTIVITY_KIND, _activity_payload(entry))
80
+
81
+
82
+ async def defer_retirement(
83
+ control_plane: ControlPlaneRepositories,
84
+ refs: list[str],
85
+ *,
86
+ tenant_id: str,
87
+ source_key: str,
88
+ ) -> None:
89
+ """Queue stored refs to be deleted once no run of the connection still uses them."""
90
+ for ref in refs:
91
+ await _queue_effect(
92
+ control_plane,
93
+ _RETIRE_WHEN_IDLE_KIND,
94
+ {"ref": ref, "tenant_id": tenant_id, "source_key": source_key},
95
+ )
96
+
97
+
98
+ async def recover_pending_control_plane_effects(
99
+ control_plane: ControlPlaneRepositories,
100
+ *,
101
+ limit: int = 100,
102
+ erasure_handler: Callable[[PendingControlPlaneEffect], Awaitable[bool]] | None = None,
103
+ connection_busy: ConnectionBusy | None = None,
104
+ ) -> int:
105
+ """Retry queued effects and authorized cross-store erasure intents.
106
+
107
+ Post-commit effects and pre-delete erasure intents are idempotent; a
108
+ concurrent initial attempt may perform the same deletion harmlessly.
109
+ A row that fails again is left pending for the next drain pass; one bad
110
+ row must not block the rest. A failure to delete a row that already replayed
111
+ is logged and the row replays again next pass, which is safe because both
112
+ effect kinds are idempotent.
113
+ """
114
+ recovered = 0
115
+ for effect in await control_plane.pending_effects.list_pending(limit=limit):
116
+ try:
117
+ if await _still_in_use(effect, connection_busy):
118
+ continue
119
+ if erasure_handler is None or not await erasure_handler(effect):
120
+ await _replay_effect(control_plane, effect)
121
+ except Exception:
122
+ logger.exception(
123
+ "control-plane pending effect retry failed id=%s kind=%s",
124
+ effect.id,
125
+ effect.kind,
126
+ )
127
+ continue
128
+ try:
129
+ await control_plane.pending_effects.complete(effect.id)
130
+ except Exception:
131
+ logger.exception(
132
+ "control-plane pending effect complete failed id=%s kind=%s; will retry",
133
+ effect.id,
134
+ effect.kind,
135
+ )
136
+ continue
137
+ recovered += 1
138
+ return recovered
139
+
140
+
141
+ async def _queue_effect(
142
+ control_plane: ControlPlaneRepositories, kind: str, payload: dict[str, Any]
143
+ ) -> None:
144
+ """Durably record a failed side effect; logged (not raised) if even this fails.
145
+
146
+ Both call sites here run after the primary write they depend on already
147
+ committed, so there is no error left to surface to the caller -- a
148
+ failure enqueuing the retry itself just means this side effect is lost
149
+ until someone notices the log line.
150
+ """
151
+ try:
152
+ await control_plane.pending_effects.enqueue(
153
+ PendingControlPlaneEffect(id=f"eff_{uuid4().hex}", kind=kind, payload=payload)
154
+ )
155
+ except Exception:
156
+ logger.critical(
157
+ "control-plane pending effect enqueue failed kind=%s payload=%r; effect lost",
158
+ kind,
159
+ payload,
160
+ exc_info=True,
161
+ )
162
+
163
+
164
+ async def _still_in_use(
165
+ effect: PendingControlPlaneEffect, connection_busy: ConnectionBusy | None
166
+ ) -> bool:
167
+ """Report whether a deferred retirement's connection still has an active run."""
168
+ if effect.kind != _RETIRE_WHEN_IDLE_KIND:
169
+ return False
170
+ if connection_busy is None:
171
+ return True
172
+ return await connection_busy(
173
+ str(effect.payload["tenant_id"]), str(effect.payload["source_key"])
174
+ )
175
+
176
+
177
+ async def _replay_effect(
178
+ control_plane: ControlPlaneRepositories, effect: PendingControlPlaneEffect
179
+ ) -> None:
180
+ """Perform one queued effect.
181
+
182
+ A secret retirement queued before refs became tenant-scoped carries no tenant. Its ref
183
+ was retired from the source that used it, so migration 0032 found no owner and left
184
+ the secret under ``LEGACY_SECRET_TENANT_ID``; it is retired there rather than dropped,
185
+ which would orphan the ciphertext.
186
+
187
+ Raises:
188
+ HarborInvariantError: The effect kind is unknown.
189
+ """
190
+ if effect.kind == _RETIRE_WHEN_IDLE_KIND:
191
+ await control_plane.secrets.delete(
192
+ str(effect.payload["ref"]), tenant_id=str(effect.payload["tenant_id"])
193
+ )
194
+ return
195
+ if effect.kind == _RETIRE_SECRET_KIND:
196
+ tenant_id = effect.payload.get("tenant_id")
197
+ if not isinstance(tenant_id, str) or not tenant_id:
198
+ logger.warning(
199
+ "pending secret retirement carries no tenant; retiring under %s ref=%r",
200
+ LEGACY_SECRET_TENANT_ID,
201
+ effect.payload.get("ref"),
202
+ )
203
+ tenant_id = LEGACY_SECRET_TENANT_ID
204
+ await control_plane.secrets.delete(str(effect.payload["ref"]), tenant_id=tenant_id)
205
+ return
206
+ if effect.kind == _LOG_ACTIVITY_KIND:
207
+ await control_plane.activity.append(_activity_from_payload(effect.payload))
208
+ return
209
+ raise HarborInvariantError(f"unknown pending control-plane effect kind: {effect.kind!r}")
210
+
211
+
212
+ def _activity_payload(entry: ActivityEntry) -> dict[str, Any]:
213
+ return {
214
+ "id": entry.id,
215
+ "actor": entry.actor,
216
+ "verb": entry.verb,
217
+ "entity_type": entry.entity_type,
218
+ "entity_id": entry.entity_id,
219
+ "summary": entry.summary,
220
+ "tenant_id": entry.tenant_id,
221
+ "created_at": entry.created_at.isoformat(),
222
+ }
223
+
224
+
225
+ def _activity_from_payload(payload: dict[str, Any]) -> ActivityEntry:
226
+ return ActivityEntry(
227
+ id=payload["id"],
228
+ actor=payload["actor"],
229
+ verb=payload["verb"],
230
+ entity_type=payload["entity_type"],
231
+ entity_id=payload["entity_id"],
232
+ summary=payload["summary"],
233
+ tenant_id=payload["tenant_id"],
234
+ created_at=datetime.fromisoformat(payload["created_at"]),
235
+ )
@@ -0,0 +1,313 @@
1
+ """Project use cases: list, read, create or update, and delete with its connections.
2
+
3
+ Project ids are unique across tenants in 2.0.0 storage, so an id another
4
+ tenant holds is reported as ``already_exists``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import json
11
+ import logging
12
+ from collections.abc import Awaitable, Callable
13
+ from dataclasses import replace
14
+ from typing import Any
15
+ from uuid import uuid4
16
+
17
+ from harborrag_core.base import utc_now
18
+ from harborrag_core.contracts.errors import (
19
+ HarborAlreadyRunningError,
20
+ HarborConflictError,
21
+ HarborInUseError,
22
+ HarborNotFoundError,
23
+ HarborPreconditionFailedError,
24
+ HarborValidationError,
25
+ )
26
+ from harborrag_core.domain.activity import ActivityEntry
27
+ from harborrag_core.domain.connection import CONNECTION_ID_PATTERN, Connection
28
+ from harborrag_core.domain.job import Job
29
+ from harborrag_core.domain.project import Project
30
+ from harborrag_engine.control_plane.connection_views import project_view, resolve_any_version
31
+ from harborrag_runtime.composition import ControlPlaneRepositories
32
+ from harborrag_runtime.config.connectors.models import ConnectionValidationError, FieldIssue
33
+
34
+ from .connection_models import ConnectionRuns
35
+ from .connections import ConnectionService
36
+ from .effect_recovery import log_activity
37
+
38
+ logger = logging.getLogger("harborrag.runtime.application.control_plane.projects")
39
+
40
+
41
+ class ProjectIdTakenError(HarborConflictError):
42
+ """The project id is already used by another tenant."""
43
+
44
+ error_code = "already_exists"
45
+
46
+
47
+ class ProjectService:
48
+ """Facade over projects and the cascade that removes their connections.
49
+
50
+ Args:
51
+ control_plane: Returns the control-plane repositories.
52
+ runs: Returns the run registry of connections.
53
+ connections: Connection service the removal cascade deletes through.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ *,
59
+ control_plane: Callable[[], ControlPlaneRepositories],
60
+ runs: Callable[[], Awaitable[ConnectionRuns]],
61
+ connections: ConnectionService,
62
+ ) -> None:
63
+ self._control_plane = control_plane
64
+ self._runs = runs
65
+ self._connections = connections
66
+
67
+ async def list_page(
68
+ self,
69
+ *,
70
+ tenant_id: str,
71
+ query: str | None = None,
72
+ limit: int = 20,
73
+ cursor: str | None = None,
74
+ ) -> tuple[list[dict[str, Any]], str | None]:
75
+ """Return one page of the tenant's projects ordered by id, optionally name-filtered."""
76
+ after = _decode_cursor(cursor) if cursor else ""
77
+ projects = sorted(
78
+ (
79
+ project
80
+ for project in await self._control_plane().projects.list(
81
+ tenant_ids=frozenset({tenant_id})
82
+ )
83
+ if project.id > after and (not query or query.casefold() in project.name.casefold())
84
+ ),
85
+ key=lambda project: project.id,
86
+ )
87
+ page = projects[:limit]
88
+ next_cursor = _encode_cursor(page[-1].id) if len(projects) > limit else None
89
+ return [await self._view(project) for project in page], next_cursor
90
+
91
+ async def get(self, *, tenant_id: str, project_id: str) -> tuple[dict[str, Any], int]:
92
+ """Return a project's view and version.
93
+
94
+ Raises:
95
+ HarborNotFoundError: No such project in the tenant.
96
+ """
97
+ project = await self._require(tenant_id, project_id)
98
+ return await self._view(project), project.version
99
+
100
+ async def put( # noqa: PLR0913 - one body plus its preconditions
101
+ self,
102
+ *,
103
+ tenant_id: str,
104
+ project_id: str,
105
+ name: str,
106
+ description: str | None,
107
+ actor: str,
108
+ expected_version: int | None = None,
109
+ create_only: bool = False,
110
+ ) -> tuple[dict[str, Any], bool, int]:
111
+ """Create or update a project.
112
+
113
+ Returns:
114
+ The view, whether it was created, and the stored version.
115
+
116
+ Raises:
117
+ ConnectionValidationError: ``project_id`` breaks the id pattern.
118
+ ProjectIdTakenError: Another tenant already uses ``project_id``.
119
+ HarborPreconditionFailedError: ``If-Match`` or ``If-None-Match`` does not hold.
120
+ """
121
+ if not CONNECTION_ID_PATTERN.fullmatch(project_id):
122
+ raise ConnectionValidationError(
123
+ [FieldIssue("project_id", "must match ^[a-z0-9][a-z0-9_-]{0,62}$")]
124
+ )
125
+ if not name.strip():
126
+ raise HarborValidationError("name must not be empty")
127
+ projects = self._control_plane().projects
128
+ existing = await projects.get(project_id, tenant_ids=None)
129
+ if existing is not None and existing.tenant_id != tenant_id:
130
+ raise ProjectIdTakenError(f"project id {project_id!r} is already used")
131
+ if existing is None:
132
+ if expected_version is not None:
133
+ raise HarborPreconditionFailedError("project does not exist")
134
+ created = await projects.create(
135
+ Project(
136
+ id=project_id,
137
+ name=name,
138
+ collection=project_id,
139
+ tenant_id=tenant_id,
140
+ description=description or "",
141
+ )
142
+ )
143
+ await self._record(created, "created", actor)
144
+ return await self._view(created), True, created.version
145
+ if create_only:
146
+ raise HarborPreconditionFailedError("project already exists")
147
+ replacement = replace(existing, name=name, description=description or "")
148
+ expected = resolve_any_version(expected_version, existing.version)
149
+ if replacement.name == existing.name and replacement.description == existing.description:
150
+ # A body that changes nothing stores nothing: keep the version and
151
+ # skip the activity entry, but still honour a stale If-Match.
152
+ if expected is not None and expected != existing.version:
153
+ raise HarborPreconditionFailedError("project changed since it was read")
154
+ return await self._view(existing), False, existing.version
155
+ updated = await projects.update(replacement, expected_version=expected)
156
+ await self._record(updated, "updated", actor)
157
+ return await self._view(updated), False, updated.version
158
+
159
+ async def delete(
160
+ self, *, tenant_id: str, project_id: str, actor: str, cascade: bool = False
161
+ ) -> str | None:
162
+ """Delete a project; with connections, only as a background cascade.
163
+
164
+ Returns:
165
+ None when the empty project was deleted, else the cascade's job id.
166
+
167
+ Raises:
168
+ HarborNotFoundError: No such project in the tenant.
169
+ HarborInUseError: It has connections and ``cascade`` is false.
170
+ HarborAlreadyRunningError: One of its connections is ingesting.
171
+ """
172
+ control_plane = self._control_plane()
173
+ project = await self._require(tenant_id, project_id)
174
+ connections = await self._project_connections(project)
175
+ if not connections:
176
+ await control_plane.projects.delete(project_id, tenant_ids=frozenset({tenant_id}))
177
+ await self._record(project, "deleted", actor)
178
+ return None
179
+ if not cascade:
180
+ raise HarborInUseError(
181
+ "the project still has connections; use cascade=true",
182
+ details={"connection_refs": [connection.ref for connection in connections]},
183
+ )
184
+ for connection in connections:
185
+ if await self._connections.connection_busy(tenant_id, connection.source_key):
186
+ raise HarborAlreadyRunningError(
187
+ f"connection {connection.ref!r} is ingesting",
188
+ details={"connection_ref": connection.ref},
189
+ )
190
+ job = await control_plane.jobs.save(
191
+ Job(
192
+ id=f"job_{uuid4().hex[:16]}",
193
+ source_id=project_id,
194
+ project_id=project_id,
195
+ job_type="delete_project",
196
+ tenant_id=tenant_id,
197
+ status="running",
198
+ payload={"project": project_id, "actor": actor},
199
+ )
200
+ )
201
+ for connection in connections:
202
+ await control_plane.connections.set_status(
203
+ tenant_id=tenant_id,
204
+ source_key=connection.source_key,
205
+ status="deleting",
206
+ detail={"job_id": job.id, "purge": True},
207
+ )
208
+ await self._record(project, "deleted", actor)
209
+ self._connections.spawn(self.finish_deletion(project, job_id=job.id))
210
+ return job.id
211
+
212
+ async def finish_deletion(self, project: Project, *, job_id: str) -> None:
213
+ """Remove every connection of the project, then the project itself.
214
+
215
+ While a connection remains, the job stays running with its last error, so
216
+ the next start's ``resume_deletions`` tries again; it succeeds only once
217
+ the project row is gone.
218
+ """
219
+ control_plane = self._control_plane()
220
+ for connection in await self._project_connections(project):
221
+ await self._connections.finish_deletion(connection, job_id=job_id, purge=True)
222
+ remaining = await self._project_connections(project)
223
+ job = await control_plane.jobs.get(job_id, tenant_ids=frozenset({project.tenant_id}))
224
+ if remaining:
225
+ if job is not None:
226
+ await control_plane.jobs.save(
227
+ replace(job, status="running", last_error="connections remain")
228
+ )
229
+ return
230
+ await control_plane.projects.delete(project.id, tenant_ids=frozenset({project.tenant_id}))
231
+ if job is not None:
232
+ await control_plane.jobs.save(replace(job, status="succeeded", finished_at=utc_now()))
233
+
234
+ async def resume_deletions(self) -> int:
235
+ """Finish every project cascade a previous process left running."""
236
+ control_plane = self._control_plane()
237
+ jobs = [
238
+ job
239
+ for job in await control_plane.jobs.list("running", tenant_ids=None)
240
+ if job.job_type == "delete_project"
241
+ ]
242
+ for job in jobs:
243
+ project = await control_plane.projects.get(
244
+ job.project_id, tenant_ids=frozenset({job.tenant_id})
245
+ )
246
+ if project is not None:
247
+ await self.finish_deletion(project, job_id=job.id)
248
+ else:
249
+ await control_plane.jobs.save(
250
+ replace(job, status="succeeded", finished_at=utc_now(), last_error=None)
251
+ )
252
+ return len(jobs)
253
+
254
+ async def _require(self, tenant_id: str, project_id: str) -> Project:
255
+ """Return the project or raise not found."""
256
+ project = await self._control_plane().projects.get(
257
+ project_id, tenant_ids=frozenset({tenant_id})
258
+ )
259
+ if project is None:
260
+ raise HarborNotFoundError(f"project {project_id!r} not found")
261
+ return project
262
+
263
+ async def _project_connections(self, project: Project) -> list[Connection]:
264
+ """Every connection of the project."""
265
+ connections, _ = await self._control_plane().connections.list(
266
+ tenant_ids=frozenset({project.tenant_id}), project_id=project.id
267
+ )
268
+ return connections
269
+
270
+ async def _view(self, project: Project) -> dict[str, Any]:
271
+ """Return the API view with connection and document counts."""
272
+ connections = await self._project_connections(project)
273
+ runs = await self._runs()
274
+ documents = 0
275
+ for connection in connections:
276
+ documents += await runs.connection_document_count(
277
+ tenant_id=project.tenant_id, connection_id=connection.source_key
278
+ )
279
+ return project_view(project, connections=len(connections), documents=documents)
280
+
281
+ async def _record(self, project: Project, verb: str, actor: str) -> None:
282
+ """Append an audit entry for a project write."""
283
+ await log_activity(
284
+ self._control_plane(),
285
+ ActivityEntry(
286
+ id=f"act_{uuid4().hex}",
287
+ tenant_id=project.tenant_id,
288
+ actor=actor,
289
+ verb=verb,
290
+ entity_type="project",
291
+ entity_id=project.id,
292
+ summary=f"{verb.capitalize()} project {project.id!r}",
293
+ ),
294
+ )
295
+
296
+
297
+ def _encode_cursor(project_id: str) -> str:
298
+ """Opaque cursor after ``project_id``."""
299
+ payload = json.dumps({"after": project_id}).encode("utf-8")
300
+ return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=")
301
+
302
+
303
+ def _decode_cursor(value: str) -> str:
304
+ """Project id a cursor points after.
305
+
306
+ Raises:
307
+ HarborValidationError: The cursor is malformed.
308
+ """
309
+ try:
310
+ payload = json.loads(base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)))
311
+ return str(payload["after"])
312
+ except (KeyError, TypeError, ValueError) as error:
313
+ raise HarborValidationError("project cursor is invalid", {"field": "cursor"}) from error