sqllocks-shape-eventhubs 0.9.1__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.
- sqllocks_shape_eventhubs-0.9.1/LICENSE +21 -0
- sqllocks_shape_eventhubs-0.9.1/PKG-INFO +75 -0
- sqllocks_shape_eventhubs-0.9.1/README.md +49 -0
- sqllocks_shape_eventhubs-0.9.1/pyproject.toml +43 -0
- sqllocks_shape_eventhubs-0.9.1/setup.cfg +4 -0
- sqllocks_shape_eventhubs-0.9.1/src/shape_eventhubs/__init__.py +18 -0
- sqllocks_shape_eventhubs-0.9.1/src/shape_eventhubs/emitter.py +261 -0
- sqllocks_shape_eventhubs-0.9.1/src/shape_eventhubs/source.py +408 -0
- sqllocks_shape_eventhubs-0.9.1/src/shape_eventhubs/testing.py +382 -0
- sqllocks_shape_eventhubs-0.9.1/src/sqllocks_shape_eventhubs.egg-info/PKG-INFO +75 -0
- sqllocks_shape_eventhubs-0.9.1/src/sqllocks_shape_eventhubs.egg-info/SOURCES.txt +21 -0
- sqllocks_shape_eventhubs-0.9.1/src/sqllocks_shape_eventhubs.egg-info/dependency_links.txt +1 -0
- sqllocks_shape_eventhubs-0.9.1/src/sqllocks_shape_eventhubs.egg-info/entry_points.txt +5 -0
- sqllocks_shape_eventhubs-0.9.1/src/sqllocks_shape_eventhubs.egg-info/requires.txt +5 -0
- sqllocks_shape_eventhubs-0.9.1/src/sqllocks_shape_eventhubs.egg-info/top_level.txt +1 -0
- sqllocks_shape_eventhubs-0.9.1/tests/test_emitter.py +139 -0
- sqllocks_shape_eventhubs-0.9.1/tests/test_emitter_emulator.py +102 -0
- sqllocks_shape_eventhubs-0.9.1/tests/test_emitter_sizes.py +19 -0
- sqllocks_shape_eventhubs-0.9.1/tests/test_emulator.py +248 -0
- sqllocks_shape_eventhubs-0.9.1/tests/test_live.py +46 -0
- sqllocks_shape_eventhubs-0.9.1/tests/test_skeleton.py +9 -0
- sqllocks_shape_eventhubs-0.9.1/tests/test_source.py +277 -0
- sqllocks_shape_eventhubs-0.9.1/tests/test_source_bounds.py +56 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-2026 SQLLocks (Jonathan Stewart)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sqllocks-shape-eventhubs
|
|
3
|
+
Version: 0.9.1
|
|
4
|
+
Summary: Shape plugin: Azure Event Hubs stream source and event emitter
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/sqllocks/shape
|
|
7
|
+
Project-URL: Repository, https://github.com/sqllocks/shape
|
|
8
|
+
Project-URL: Issues, https://github.com/sqllocks/shape/issues
|
|
9
|
+
Project-URL: Documentation, https://github.com/sqllocks/shape/tree/main/plugins/shape-eventhubs
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Topic :: Database
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: sqllocks-shape==0.9.1
|
|
22
|
+
Requires-Dist: azure-eventhub<6,>=5.12
|
|
23
|
+
Provides-Extra: entra
|
|
24
|
+
Requires-Dist: azure-identity>=1.16.1; extra == "entra"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# sqllocks-shape-eventhubs
|
|
28
|
+
|
|
29
|
+
Shape plugin: an Azure Event Hubs stream source (`shape.stream_sources`, scheme `eventhubs://`).
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
pip install sqllocks-shape-eventhubs # or: pip install 'sqllocks-shape[eventhubs]'
|
|
33
|
+
export SHAPE_EVENTHUBS_CONNECTION_STRING='Endpoint=sb://...'
|
|
34
|
+
shape stream-profile eventhubs://contoso.servicebus.windows.net/telemetry -o telemetry.json
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`eventhubs://NAMESPACE/HUB[?consumer_group=NAME]` reads one event hub as Arrow micro-batches.
|
|
38
|
+
Connect with a connection string (the `connection_string` option or
|
|
39
|
+
`SHAPE_EVENTHUBS_CONNECTION_STRING`; the hub name comes from the URI) or, with the `entra` extra
|
|
40
|
+
(`pip install 'sqllocks-shape-eventhubs[entra]'`), with Microsoft Entra sign-in. Event bodies are
|
|
41
|
+
JSON objects; their fields become columns, and `_shape_event_time` carries the event time (the
|
|
42
|
+
body's `_shape_event_time`, or the enqueued time). Shape keeps its own position: each partition
|
|
43
|
+
is read from an explicit sequence number, nothing is checkpointed in Azure Blob Storage, and a
|
|
44
|
+
`StreamOffset` is `{partition id: next sequence number}`.
|
|
45
|
+
|
|
46
|
+
Options, offsets, delivery guarantees and the checkpoint format are described in
|
|
47
|
+
`docs/plugins/streaming.md`.
|
|
48
|
+
|
|
49
|
+
## Emitting events: `eventhubs://`
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
export SHAPE_EVENTHUBS_CONNECTION_STRING='Endpoint=sb://...'
|
|
53
|
+
shape emit retail --realtime --rate 2000 --sink eventhubs://my-namespace/my-hub
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`shape.emitters` `eventhubs`: one message per event (body = the event JSON; content type
|
|
57
|
+
`application/json`, or `application/cloudevents+json` with `--envelope cloudevents`), the
|
|
58
|
+
idempotency key `<table>/<seq>` as the property `shape_key` (plus `shape_table`, `shape_seq`).
|
|
59
|
+
Events are packed into service batches by size, one table per batch, with the table as the
|
|
60
|
+
partition key (`partition_key="none"` to let the service spread them). `emit` returns after the
|
|
61
|
+
service accepted every batch; a throttled service (`server-busy`) is waited for, any other send
|
|
62
|
+
failure is retried by the runtime. Event Hubs does not deduplicate: keep the first message of each
|
|
63
|
+
`shape_key`. See `docs/EMIT.md`.
|
|
64
|
+
|
|
65
|
+
Tests: contract tests run on every PR against an in-memory hub
|
|
66
|
+
(`shape_eventhubs.testing.FakeHub`, `FakeProducerHub`; the emitter contract is
|
|
67
|
+
`shape.streaming.emit.contract`); `pytest -m emulator plugins/shape-eventhubs/tests` runs the
|
|
68
|
+
end-to-end tests against the Event Hubs emulator (`docker compose -f ci/emulators/docker-compose.yml
|
|
69
|
+
up -d --wait azurite eventhubs`; amd64 only), nightly in CI. Against live Azure resources, the
|
|
70
|
+
`live` marker runs `plugins/shape-eventhubs/tests/test_live.py` with the owner's `EVENTHUBS_*`
|
|
71
|
+
secrets (`EVENTHUBS_CONNECTION_STRING`, `EVENTHUBS_HUB`, optionally `EVENTHUBS_GROUP`; plan section
|
|
72
|
+
9, O-03); the nightly job runs it only where they exist.
|
|
73
|
+
|
|
74
|
+
Its version always equals core's (`sqllocks-shape`), and it is released together with core.
|
|
75
|
+
How plugins are written: `docs/plugins/authoring.md` in the repository.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# sqllocks-shape-eventhubs
|
|
2
|
+
|
|
3
|
+
Shape plugin: an Azure Event Hubs stream source (`shape.stream_sources`, scheme `eventhubs://`).
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
pip install sqllocks-shape-eventhubs # or: pip install 'sqllocks-shape[eventhubs]'
|
|
7
|
+
export SHAPE_EVENTHUBS_CONNECTION_STRING='Endpoint=sb://...'
|
|
8
|
+
shape stream-profile eventhubs://contoso.servicebus.windows.net/telemetry -o telemetry.json
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`eventhubs://NAMESPACE/HUB[?consumer_group=NAME]` reads one event hub as Arrow micro-batches.
|
|
12
|
+
Connect with a connection string (the `connection_string` option or
|
|
13
|
+
`SHAPE_EVENTHUBS_CONNECTION_STRING`; the hub name comes from the URI) or, with the `entra` extra
|
|
14
|
+
(`pip install 'sqllocks-shape-eventhubs[entra]'`), with Microsoft Entra sign-in. Event bodies are
|
|
15
|
+
JSON objects; their fields become columns, and `_shape_event_time` carries the event time (the
|
|
16
|
+
body's `_shape_event_time`, or the enqueued time). Shape keeps its own position: each partition
|
|
17
|
+
is read from an explicit sequence number, nothing is checkpointed in Azure Blob Storage, and a
|
|
18
|
+
`StreamOffset` is `{partition id: next sequence number}`.
|
|
19
|
+
|
|
20
|
+
Options, offsets, delivery guarantees and the checkpoint format are described in
|
|
21
|
+
`docs/plugins/streaming.md`.
|
|
22
|
+
|
|
23
|
+
## Emitting events: `eventhubs://`
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
export SHAPE_EVENTHUBS_CONNECTION_STRING='Endpoint=sb://...'
|
|
27
|
+
shape emit retail --realtime --rate 2000 --sink eventhubs://my-namespace/my-hub
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
`shape.emitters` `eventhubs`: one message per event (body = the event JSON; content type
|
|
31
|
+
`application/json`, or `application/cloudevents+json` with `--envelope cloudevents`), the
|
|
32
|
+
idempotency key `<table>/<seq>` as the property `shape_key` (plus `shape_table`, `shape_seq`).
|
|
33
|
+
Events are packed into service batches by size, one table per batch, with the table as the
|
|
34
|
+
partition key (`partition_key="none"` to let the service spread them). `emit` returns after the
|
|
35
|
+
service accepted every batch; a throttled service (`server-busy`) is waited for, any other send
|
|
36
|
+
failure is retried by the runtime. Event Hubs does not deduplicate: keep the first message of each
|
|
37
|
+
`shape_key`. See `docs/EMIT.md`.
|
|
38
|
+
|
|
39
|
+
Tests: contract tests run on every PR against an in-memory hub
|
|
40
|
+
(`shape_eventhubs.testing.FakeHub`, `FakeProducerHub`; the emitter contract is
|
|
41
|
+
`shape.streaming.emit.contract`); `pytest -m emulator plugins/shape-eventhubs/tests` runs the
|
|
42
|
+
end-to-end tests against the Event Hubs emulator (`docker compose -f ci/emulators/docker-compose.yml
|
|
43
|
+
up -d --wait azurite eventhubs`; amd64 only), nightly in CI. Against live Azure resources, the
|
|
44
|
+
`live` marker runs `plugins/shape-eventhubs/tests/test_live.py` with the owner's `EVENTHUBS_*`
|
|
45
|
+
secrets (`EVENTHUBS_CONNECTION_STRING`, `EVENTHUBS_HUB`, optionally `EVENTHUBS_GROUP`; plan section
|
|
46
|
+
9, O-03); the nightly job runs it only where they exist.
|
|
47
|
+
|
|
48
|
+
Its version always equals core's (`sqllocks-shape`), and it is released together with core.
|
|
49
|
+
How plugins are written: `docs/plugins/authoring.md` in the repository.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sqllocks-shape-eventhubs"
|
|
7
|
+
# Lockstep with core (T-09): scripts/check_plugin_skeletons.py fails when this drifts.
|
|
8
|
+
version = "0.9.1"
|
|
9
|
+
description = "Shape plugin: Azure Event Hubs stream source and event emitter"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
17
|
+
"Programming Language :: Python :: 3.11",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Programming Language :: Python :: 3.14",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Topic :: Database",
|
|
23
|
+
]
|
|
24
|
+
dependencies = ["sqllocks-shape==0.9.1", "azure-eventhub>=5.12,<6"]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/sqllocks/shape"
|
|
28
|
+
Repository = "https://github.com/sqllocks/shape"
|
|
29
|
+
Issues = "https://github.com/sqllocks/shape/issues"
|
|
30
|
+
Documentation = "https://github.com/sqllocks/shape/tree/main/plugins/shape-eventhubs"
|
|
31
|
+
|
|
32
|
+
[project.optional-dependencies]
|
|
33
|
+
# Microsoft Entra sign-in instead of a connection string.
|
|
34
|
+
entra = ["azure-identity>=1.16.1"]
|
|
35
|
+
|
|
36
|
+
[project.entry-points."shape.stream_sources"]
|
|
37
|
+
eventhubs = "shape_eventhubs:EventHubsStreamSource"
|
|
38
|
+
|
|
39
|
+
[project.entry-points."shape.emitters"]
|
|
40
|
+
eventhubs = "shape_eventhubs:EventHubsEmitter"
|
|
41
|
+
|
|
42
|
+
[tool.setuptools.packages.find]
|
|
43
|
+
where = ["src"]
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Shape plugin: Azure Event Hubs.
|
|
2
|
+
|
|
3
|
+
* ``shape.stream_sources``: ``eventhubs`` reads an event hub
|
|
4
|
+
(``eventhubs://<namespace>/<hub>``) as Arrow micro-batches with ``{partition: next sequence
|
|
5
|
+
number}`` offsets, for ``shape stream-profile``.
|
|
6
|
+
|
|
7
|
+
* ``shape.emitters``: ``eventhubs`` sends events to an event hub, each carrying the idempotency
|
|
8
|
+
key ``<table>/<seq>`` as the message property ``shape_key``, for ``shape emit``.
|
|
9
|
+
|
|
10
|
+
``azure-eventhub`` loads only when a read or a send starts.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from .emitter import EventHubsEmitter
|
|
14
|
+
from .source import EventHubsStreamSource
|
|
15
|
+
|
|
16
|
+
SHAPE_API = "1.0"
|
|
17
|
+
|
|
18
|
+
__all__ = ["SHAPE_API", "EventHubsEmitter", "EventHubsStreamSource"]
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""The ``eventhubs://`` emitter (P5-02).
|
|
2
|
+
|
|
3
|
+
``eventhubs://<namespace>/<hub>`` sends each event as one Event Hubs message: the body is the
|
|
4
|
+
event's JSON (flat, or the CloudEvents envelope), the **idempotency key** ``<table>/<seq>`` is the
|
|
5
|
+
message property ``shape_key`` (with ``shape_table`` and ``shape_seq``), and the content type is
|
|
6
|
+
``application/json`` (``application/cloudevents+json`` for the envelope). Event Hubs does not
|
|
7
|
+
deduplicate: a consumer keeps the first message of each ``shape_key``.
|
|
8
|
+
|
|
9
|
+
Delivery is at-least-once. ``emit`` returns after the service has accepted every batch it sent
|
|
10
|
+
(``send_batch`` returns on the acknowledgement); a failed send raises ``ConnectionError``, which
|
|
11
|
+
the runtime retries, so a repeated message is possible and a lost one is not. A throttled service
|
|
12
|
+
(an ``EventHubError`` saying ``server-busy``) is waited for inside ``emit`` with a growing pause,
|
|
13
|
+
so the generator, not the event hub, absorbs the slowdown.
|
|
14
|
+
|
|
15
|
+
Messages are packed into service batches by size. By default a batch carries one table, sent with
|
|
16
|
+
that table as its *partition key*, so a table keeps its order on one partition; ``partition_key``
|
|
17
|
+
``"none"`` lets the service spread them.
|
|
18
|
+
|
|
19
|
+
Options of :meth:`EventHubsEmitter.emit`:
|
|
20
|
+
|
|
21
|
+
``envelope`` ``"flat"`` (default) or ``"cloudevents"``.
|
|
22
|
+
``connection_string`` a connection string; otherwise ``SHAPE_EVENTHUBS_CONNECTION_STRING``;
|
|
23
|
+
otherwise Microsoft Entra sign-in (``azure-identity``) to the namespace in
|
|
24
|
+
the URI.
|
|
25
|
+
``credential`` an ``azure-identity`` credential to use instead.
|
|
26
|
+
``partition_key`` ``"table"`` (default) or ``"none"``.
|
|
27
|
+
``busy_retries`` how many times a throttled send is repeated before it fails (default 6).
|
|
28
|
+
``resuming`` accepted and ignored.
|
|
29
|
+
|
|
30
|
+
``azure-eventhub`` is imported when the first message is sent, never at plugin load.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import os
|
|
36
|
+
import time
|
|
37
|
+
from collections.abc import Callable, Iterable, Iterator
|
|
38
|
+
from typing import Any, NamedTuple
|
|
39
|
+
from urllib.parse import unquote, urlsplit
|
|
40
|
+
|
|
41
|
+
import pyarrow as pa
|
|
42
|
+
|
|
43
|
+
from shape.errors import ShapeError
|
|
44
|
+
from shape.streaming.emit.formats import ENVELOPES, EncodedEvent, encode_events
|
|
45
|
+
|
|
46
|
+
from .source import ENV_CONNECTION_STRING
|
|
47
|
+
|
|
48
|
+
PROP_KEY = "shape_key"
|
|
49
|
+
PROP_TABLE = "shape_table"
|
|
50
|
+
PROP_SYNTHETIC = "shape_synthetic"
|
|
51
|
+
PROP_SEQ = "shape_seq"
|
|
52
|
+
_BUSY_PAUSE = 0.5 # seconds; doubles with each repeat
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class HubTarget(NamedTuple):
|
|
56
|
+
namespace: str
|
|
57
|
+
hub: str | None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def parse_uri(uri: str) -> HubTarget:
|
|
61
|
+
"""The namespace and event hub of an ``eventhubs://`` URI."""
|
|
62
|
+
parts = urlsplit(uri)
|
|
63
|
+
if parts.scheme != "eventhubs" or not parts.netloc:
|
|
64
|
+
raise ShapeError(f"not an eventhubs URI: {uri!r} (eventhubs://<namespace>/<hub>)")
|
|
65
|
+
hub = unquote(parts.path.lstrip("/"))
|
|
66
|
+
if not hub or "/" in hub:
|
|
67
|
+
raise ShapeError(f"the eventhubs URI needs one event hub name: {uri!r}")
|
|
68
|
+
return HubTarget(parts.netloc, hub)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _sdk_producer(target: HubTarget, options: dict[str, Any], env: str) -> Any:
|
|
72
|
+
try:
|
|
73
|
+
from azure.eventhub import EventHubProducerClient
|
|
74
|
+
except ImportError as exc:
|
|
75
|
+
raise ShapeError(
|
|
76
|
+
"emitting to Event Hubs needs the azure-eventhub package "
|
|
77
|
+
"(pip install sqllocks-shape-eventhubs)"
|
|
78
|
+
) from exc
|
|
79
|
+
conn = options.get("connection_string") or os.environ.get(env)
|
|
80
|
+
if conn:
|
|
81
|
+
return EventHubProducerClient.from_connection_string(conn, eventhub_name=target.hub)
|
|
82
|
+
credential = options.get("credential")
|
|
83
|
+
if credential is None:
|
|
84
|
+
try:
|
|
85
|
+
from azure.identity import DefaultAzureCredential
|
|
86
|
+
except ImportError as exc:
|
|
87
|
+
raise ShapeError(
|
|
88
|
+
f"give a connection string (the connection_string option or {env}) or install "
|
|
89
|
+
"azure-identity for Microsoft Entra sign-in"
|
|
90
|
+
) from exc
|
|
91
|
+
credential = DefaultAzureCredential()
|
|
92
|
+
return EventHubProducerClient(
|
|
93
|
+
fully_qualified_namespace=target.namespace,
|
|
94
|
+
eventhub_name=target.hub,
|
|
95
|
+
credential=credential,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _is_busy(exc: BaseException) -> bool:
|
|
100
|
+
text = str(exc).lower()
|
|
101
|
+
return "server-busy" in text or "serverbusy" in text or "throttl" in text
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _groups(events: list[EncodedEvent], by_table: bool) -> Iterator[tuple[str | None, list]]:
|
|
105
|
+
"""Consecutive events of one table (or all of them), each group sent with one partition key."""
|
|
106
|
+
if not by_table:
|
|
107
|
+
yield None, events
|
|
108
|
+
return
|
|
109
|
+
start = 0
|
|
110
|
+
for i in range(1, len(events) + 1):
|
|
111
|
+
if i == len(events) or events[i].table != events[start].table:
|
|
112
|
+
yield events[start].table, events[start:i]
|
|
113
|
+
start = i
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class EventHubsEmitter:
|
|
117
|
+
"""Events to an event hub, each carrying the idempotency key as a message property.
|
|
118
|
+
|
|
119
|
+
``client_factory(target, options)`` is for tests: it stands in for building an
|
|
120
|
+
``azure.eventhub.EventHubProducerClient``.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
name = "eventhubs"
|
|
124
|
+
accepts_poison = True # one JSON text per message: a cut-off body is a poison message
|
|
125
|
+
supports_synthetic = True # the `synthetic` option marks every message with a header
|
|
126
|
+
schemes = ("eventhubs",)
|
|
127
|
+
env_connection_string = ENV_CONNECTION_STRING
|
|
128
|
+
|
|
129
|
+
def __init__(
|
|
130
|
+
self,
|
|
131
|
+
client_factory: Callable[[HubTarget, dict[str, Any]], Any] | None = None,
|
|
132
|
+
*,
|
|
133
|
+
busy_pause: float = _BUSY_PAUSE,
|
|
134
|
+
) -> None:
|
|
135
|
+
self._client_factory = client_factory
|
|
136
|
+
self._busy_pause = busy_pause
|
|
137
|
+
self._clients: dict[tuple[str, str | None], Any] = {}
|
|
138
|
+
|
|
139
|
+
def parse(self, uri: str) -> HubTarget:
|
|
140
|
+
return parse_uri(uri)
|
|
141
|
+
|
|
142
|
+
def _client(self, target: HubTarget, options: dict[str, Any]) -> Any:
|
|
143
|
+
client = self._clients.get(target)
|
|
144
|
+
if client is None:
|
|
145
|
+
if self._client_factory is not None:
|
|
146
|
+
client = self._client_factory(target, options)
|
|
147
|
+
else:
|
|
148
|
+
client = _sdk_producer(target, options, self.env_connection_string)
|
|
149
|
+
self._clients[target] = client
|
|
150
|
+
return client
|
|
151
|
+
|
|
152
|
+
def emit(
|
|
153
|
+
self,
|
|
154
|
+
uri: str,
|
|
155
|
+
batches: Iterable[pa.RecordBatch],
|
|
156
|
+
*,
|
|
157
|
+
envelope: str = "flat",
|
|
158
|
+
resuming: bool = False,
|
|
159
|
+
partition_key: str = "table",
|
|
160
|
+
busy_retries: int = 6,
|
|
161
|
+
synthetic: bool = False,
|
|
162
|
+
**options: Any,
|
|
163
|
+
) -> int:
|
|
164
|
+
"""Send every batch; return the number of events, after the service accepted them."""
|
|
165
|
+
connect = {k: options.pop(k) for k in ("connection_string", "credential") if k in options}
|
|
166
|
+
if options:
|
|
167
|
+
raise ShapeError(f"unknown {self.name} emitter options: {sorted(options)}")
|
|
168
|
+
if envelope not in ENVELOPES:
|
|
169
|
+
raise ShapeError(f"unknown envelope {envelope!r}; choose from {', '.join(ENVELOPES)}")
|
|
170
|
+
if partition_key not in ("table", "none"):
|
|
171
|
+
raise ShapeError("partition_key must be 'table' or 'none'")
|
|
172
|
+
target = self.parse(uri)
|
|
173
|
+
client = self._client(target, connect)
|
|
174
|
+
content_type = "application/json" if envelope == "flat" else "application/cloudevents+json"
|
|
175
|
+
sent = 0
|
|
176
|
+
for batch in batches:
|
|
177
|
+
events = encode_events(batch, envelope)
|
|
178
|
+
for key, group in _groups(events, partition_key == "table"):
|
|
179
|
+
self._send_group(client, key, group, content_type, busy_retries, synthetic)
|
|
180
|
+
sent += len(events)
|
|
181
|
+
return sent
|
|
182
|
+
|
|
183
|
+
# ---------------------------------------------------------------- sending
|
|
184
|
+
def _send_group(
|
|
185
|
+
self,
|
|
186
|
+
client: Any,
|
|
187
|
+
key: str | None,
|
|
188
|
+
group: list[EncodedEvent],
|
|
189
|
+
content_type: str,
|
|
190
|
+
busy: int,
|
|
191
|
+
synthetic: bool = False,
|
|
192
|
+
) -> None:
|
|
193
|
+
from azure.eventhub import EventData
|
|
194
|
+
|
|
195
|
+
def new_batch() -> Any:
|
|
196
|
+
return client.create_batch(partition_key=key) if key else client.create_batch()
|
|
197
|
+
|
|
198
|
+
def message(ev: EncodedEvent) -> Any:
|
|
199
|
+
data = EventData(ev.body)
|
|
200
|
+
data.content_type = content_type
|
|
201
|
+
data.properties = {PROP_KEY: ev.key, PROP_TABLE: ev.table, PROP_SEQ: ev.seq}
|
|
202
|
+
if synthetic:
|
|
203
|
+
data.properties[PROP_SYNTHETIC] = True
|
|
204
|
+
return data
|
|
205
|
+
|
|
206
|
+
def too_large(ev: EncodedEvent) -> ShapeError:
|
|
207
|
+
return ShapeError(
|
|
208
|
+
f"event {ev.key} ({len(ev.body)} bytes) is larger than an event hub batch; "
|
|
209
|
+
"make the rows smaller or emit to a hub tier with a larger message size"
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
current = new_batch()
|
|
213
|
+
count = 0
|
|
214
|
+
for ev in group:
|
|
215
|
+
data = message(ev)
|
|
216
|
+
try:
|
|
217
|
+
current.add(data)
|
|
218
|
+
except ValueError:
|
|
219
|
+
if count == 0:
|
|
220
|
+
raise too_large(ev) from None
|
|
221
|
+
self._send(client, current, busy)
|
|
222
|
+
current = new_batch()
|
|
223
|
+
try:
|
|
224
|
+
current.add(data)
|
|
225
|
+
except ValueError:
|
|
226
|
+
raise too_large(ev) from None
|
|
227
|
+
count = 0
|
|
228
|
+
count += 1
|
|
229
|
+
if count:
|
|
230
|
+
self._send(client, current, busy)
|
|
231
|
+
|
|
232
|
+
def _send(self, client: Any, batch: Any, busy: int) -> None:
|
|
233
|
+
from azure.eventhub.exceptions import AuthenticationError, EventDataError, EventHubError
|
|
234
|
+
|
|
235
|
+
pause = self._busy_pause
|
|
236
|
+
attempt = 0
|
|
237
|
+
while True:
|
|
238
|
+
try:
|
|
239
|
+
client.send_batch(batch)
|
|
240
|
+
return
|
|
241
|
+
except AuthenticationError as exc:
|
|
242
|
+
raise ShapeError(f"{self.name}: not authorised: {exc}") from exc
|
|
243
|
+
except EventDataError as exc:
|
|
244
|
+
raise ShapeError(f"{self.name}: the service refused the data: {exc}") from exc
|
|
245
|
+
except EventHubError as exc:
|
|
246
|
+
if not _is_busy(exc):
|
|
247
|
+
raise ConnectionError(f"{self.name}: send failed: {exc}") from exc
|
|
248
|
+
# Throttled: back off and repeat; the stall reaches the generator as backpressure.
|
|
249
|
+
attempt += 1
|
|
250
|
+
if attempt > busy:
|
|
251
|
+
raise ConnectionError(f"{self.name}: the service stayed busy: {exc}") from exc
|
|
252
|
+
time.sleep(pause)
|
|
253
|
+
pause *= 2
|
|
254
|
+
|
|
255
|
+
def flush(self) -> None:
|
|
256
|
+
return None # every emit() returns after acknowledgement
|
|
257
|
+
|
|
258
|
+
def close(self) -> None:
|
|
259
|
+
clients, self._clients = list(self._clients.values()), {}
|
|
260
|
+
for client in clients:
|
|
261
|
+
client.close()
|