hexkit 10.0.0__tar.gz → 11.0.0__tar.gz
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.
- {hexkit-10.0.0/src/hexkit.egg-info → hexkit-11.0.0}/PKG-INFO +1 -1
- {hexkit-10.0.0 → hexkit-11.0.0}/pyproject.toml +1 -1
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/.agents/skills/hexkit/SKILL.md +10 -1
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/opentelemetry/instrumentation.py +48 -3
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/protocols/dao.py +177 -49
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/protocols/objstorage.py +3 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/akafka/provider/eventsub.py +362 -70
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/akafka/testutils.py +30 -10
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongodb/provider/__init__.py +4 -4
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongodb/provider/dao.py +326 -52
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongodb/provider/utils.py +5 -2
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongokafka/provider/daopub.py +162 -59
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/provider/objstorage.py +5 -3
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/testing/dao.py +102 -31
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/testing/objstorage.py +8 -3
- {hexkit-10.0.0 → hexkit-11.0.0/src/hexkit.egg-info}/PKG-INFO +1 -1
- {hexkit-10.0.0 → hexkit-11.0.0}/LICENSE +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/MANIFEST.in +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/README.md +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/setup.cfg +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/__main__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/base.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/config.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/correlation.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/custom_types.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/log.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/opentelemetry/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/opentelemetry/testutils.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/protocols/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/protocols/daopub.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/protocols/daosub.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/protocols/eventpub.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/protocols/eventsub.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/protocols/kvstore.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/akafka/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/akafka/config.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/akafka/provider/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/akafka/provider/daosub.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/akafka/provider/eventpub.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/akafka/provider/utils.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/akafka/testcontainer.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongodb/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongodb/config.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongodb/migrations/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongodb/migrations/_manager.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongodb/migrations/_utils.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongodb/migrations/helpers.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongodb/provider/client.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongodb/provider/kvstore.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongodb/testutils.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongokafka/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongokafka/config.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongokafka/provider/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongokafka/provider/persistent_pub.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/mongokafka/testutils.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/redis/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/redis/config.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/redis/provider/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/redis/provider/client.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/redis/provider/kvstore.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/redis/testutils.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/config.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/provider/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/provider/kvstore.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/test_files/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/test_files/test_file1.yaml +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/test_files/test_file2.yaml +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/test_files/test_file3.yaml +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/test_files/test_file4.yaml +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/testutils/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/testutils/_fixtures.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/testutils/_typical_workflow.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/s3/testutils/_utils.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/testing/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/testing/eventpub.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/testing/kvstore.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/vault/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/vault/config.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/vault/provider/__init__.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/vault/provider/client.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/vault/provider/kvstore.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/providers/vault/testutils.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/py.typed +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit/utils.py +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit.egg-info/SOURCES.txt +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit.egg-info/dependency_links.txt +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit.egg-info/requires.txt +0 -0
- {hexkit-10.0.0 → hexkit-11.0.0}/src/hexkit.egg-info/top_level.txt +0 -0
|
@@ -24,7 +24,7 @@ classifiers = [
|
|
|
24
24
|
]
|
|
25
25
|
name = "hexkit"
|
|
26
26
|
# 9.0.2 is spent on TestPyPI: a pypi-publish.yaml rehearsal uploaded it there.
|
|
27
|
-
version = "
|
|
27
|
+
version = "11.0.0"
|
|
28
28
|
description = "A Toolkit for Building Microservices using the Hexagonal Architecture"
|
|
29
29
|
license = "Apache-2.0"
|
|
30
30
|
dependencies = [
|
|
@@ -38,6 +38,8 @@ Look at the stored data, not the event, when choosing between the outbox and the
|
|
|
38
38
|
- Give each inbound prepare function an optional override of the core port, compared with `is not None`, so tests can run the real adapter against a mock core.
|
|
39
39
|
- Each entrypoint creates the config, calls `configure_logging` exactly once (a second call duplicates every line), and uses one prepare function.
|
|
40
40
|
Call `configure_opentelemetry` before any app or client is constructed: a FastAPI app created earlier is silently left untraced.
|
|
41
|
+
Metrics need `enable_otel_metrics` as well as `enable_opentelemetry`.
|
|
42
|
+
Never query the database in an observable gauge's callback: it runs on the exporter thread and cannot await; read on the event loop and let the callback report the cached value ([Metrics](https://ghga-de.github.io/ghga/hexkit/user-guide/observability_tools/opentelemetry.md#metrics)).
|
|
41
43
|
|
|
42
44
|
## Configuration
|
|
43
45
|
|
|
@@ -52,7 +54,9 @@ Look at the stored data, not the event, when choosing between the outbox and the
|
|
|
52
54
|
|
|
53
55
|
- Bind each DAO to a frozen Pydantic DTO that carries its own ID (`UUID4Field()` generates one); change a resource with `model_copy(update=...)` and write it back.
|
|
54
56
|
- `insert` fails on an existing ID, `update` and `delete` on a missing one; use `upsert` only where create-or-replace is meant.
|
|
55
|
-
-
|
|
57
|
+
- `insert_many`, `update_many` and `upsert_many` write a batch in one call; they are not atomic, and their `BatchOperationError` maps each failed ID to the error that `insert`, `update` or `upsert` raises.
|
|
58
|
+
`delete_many` ignores unknown IDs.
|
|
59
|
+
- Filter with `filter_=`; hexkit 11 removed `mapping=`.
|
|
56
60
|
- `find_all` is not awaited: it returns a lazy `FindResult` with `to_list()` and `total_count()`.
|
|
57
61
|
Always pass `sort` with `skip` and `limit`.
|
|
58
62
|
- For read-modify-write under concurrent writers, pass `precondition=` to `update` and wrap the read and the update in `race_condition_retries` from `hexkit.protocols.dao`, which retries on `PreconditionFailedError`; do not write a retry loop of your own.
|
|
@@ -70,6 +74,7 @@ Look at the stored data, not the event, when choosing between the outbox and the
|
|
|
70
74
|
- Delivery is at least once, so every translator is idempotent.
|
|
71
75
|
- Let an exception propagate from the translator: it triggers the retries (`kafka_max_retries`, `kafka_retry_backoff`) and then the dead letter queue (`kafka_enable_dlq`), which needs a `dlq_publisher` passed to `construct()` ([Dead Letter Queue](https://ghga-de.github.io/ghga/hexkit/user-guide/arch_concepts/dlq.md)).
|
|
72
76
|
A caught and logged exception commits the offset, and the event is lost.
|
|
77
|
+
- A record whose key is not ASCII or whose value is not a JSON object never reaches the translator: it goes to the DLQ wrapped, or, with the DLQ off, raises `MalformedRecordError` ([Malformed Records](https://ghga-de.github.io/ghga/hexkit/user-guide/providers/kafka/subscriber.md#malformed-records)).
|
|
73
78
|
- One subscriber takes one translator; combine several, outbox translators included, with `ComboTranslator`.
|
|
74
79
|
- `service_name` is the consumer group, so all instances of a service share the events.
|
|
75
80
|
- Correlation IDs travel with events and logs on their own; set one only where work starts without a request or event, such as a job, with `set_new_correlation_id()` ([Correlation IDs](https://ghga-de.github.io/ghga/hexkit/user-guide/observability_tools/correlation_ids.md)).
|
|
@@ -82,6 +87,10 @@ Look at the stored data, not the event, when choosing between the outbox and the
|
|
|
82
87
|
- A deleted resource keeps a stub with a `__metadata__` field in the collection; read and write it only through the DAO.
|
|
83
88
|
- Read and write a collection only through Outbox DAOs with the same model, topic and `dto_to_event`, never also through a plain DAO or directly: such access publishes nothing and breaks the outbox metadata.
|
|
84
89
|
A consumer's copy in its own database is a different collection and may use any DAO ([One DAO per collection](https://ghga-de.github.io/ghga/hexkit/user-guide/providers/mongokafka.md#one-dao-per-collection)).
|
|
90
|
+
- A batch publishes its events one by one after its write and raises at the first failed one, as a single write does; `publish_pending()` sends what is left.
|
|
91
|
+
When the write failed for some IDs, the batch logs the failed publish and raises its `BatchOperationError` instead.
|
|
92
|
+
The publisher's `delete_many` raises one too, for the IDs it could not tombstone.
|
|
93
|
+
Publishing takes milliseconds per resource, so expect seconds for thousands ([Publishing a batch](https://ghga-de.github.io/ghga/hexkit/user-guide/providers/mongokafka.md#publishing-a-batch)).
|
|
85
94
|
- Offer `publish_pending()` and `republish()` as a command, such as `publish-events`, run as a job: it publishes what failed to publish, and fills a new consumer.
|
|
86
95
|
- On the consuming side, implement `changed()` as an upsert and let `deleted()` accept a resource that is already gone.
|
|
87
96
|
|
|
@@ -17,11 +17,19 @@
|
|
|
17
17
|
|
|
18
18
|
import importlib
|
|
19
19
|
import logging
|
|
20
|
+
import uuid
|
|
21
|
+
from collections.abc import Sequence
|
|
20
22
|
from typing import Annotated
|
|
21
23
|
|
|
22
|
-
from opentelemetry import trace
|
|
24
|
+
from opentelemetry import metrics, trace
|
|
25
|
+
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
|
23
26
|
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
|
24
|
-
from opentelemetry.sdk.
|
|
27
|
+
from opentelemetry.sdk.metrics import MeterProvider
|
|
28
|
+
from opentelemetry.sdk.metrics.export import (
|
|
29
|
+
MetricReader,
|
|
30
|
+
PeriodicExportingMetricReader,
|
|
31
|
+
)
|
|
32
|
+
from opentelemetry.sdk.resources import SERVICE_INSTANCE_ID, SERVICE_NAME, Resource
|
|
25
33
|
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
|
|
26
34
|
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
|
27
35
|
from opentelemetry.sdk.trace.sampling import ParentBasedTraceIdRatio
|
|
@@ -82,6 +90,27 @@ class OpenTelemetryConfig(BaseSettings):
|
|
|
82
90
|
"Setting this to 0 will result in no spans being sampled, but this does not "
|
|
83
91
|
"automatically set `enable_opentelemetry` to False.",
|
|
84
92
|
)
|
|
93
|
+
enable_otel_metrics: bool = Field(
|
|
94
|
+
default=False,
|
|
95
|
+
description="Also export metrics via OTLP. Requires `enable_opentelemetry` "
|
|
96
|
+
"and a collector with a metrics pipeline.",
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _build_resource(service_name: str) -> Resource:
|
|
101
|
+
"""Build the resource that identifies this process in traces and metrics.
|
|
102
|
+
|
|
103
|
+
Each process needs its own `service.instance.id`: the metrics backend tells the
|
|
104
|
+
replicas and workers of a service apart by it, and without one their metrics
|
|
105
|
+
land in a single series that each push overwrites. `Resource.create` adds a
|
|
106
|
+
random one in recent SDK versions; it is added here for those that lack it.
|
|
107
|
+
`Resource.create` also merges `OTEL_RESOURCE_ATTRIBUTES`, so a deployment can
|
|
108
|
+
set `k8s.pod.name` or a fixed instance ID there.
|
|
109
|
+
"""
|
|
110
|
+
resource = Resource.create({SERVICE_NAME: service_name})
|
|
111
|
+
if not resource.attributes.get(SERVICE_INSTANCE_ID):
|
|
112
|
+
resource = resource.merge(Resource({SERVICE_INSTANCE_ID: str(uuid.uuid4())}))
|
|
113
|
+
return resource
|
|
85
114
|
|
|
86
115
|
|
|
87
116
|
def configure_opentelemetry(
|
|
@@ -89,6 +118,7 @@ def configure_opentelemetry(
|
|
|
89
118
|
service_name: str,
|
|
90
119
|
config: OpenTelemetryConfig,
|
|
91
120
|
span_processor: SpanProcessor | None = None,
|
|
121
|
+
metric_readers: Sequence[MetricReader] | None = None,
|
|
92
122
|
):
|
|
93
123
|
"""Configure all needed parts of OpenTelemetry.
|
|
94
124
|
|
|
@@ -99,12 +129,15 @@ def configure_opentelemetry(
|
|
|
99
129
|
leaving the default no-op TracerProvider from the OpenTelemetry API in place.
|
|
100
130
|
|
|
101
131
|
By default, spans are exported via OTLP over HTTP using a `BatchSpanProcessor`.
|
|
132
|
+
If `enable_otel_metrics` is set, a MeterProvider with the same resource is set up
|
|
133
|
+
too, by default exporting via OTLP over HTTP on the interval given by the
|
|
134
|
+
`OTEL_METRIC_EXPORT_INTERVAL` environment variable (60 seconds if unset).
|
|
102
135
|
"""
|
|
103
136
|
if not config.enable_opentelemetry:
|
|
104
137
|
logger.info("OpenTelemetry disabled via config.")
|
|
105
138
|
return
|
|
106
139
|
|
|
107
|
-
resource =
|
|
140
|
+
resource = _build_resource(service_name)
|
|
108
141
|
# Replace the default static sampler with a probabilistic one that honors parent
|
|
109
142
|
# span sampling decisions
|
|
110
143
|
# This should consistently yield full traces within a service but not necessarily
|
|
@@ -120,4 +153,16 @@ def configure_opentelemetry(
|
|
|
120
153
|
)
|
|
121
154
|
trace.set_tracer_provider(trace_provider)
|
|
122
155
|
|
|
156
|
+
# Set before instrumenting, so the instrumented libraries record their metrics
|
|
157
|
+
# on this provider from the start
|
|
158
|
+
if config.enable_otel_metrics:
|
|
159
|
+
readers = (
|
|
160
|
+
metric_readers
|
|
161
|
+
if metric_readers is not None
|
|
162
|
+
else [PeriodicExportingMetricReader(OTLPMetricExporter())]
|
|
163
|
+
)
|
|
164
|
+
metrics.set_meter_provider(
|
|
165
|
+
MeterProvider(resource=resource, metric_readers=readers)
|
|
166
|
+
)
|
|
167
|
+
|
|
123
168
|
instrument_installed_libraries()
|
|
@@ -19,10 +19,17 @@ with the database.
|
|
|
19
19
|
"""
|
|
20
20
|
|
|
21
21
|
import typing
|
|
22
|
-
import warnings
|
|
23
22
|
from abc import ABC, abstractmethod
|
|
24
23
|
from asyncio import sleep
|
|
25
|
-
from collections
|
|
24
|
+
from collections import Counter
|
|
25
|
+
from collections.abc import (
|
|
26
|
+
AsyncIterator,
|
|
27
|
+
Awaitable,
|
|
28
|
+
Callable,
|
|
29
|
+
Collection,
|
|
30
|
+
Iterable,
|
|
31
|
+
Mapping,
|
|
32
|
+
)
|
|
26
33
|
from contextlib import AbstractAsyncContextManager
|
|
27
34
|
from functools import partial
|
|
28
35
|
from logging import Logger
|
|
@@ -37,6 +44,7 @@ from hexkit.custom_types import ID
|
|
|
37
44
|
from hexkit.utils import FieldNotInModelError, validate_fields_in_model
|
|
38
45
|
|
|
39
46
|
__all__ = [
|
|
47
|
+
"BatchOperationError",
|
|
40
48
|
"Dao",
|
|
41
49
|
"DaoFactoryProtocol",
|
|
42
50
|
"FindError",
|
|
@@ -113,45 +121,72 @@ class PreconditionFailedError(DaoError):
|
|
|
113
121
|
super().__init__(message)
|
|
114
122
|
|
|
115
123
|
|
|
116
|
-
#
|
|
117
|
-
|
|
118
|
-
"The mapping parameter is being renamed to filter_, and support for mapping will"
|
|
119
|
-
" be removed in hexkit v11.0.0."
|
|
120
|
-
)
|
|
124
|
+
# How many IDs an error message names before it only counts the rest
|
|
125
|
+
_NAMED_IDS = 5
|
|
121
126
|
|
|
122
127
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
"""Return the filter to use, accepting the deprecated `mapping` name for it.
|
|
128
|
+
def _named_ids(ids: list[ID]) -> str:
|
|
129
|
+
"""Name the first IDs and count the rest, so that a log line stays short."""
|
|
130
|
+
named = str(ids[:_NAMED_IDS])
|
|
131
|
+
if len(ids) > _NAMED_IDS:
|
|
132
|
+
named += f" and {len(ids) - _NAMED_IDS} more"
|
|
133
|
+
return named
|
|
134
|
+
|
|
131
135
|
|
|
132
|
-
|
|
133
|
-
|
|
136
|
+
def _note_all_ids(error: Exception, ids: list[ID]) -> None:
|
|
137
|
+
"""Attach every ID when the message leaves some out.
|
|
138
|
+
|
|
139
|
+
A traceback prints the note, while `str(error)`, and so a log line of the
|
|
140
|
+
message, leaves it out.
|
|
134
141
|
"""
|
|
135
|
-
if
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
return filter_
|
|
142
|
+
if len(ids) > _NAMED_IDS:
|
|
143
|
+
error.add_note(f"All {len(ids)} IDs: {ids}")
|
|
144
|
+
|
|
139
145
|
|
|
140
|
-
|
|
141
|
-
|
|
146
|
+
class BatchOperationError(DaoError):
|
|
147
|
+
"""Raised when a batch partly failed: what it names failed, the rest succeeded.
|
|
142
148
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
149
|
+
`errors` maps each failed ID to the error a single-resource method would raise.
|
|
150
|
+
It also names each resource whose write was applied but not confirmed, such as
|
|
151
|
+
after a MongoDB write concern error, with the error a single write raises for that;
|
|
152
|
+
such a write stays stored unless a failover rolls it back.
|
|
153
|
+
`not_attempted` lists, in input order, the IDs an ordered batch skipped after its
|
|
154
|
+
first failure. An unordered batch attempts every resource, so for it the list is
|
|
155
|
+
empty.
|
|
156
|
+
|
|
157
|
+
The message names the first five failed IDs; when there are more, a note on the
|
|
158
|
+
error, which a traceback prints, lists all of them.
|
|
159
|
+
"""
|
|
160
|
+
|
|
161
|
+
def __init__(
|
|
162
|
+
self, *, errors: Mapping[ID, DaoError], not_attempted: Collection[ID] = ()
|
|
163
|
+
):
|
|
164
|
+
self.errors = dict(errors)
|
|
165
|
+
self.not_attempted = tuple(not_attempted)
|
|
166
|
+
failed = list(self.errors)
|
|
167
|
+
super().__init__(
|
|
168
|
+
f"{len(failed)} resource(s) of the batch failed: {_named_ids(failed)}"
|
|
169
|
+
)
|
|
170
|
+
_note_all_ids(self, failed)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def ensure_distinct_ids(ids: Iterable[ID]) -> None:
|
|
174
|
+
"""Raise a ValueError naming the IDs that occur more than once in a batch."""
|
|
175
|
+
duplicates = [id_ for id_, count in Counter(ids).items() if count > 1]
|
|
176
|
+
if duplicates:
|
|
177
|
+
error = ValueError(
|
|
178
|
+
f"The batch holds these IDs more than once: {_named_ids(duplicates)}"
|
|
179
|
+
)
|
|
180
|
+
_note_all_ids(error, duplicates)
|
|
181
|
+
raise error
|
|
147
182
|
|
|
148
183
|
|
|
149
184
|
class FindError(DaoError):
|
|
150
185
|
"""Base for all error related to DAO find operations."""
|
|
151
186
|
|
|
152
187
|
|
|
153
|
-
class
|
|
154
|
-
"""Raised when an invalid
|
|
188
|
+
class InvalidFilterError(FindError):
|
|
189
|
+
"""Raised when an invalid filter was provided to find."""
|
|
155
190
|
|
|
156
191
|
|
|
157
192
|
class MultipleHitsFoundError(FindError):
|
|
@@ -159,14 +194,11 @@ class MultipleHitsFoundError(FindError):
|
|
|
159
194
|
single hit was expected.
|
|
160
195
|
"""
|
|
161
196
|
|
|
162
|
-
# TODO: Remove `mapping` when moving hexkit to v11.0.0
|
|
163
197
|
def __init__(
|
|
164
198
|
self,
|
|
165
199
|
*,
|
|
166
|
-
filter_: Mapping[str, str]
|
|
167
|
-
mapping: Mapping[str, str] | None = None,
|
|
200
|
+
filter_: Mapping[str, str],
|
|
168
201
|
):
|
|
169
|
-
filter_ = resolve_filter(filter_, mapping)
|
|
170
202
|
message = (
|
|
171
203
|
"Multiple hits were found for the following key-value pairs while only a"
|
|
172
204
|
f" single one was expected: {filter_}"
|
|
@@ -179,14 +211,11 @@ class NoHitsFoundError(FindError):
|
|
|
179
211
|
single hit was expected.
|
|
180
212
|
"""
|
|
181
213
|
|
|
182
|
-
# TODO: Remove `mapping` when moving hexkit to v11.0.0
|
|
183
214
|
def __init__(
|
|
184
215
|
self,
|
|
185
216
|
*,
|
|
186
|
-
filter_: Mapping[str, str]
|
|
187
|
-
mapping: Mapping[str, str] | None = None,
|
|
217
|
+
filter_: Mapping[str, str],
|
|
188
218
|
):
|
|
189
|
-
filter_ = resolve_filter(filter_, mapping)
|
|
190
219
|
message = (
|
|
191
220
|
"No hits were found for the following key-value pairs while a single one"
|
|
192
221
|
f" was expected: {filter_}"
|
|
@@ -298,7 +327,7 @@ class Dao(typing.Protocol[Dto]):
|
|
|
298
327
|
when resource with the id specified in the dto was not found
|
|
299
328
|
PreconditionFailedError:
|
|
300
329
|
when the resource exists but doesn't match `precondition`
|
|
301
|
-
|
|
330
|
+
InvalidFilterError: when `precondition` doesn't pass validation
|
|
302
331
|
UniqueConstraintViolationError:
|
|
303
332
|
when updating the dto would violate a unique index constraint over some
|
|
304
333
|
field other than the ID field.
|
|
@@ -316,12 +345,10 @@ class Dao(typing.Protocol[Dto]):
|
|
|
316
345
|
"""
|
|
317
346
|
...
|
|
318
347
|
|
|
319
|
-
# TODO: Remove `mapping` when moving hexkit to v11.0.0
|
|
320
348
|
async def find_one(
|
|
321
349
|
self,
|
|
322
350
|
*,
|
|
323
|
-
filter_: Mapping[str, Any]
|
|
324
|
-
mapping: Mapping[str, Any] | None = None,
|
|
351
|
+
filter_: Mapping[str, Any],
|
|
325
352
|
) -> Dto:
|
|
326
353
|
"""Find the resource that matches the specified filter.
|
|
327
354
|
|
|
@@ -337,8 +364,6 @@ class Dao(typing.Protocol[Dto]):
|
|
|
337
364
|
filter_:
|
|
338
365
|
A mapping where the keys correspond to the names of resource fields
|
|
339
366
|
and the values correspond to the actual values of the resource fields
|
|
340
|
-
mapping:
|
|
341
|
-
Deprecated alias for `filter_`.
|
|
342
367
|
|
|
343
368
|
Returns:
|
|
344
369
|
Returns a hit in the form of the respective DTO model if exactly one hit
|
|
@@ -352,12 +377,10 @@ class Dao(typing.Protocol[Dto]):
|
|
|
352
377
|
"""
|
|
353
378
|
...
|
|
354
379
|
|
|
355
|
-
# TODO: Remove `mapping` when moving hexkit to v11.0.0
|
|
356
380
|
def find_all(
|
|
357
381
|
self,
|
|
358
382
|
*,
|
|
359
|
-
filter_: Mapping[str, Any]
|
|
360
|
-
mapping: Mapping[str, Any] | None = None,
|
|
383
|
+
filter_: Mapping[str, Any],
|
|
361
384
|
skip: int | None = None,
|
|
362
385
|
limit: int | None = None,
|
|
363
386
|
sort: list[str] | None = None,
|
|
@@ -373,8 +396,6 @@ class Dao(typing.Protocol[Dto]):
|
|
|
373
396
|
filter_:
|
|
374
397
|
A mapping where the keys correspond to the names of resource fields
|
|
375
398
|
and the values correspond to the actual values of the resource fields.
|
|
376
|
-
mapping:
|
|
377
|
-
Deprecated alias for `filter_`.
|
|
378
399
|
skip:
|
|
379
400
|
Number of matching resources to skip before yielding results.
|
|
380
401
|
Defaults to None (no skipping).
|
|
@@ -394,7 +415,7 @@ class Dao(typing.Protocol[Dto]):
|
|
|
394
415
|
A FindResult that is async-iterable and also provides total_count().
|
|
395
416
|
|
|
396
417
|
Raises:
|
|
397
|
-
|
|
418
|
+
InvalidFilterError: If `filter_` doesn't pass validation.
|
|
398
419
|
ValueError: if `skip` or `limit` are less than 0.
|
|
399
420
|
"""
|
|
400
421
|
...
|
|
@@ -431,6 +452,113 @@ class Dao(typing.Protocol[Dto]):
|
|
|
431
452
|
"""
|
|
432
453
|
...
|
|
433
454
|
|
|
455
|
+
async def insert_many(
|
|
456
|
+
self, dtos: Collection[Dto], *, ordered: bool = False
|
|
457
|
+
) -> None:
|
|
458
|
+
"""Create several resources in one call.
|
|
459
|
+
|
|
460
|
+
The batch is not atomic: when some resources fail, the others are still
|
|
461
|
+
created. An empty batch writes nothing.
|
|
462
|
+
|
|
463
|
+
Args:
|
|
464
|
+
dtos:
|
|
465
|
+
The resources as pydantic-based data transfer objects, each including
|
|
466
|
+
its ID. No two of them may share an ID.
|
|
467
|
+
ordered:
|
|
468
|
+
Whether to stop at the first failure and skip the remaining resources,
|
|
469
|
+
instead of attempting every one.
|
|
470
|
+
|
|
471
|
+
Raises:
|
|
472
|
+
ValueError: when two DTOs share an ID; nothing is written then.
|
|
473
|
+
BatchOperationError:
|
|
474
|
+
when some resources failed. Each failed ID maps to
|
|
475
|
+
`ResourceAlreadyExistsError` if a resource with that ID already exists,
|
|
476
|
+
to `UniqueConstraintViolationError` if it clashes with a unique index
|
|
477
|
+
over another field, to `DbTimeoutError` if its write timed out, or to
|
|
478
|
+
a plain `DaoError` for any other failure, such as a failed document
|
|
479
|
+
validation. A failed write concern also names each resource it left
|
|
480
|
+
unconfirmed, with `DbTimeoutError` if it timed out or a plain
|
|
481
|
+
`DaoError` otherwise; those resources stay stored.
|
|
482
|
+
"""
|
|
483
|
+
...
|
|
484
|
+
|
|
485
|
+
async def update_many(
|
|
486
|
+
self, dtos: Collection[Dto], *, ordered: bool = False
|
|
487
|
+
) -> None:
|
|
488
|
+
"""Replace several existing resources in one call, matched by their IDs.
|
|
489
|
+
|
|
490
|
+
The batch is not atomic: when some resources fail, the others are still
|
|
491
|
+
replaced. An empty batch writes nothing.
|
|
492
|
+
|
|
493
|
+
Args:
|
|
494
|
+
dtos:
|
|
495
|
+
The updated resources as pydantic-based data transfer objects, each
|
|
496
|
+
including its ID. No two of them may share an ID.
|
|
497
|
+
ordered:
|
|
498
|
+
Whether to stop at the first failure and skip the remaining resources,
|
|
499
|
+
instead of attempting every one. A missing resource never stops the
|
|
500
|
+
batch.
|
|
501
|
+
|
|
502
|
+
Raises:
|
|
503
|
+
ValueError: when two DTOs share an ID; nothing is written then.
|
|
504
|
+
BatchOperationError:
|
|
505
|
+
when some resources failed. Each failed ID maps to
|
|
506
|
+
`ResourceNotFoundError` if no resource with that ID exists, to
|
|
507
|
+
`UniqueConstraintViolationError` if it clashes with a unique index over
|
|
508
|
+
another field, to `DbTimeoutError` if its write timed out, or to a plain
|
|
509
|
+
`DaoError` for any other failure, such as a failed document validation.
|
|
510
|
+
A failed write concern also names each resource it left unconfirmed,
|
|
511
|
+
a missing one included, with `DbTimeoutError` if it timed out or a
|
|
512
|
+
plain `DaoError` otherwise; those resources stay stored.
|
|
513
|
+
"""
|
|
514
|
+
...
|
|
515
|
+
|
|
516
|
+
async def upsert_many(
|
|
517
|
+
self, dtos: Collection[Dto], *, ordered: bool = False
|
|
518
|
+
) -> None:
|
|
519
|
+
"""Create or replace several resources in one call, matched by their IDs.
|
|
520
|
+
|
|
521
|
+
The batch is not atomic: when some resources fail, the others are still
|
|
522
|
+
written. An empty batch writes nothing.
|
|
523
|
+
|
|
524
|
+
Args:
|
|
525
|
+
dtos:
|
|
526
|
+
The resources as pydantic-based data transfer objects, each including
|
|
527
|
+
its ID. No two of them may share an ID.
|
|
528
|
+
ordered:
|
|
529
|
+
Whether to stop at the first failure and skip the remaining resources,
|
|
530
|
+
instead of attempting every one.
|
|
531
|
+
|
|
532
|
+
Raises:
|
|
533
|
+
ValueError: when two DTOs share an ID; nothing is written then.
|
|
534
|
+
BatchOperationError:
|
|
535
|
+
when some resources failed. Each failed ID maps to
|
|
536
|
+
`UniqueConstraintViolationError` if it clashes with a unique index over
|
|
537
|
+
another field, to `DbTimeoutError` if its write timed out, or to a plain
|
|
538
|
+
`DaoError` for any other failure, such as a failed document validation.
|
|
539
|
+
A failed write concern also names each resource it left unconfirmed,
|
|
540
|
+
with `DbTimeoutError` if it timed out or a plain `DaoError` otherwise;
|
|
541
|
+
those resources stay stored.
|
|
542
|
+
"""
|
|
543
|
+
...
|
|
544
|
+
|
|
545
|
+
async def delete_many(self, ids: Collection[ID]) -> None:
|
|
546
|
+
"""Delete several resources in one call by providing their IDs.
|
|
547
|
+
|
|
548
|
+
IDs that do not exist are ignored, and an ID given more than once is deleted
|
|
549
|
+
once. An empty batch deletes nothing.
|
|
550
|
+
|
|
551
|
+
Args:
|
|
552
|
+
ids: The IDs of the resources.
|
|
553
|
+
|
|
554
|
+
Raises:
|
|
555
|
+
TypeError: when `ids` is a single string instead of a collection of IDs.
|
|
556
|
+
DbTimeoutError: when the write or its write concern timed out.
|
|
557
|
+
DaoError: when the write concern failed otherwise, which no single resource
|
|
558
|
+
caused.
|
|
559
|
+
"""
|
|
560
|
+
...
|
|
561
|
+
|
|
434
562
|
|
|
435
563
|
class DaoFactoryBase:
|
|
436
564
|
"""A base for Data Access Objects (DAO) Factory protocols."""
|
|
@@ -123,6 +123,7 @@ class ObjectStorageProtocol(ABC):
|
|
|
123
123
|
part_number: int,
|
|
124
124
|
expires_after: int = 3600,
|
|
125
125
|
part_md5: str | None = None,
|
|
126
|
+
verify_upload: bool = True,
|
|
126
127
|
) -> str:
|
|
127
128
|
"""Given a id of an instantiated multipart upload along with the corresponding
|
|
128
129
|
bucket and object ID, it returns a presigned URL for uploading a file part with the
|
|
@@ -139,6 +140,7 @@ class ObjectStorageProtocol(ABC):
|
|
|
139
140
|
part_number=part_number,
|
|
140
141
|
expires_after=expires_after,
|
|
141
142
|
part_md5=part_md5,
|
|
143
|
+
verify_upload=verify_upload,
|
|
142
144
|
)
|
|
143
145
|
|
|
144
146
|
async def abort_multipart_upload(
|
|
@@ -420,6 +422,7 @@ class ObjectStorageProtocol(ABC):
|
|
|
420
422
|
part_number: int,
|
|
421
423
|
expires_after: int = 3600,
|
|
422
424
|
part_md5: str | None = None,
|
|
425
|
+
verify_upload: bool = True,
|
|
423
426
|
) -> str:
|
|
424
427
|
"""
|
|
425
428
|
Given a id of an instantiated multipart upload along with the corresponding
|