industream-eventhub-client 1.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.
- industream_eventhub_client-1.0.0/.gitignore +59 -0
- industream_eventhub_client-1.0.0/PKG-INFO +531 -0
- industream_eventhub_client-1.0.0/README.md +514 -0
- industream_eventhub_client-1.0.0/pyproject.toml +64 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/__init__.py +105 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/backend_error_reason.py +17 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/backend_problem.py +83 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/backend_reply.py +56 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/backend_request.py +38 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/backend_request_kind.py +56 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/__init__.py +0 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/acknowledgement.py +20 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/actor.py +20 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/actor_proof.py +13 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/actor_type.py +11 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/cloud_event.py +71 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_category.py +11 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_change.py +12 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_comment.py +20 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_contract.py +191 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_decode_error.py +4 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_decoder.py +446 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_end.py +20 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_factory.py +240 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_json.py +54 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_model.py +81 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_modification.py +16 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_nats_subject.py +87 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_severity.py +15 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_sop.py +89 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_state.py +17 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/event_state_decoder.py +159 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/int32.py +8 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/latest_event_version.py +18 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/latest_event_version_decoder.py +63 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/modified_event.py +14 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/received_event.py +80 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/models/timestamp.py +60 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/modifying/__init__.py +0 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/modifying/command_actor.py +108 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/modifying/command_reply.py +34 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/modifying/event_modification_error.py +24 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/modifying/event_modifier.py +93 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/publishing/__init__.py +0 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/publishing/event_publish_error.py +4 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/publishing/event_publisher.py +74 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/publishing/published_event.py +18 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/py.typed +0 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/__init__.py +0 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/event_filter_request.py +99 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/event_history_filter.py +79 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/event_history_page.py +17 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/event_history_reader.py +87 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/event_query_error.py +24 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/event_selector.py +15 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/event_statistics.py +20 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/event_statistics_group.py +43 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/event_window.py +12 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/history_reply.py +38 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/history_request.py +19 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/statistics_dimension.py +36 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/statistics_order.py +12 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/statistics_reply.py +144 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/querying/statistics_request.py +33 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/reply_json.py +87 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/subscribing/__init__.py +0 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/subscribing/consume_options.py +25 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/subscribing/event_subscriber.py +312 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/subscribing/handler_failure.py +22 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/subscribing/invalid_message.py +22 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/subscribing/missed_events.py +15 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/subscribing/ordered_consumer.py +176 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/subscribing/read_options.py +21 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/subscribing/read_start.py +38 -0
- industream_eventhub_client-1.0.0/src/industream/eventhub/client/subscribing/subscription_start.py +13 -0
- industream_eventhub_client-1.0.0/tests/__init__.py +0 -0
- industream_eventhub_client-1.0.0/tests/e2e/__init__.py +0 -0
- industream_eventhub_client-1.0.0/tests/e2e/conftest.py +30 -0
- industream_eventhub_client-1.0.0/tests/e2e/deployment_nats_image.py +19 -0
- industream_eventhub_client-1.0.0/tests/e2e/event_queue.py +67 -0
- industream_eventhub_client-1.0.0/tests/e2e/modifying/__init__.py +0 -0
- industream_eventhub_client-1.0.0/tests/e2e/modifying/command_cases.py +75 -0
- industream_eventhub_client-1.0.0/tests/e2e/modifying/fake_backend.py +65 -0
- industream_eventhub_client-1.0.0/tests/e2e/modifying/test_command_actor.py +38 -0
- industream_eventhub_client-1.0.0/tests/e2e/modifying/test_event_modifier.py +228 -0
- industream_eventhub_client-1.0.0/tests/e2e/modifying/test_event_modifier_replies.py +58 -0
- industream_eventhub_client-1.0.0/tests/e2e/modifying/test_event_modifier_rights.py +25 -0
- industream_eventhub_client-1.0.0/tests/e2e/nats_server.py +166 -0
- industream_eventhub_client-1.0.0/tests/e2e/publishing/__init__.py +0 -0
- industream_eventhub_client-1.0.0/tests/e2e/publishing/test_event_publisher.py +163 -0
- industream_eventhub_client-1.0.0/tests/e2e/publishing/test_event_publisher_refused.py +38 -0
- industream_eventhub_client-1.0.0/tests/e2e/publishing/test_event_publisher_rights.py +36 -0
- industream_eventhub_client-1.0.0/tests/e2e/publishing/test_event_publisher_without_stream.py +55 -0
- industream_eventhub_client-1.0.0/tests/e2e/querying/__init__.py +0 -0
- industream_eventhub_client-1.0.0/tests/e2e/querying/query_cases.py +175 -0
- industream_eventhub_client-1.0.0/tests/e2e/querying/test_event_history_reader.py +186 -0
- industream_eventhub_client-1.0.0/tests/e2e/querying/test_event_history_reader_rights.py +22 -0
- industream_eventhub_client-1.0.0/tests/e2e/subscribing/__init__.py +0 -0
- industream_eventhub_client-1.0.0/tests/e2e/subscribing/test_event_subscriber.py +1067 -0
- industream_eventhub_client-1.0.0/tests/unit/__init__.py +0 -0
- industream_eventhub_client-1.0.0/tests/unit/contract_cases/__init__.py +0 -0
- industream_eventhub_client-1.0.0/tests/unit/contract_cases/contract_case_file.py +114 -0
- industream_eventhub_client-1.0.0/tests/unit/contract_cases/state_conversions.py +37 -0
- industream_eventhub_client-1.0.0/tests/unit/contract_cases/test_decoding_contract.py +83 -0
- industream_eventhub_client-1.0.0/tests/unit/contract_cases/test_interoperability.py +89 -0
- industream_eventhub_client-1.0.0/tests/unit/contract_cases/test_latest_version_contract.py +44 -0
- industream_eventhub_client-1.0.0/tests/unit/contract_cases/test_model_contract.py +141 -0
- industream_eventhub_client-1.0.0/tests/unit/contract_cases/test_nats_subject_contract.py +31 -0
- industream_eventhub_client-1.0.0/tests/unit/contract_cases/test_schema_contract.py +159 -0
- industream_eventhub_client-1.0.0/tests/unit/contract_cases/test_sop_contract.py +19 -0
- industream_eventhub_client-1.0.0/tests/unit/contract_cases/test_state_contract.py +38 -0
- industream_eventhub_client-1.0.0/tests/unit/models/__init__.py +0 -0
- industream_eventhub_client-1.0.0/tests/unit/models/test_event_contract.py +8 -0
- industream_eventhub_client-1.0.0/tests/unit/models/test_event_decoder.py +138 -0
- industream_eventhub_client-1.0.0/tests/unit/models/test_event_factory.py +190 -0
- industream_eventhub_client-1.0.0/tests/unit/models/test_event_nats_subject.py +6 -0
- industream_eventhub_client-1.0.0/tests/unit/publishing/__init__.py +0 -0
- industream_eventhub_client-1.0.0/tests/unit/publishing/test_event_publisher.py +23 -0
- industream_eventhub_client-1.0.0/tests/unit/test_scenario_catalogue.py +105 -0
- industream_eventhub_client-1.0.0/uv.lock +710 -0
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# --- .NET ---
|
|
2
|
+
[Bb]in/
|
|
3
|
+
[Oo]bj/
|
|
4
|
+
*.user
|
|
5
|
+
*.suo
|
|
6
|
+
*.rsuser
|
|
7
|
+
.vs/
|
|
8
|
+
[Tt]est[Rr]esult*/
|
|
9
|
+
*.trx
|
|
10
|
+
*.nupkg
|
|
11
|
+
*.snupkg
|
|
12
|
+
coverage*.json
|
|
13
|
+
coverage*.xml
|
|
14
|
+
*.binlog
|
|
15
|
+
|
|
16
|
+
# --- JavaScript ---
|
|
17
|
+
node_modules/
|
|
18
|
+
dist/
|
|
19
|
+
.vite/
|
|
20
|
+
vite.config.ts.timestamp-*
|
|
21
|
+
*.tsbuildinfo
|
|
22
|
+
npm-debug.log*
|
|
23
|
+
pnpm-debug.log*
|
|
24
|
+
|
|
25
|
+
# --- Python ---
|
|
26
|
+
__pycache__/
|
|
27
|
+
*.py[cod]
|
|
28
|
+
*.egg-info/
|
|
29
|
+
.venv/
|
|
30
|
+
venv/
|
|
31
|
+
build/
|
|
32
|
+
.pytest_cache/
|
|
33
|
+
.mypy_cache/
|
|
34
|
+
.ruff_cache/
|
|
35
|
+
.coverage
|
|
36
|
+
htmlcov/
|
|
37
|
+
.pypirc
|
|
38
|
+
|
|
39
|
+
# --- Secrets and local configuration ---
|
|
40
|
+
.env
|
|
41
|
+
.env.*
|
|
42
|
+
!.env.example
|
|
43
|
+
*.pfx
|
|
44
|
+
|
|
45
|
+
# --- IDE ---
|
|
46
|
+
.idea/
|
|
47
|
+
.vscode/*
|
|
48
|
+
!.vscode/settings.json
|
|
49
|
+
!.vscode/extensions.json
|
|
50
|
+
.history/
|
|
51
|
+
|
|
52
|
+
# --- AI tools ---
|
|
53
|
+
.claude/
|
|
54
|
+
.mcp.json
|
|
55
|
+
.superpowers/
|
|
56
|
+
|
|
57
|
+
# --- OS ---
|
|
58
|
+
.DS_Store
|
|
59
|
+
Thumbs.db
|
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: industream-eventhub-client
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: EventHub client for Python: publishes and subscribes to Industream events stored in NATS JetStream, and acknowledges and ends them through the commands of the EventHub backend.
|
|
5
|
+
Project-URL: Repository, https://github.com/industream/industream-event-hub
|
|
6
|
+
Author: Sullivan Vanet
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Keywords: cloudevents,eventhub,events,industream,jetstream,nats
|
|
9
|
+
Classifier: Framework :: AsyncIO
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Requires-Python: >=3.12
|
|
15
|
+
Requires-Dist: nats-py<3,>=2.16
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# industream-eventhub-client
|
|
19
|
+
|
|
20
|
+
Python client for EventHub: publishes and subscribes to events stored in NATS JetStream, sends the commands that
|
|
21
|
+
modify them to the EventHub backend, and reads their history from it.
|
|
22
|
+
|
|
23
|
+
It is a translation of the .NET client
|
|
24
|
+
([Industream.EventHub.Models](https://www.nuget.org/packages/Industream.EventHub.Models) and
|
|
25
|
+
[Industream.EventHub.Client](https://www.nuget.org/packages/Industream.EventHub.Client)), as close as possible: same
|
|
26
|
+
models, same names, same behaviour. Only the Python conventions change (snake_case members, UPPER_CASE constants and
|
|
27
|
+
enum members, no `Async` suffix, `Error` instead of `Exception`). Its models follow the shared schemas and its tests
|
|
28
|
+
replay the shared contract cases ([Shared/README.md](https://github.com/industream/industream-event-hub/blob/main/Shared/README.md)).
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install industream-eventhub-client
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Python 3.12 or later. The client is asynchronous (asyncio) and works on the NATS connection the application opens with
|
|
37
|
+
[nats-py](https://github.com/nats-io/nats.py).
|
|
38
|
+
|
|
39
|
+
## Building an event
|
|
40
|
+
|
|
41
|
+
What goes in the fields a publisher fills, with the thermal alarm of tuyere 12 (the rule:
|
|
42
|
+
[Event-Model.md, What goes where](https://github.com/industream/industream-event-hub/blob/main/Docs/Event-Model.md#what-goes-where)):
|
|
43
|
+
|
|
44
|
+
| Field | What goes there | Tuyere 12 |
|
|
45
|
+
|---|---|---|
|
|
46
|
+
| `name` | The **kind** of event, the same for every event of this kind: the statistics count by type | `thermalalarm`, not `thermalalarm.tuyere12` |
|
|
47
|
+
| `subject` | The **object** the event is about, inside the application (not the NATS subject) | `tuyere/12` |
|
|
48
|
+
| `attributes` | The **criteria** to filter events on, as simple values | `tuyere` = 12 |
|
|
49
|
+
| `data` | The **details**: measurements, thresholds, context. Never used to filter | `flameTemperature` = 2412 |
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from industream.eventhub.client import EventCategory, EventFactory, EventModel, EventSeverity
|
|
53
|
+
|
|
54
|
+
thermal_alarm = EventModel(
|
|
55
|
+
application="raceway", # type industream.raceway.thermalalarm
|
|
56
|
+
name="thermalalarm",
|
|
57
|
+
source="/industream/flowmaker", # optional, default: /industream/raceway
|
|
58
|
+
severity=EventSeverity.ALARM,
|
|
59
|
+
category=EventCategory.PROCESS,
|
|
60
|
+
subject="tuyere/12",
|
|
61
|
+
attributes={"tuyere": 12},
|
|
62
|
+
data={"code": "THERMAL_OUT_OF_RANGE", "flameTemperature": 2412},
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
cloud_event = EventFactory.create(thermal_alarm)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`EventFactory.create` fills in:
|
|
69
|
+
|
|
70
|
+
- `id` (UUID v7), `specversion` 1.0, `datacontenttype` `application/json`;
|
|
71
|
+
- `type` (`industream.<application>.<name>`) and `source` (`source`, or `/industream/<application>` by default);
|
|
72
|
+
- `time` in UTC, to the millisecond (now when the model has no `time`);
|
|
73
|
+
- the Severity extension (`severitytext` and `severitynumber`), `category`, and `project` (`application` unless the
|
|
74
|
+
model sets `project`);
|
|
75
|
+
- `rootevent` when the model sets `root_event_id` (secondary events, published by the EventHub backend alone: refused
|
|
76
|
+
for another application than `eventhub`);
|
|
77
|
+
- `keephistory: false` when the model sets `keep_in_history=False`: the event goes through EventHub as usual, but the
|
|
78
|
+
backend leaves it out of the database history (an ordinary event does not carry the extension);
|
|
79
|
+
- `lasting: true` when the model sets `lasting=True`: the event lasts until it is ended, like an alarm (an
|
|
80
|
+
instantaneous event does not carry the extension);
|
|
81
|
+
- the publisher attributes, keeping their type: `str`, 32-bit `int`, `bool` or `datetime` (written as a timestamp);
|
|
82
|
+
- `data.sop` when the model has a `sop`: its standard operating procedure, a dictionary language -> link
|
|
83
|
+
(`{"en": "https://intranet.example/sop/en/tuyere-overheat.pdf"}`). The data must then be a JSON object (a `dict`
|
|
84
|
+
or a dataclass) or `None`; a data that holds its own `sop` member, a key that is not an ISO 639-1 code with an
|
|
85
|
+
optional region (`fr`, `fr-FR`), or a link that is not an absolute `http` or `https` address of at most 2000
|
|
86
|
+
characters raises a `ValueError` (Docs/Event-Model.md, SOP).
|
|
87
|
+
|
|
88
|
+
`data` is any value `json` can write (`dict`, `list`, `str`, numbers…); a dataclass is written with its field names in
|
|
89
|
+
camelCase (`flame_temperature` becomes `flameTemperature`), like the typed data of the .NET client, and a `datetime`
|
|
90
|
+
(ISO 8601) or a `UUID` as a string. Another type (an `Enum`, a `Decimal`…) raises a `TypeError` when the event is
|
|
91
|
+
written, at `publish`.
|
|
92
|
+
`EventJson.encode(cloud_event)` writes the CloudEvent as structured JSON (UTF-8 bytes), as it is published.
|
|
93
|
+
|
|
94
|
+
## Invalid models
|
|
95
|
+
|
|
96
|
+
An invalid model is a programming error: `EventFactory.create` raises a `ValueError` whose message says what is wrong:
|
|
97
|
+
empty application, event or project name, unknown severity or category, empty subject, source that is not a URI
|
|
98
|
+
reference, invalid or reserved attribute name, unsupported attribute value, root event id that is not a `UUID`,
|
|
99
|
+
`time` (or `datetime` attribute) without time zone or out of the UTC range, string attribute (subject, names, project,
|
|
100
|
+
attribute value…) with a control character, a noncharacter or a lone surrogate.
|
|
101
|
+
|
|
102
|
+
`EventContract.validate_attribute_name` applies the rule of an attribute name on its own (1 to 20 lowercase letters
|
|
103
|
+
and digits, not a reserved name), for a form that checks a name before any event is built.
|
|
104
|
+
|
|
105
|
+
`EventSop.validate(sop)` applies the rule of an SOP on its own (at least one ISO 639-1 language, absolute `http` or
|
|
106
|
+
`https` links of at most 2000 characters), for a form that checks an SOP before any event is built.
|
|
107
|
+
|
|
108
|
+
## Decoding a received event
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
received_event = EventDecoder.decode(message_body) # bytes; raises EventDecodeError if invalid
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`ReceivedEvent` gives the CloudEvents fields, the severity, the category, the project, `root_event_id` (a `UUID`),
|
|
115
|
+
`keep_in_history` (`True` when `keephistory` is absent), `lasting` (`False` when `lasting` is absent), the publisher
|
|
116
|
+
attributes (read-only), `sop` (read-only, `None` when the data has none; `EventSop.url_for(sop, "fr")` gives the
|
|
117
|
+
link to open: that language, else English, else the first) and `data` (as parsed
|
|
118
|
+
JSON), plus the received `cloud_event` and, when a client read it from the stream, its `stream_sequence` and
|
|
119
|
+
`nats_subject`; a missing value is `None`. `time` is a `datetime` in UTC. The severity is read by OpenTelemetry range (`severitynumber` 13 to 16
|
|
120
|
+
is `WARN`, TRACE 1 to 4 is read as `DEBUG`), or from `severitytext` when there is no number: an event published
|
|
121
|
+
without the EventHub client may use any number of a level. Publisher attributes keep numbers and booleans typed;
|
|
122
|
+
timestamps and URIs, plain strings in JSON, come back as strings.
|
|
123
|
+
|
|
124
|
+
A message is rejected when it is not a valid CloudEvent in structured JSON (a body starting with a UTF-8 byte order
|
|
125
|
+
mark, a blank `id`, `type` or `source`, an
|
|
126
|
+
empty `subject`, a `time` that is not an RFC 3339 timestamp of a real day or has an offset beyond 14 hours, an invalid
|
|
127
|
+
`datacontenttype` or
|
|
128
|
+
`dataschema`, both `data` and `data_base64`, an extension name that is not lowercase letters and digits, a control
|
|
129
|
+
character or a noncharacter in a string attribute included),
|
|
130
|
+
has no time, severity, category or project, has a `severitynumber` that is not an integer, a `keephistory` or a `lasting`
|
|
131
|
+
that is not a boolean, a `rootevent` that is not an event id in its standard form, or an extension value outside the CloudEvents
|
|
132
|
+
type system (an object, a list, a number that is not a 32-bit integer). A `null` attribute is an absent one.
|
|
133
|
+
|
|
134
|
+
### Secondary events
|
|
135
|
+
|
|
136
|
+
When the backend acknowledges or ends an event, it publishes a **secondary event**: its `root_event_id` is the id of
|
|
137
|
+
the main event, its type `industream.eventhub.event.<change>`. A subscriber receives it like any other event, with
|
|
138
|
+
`modification` set: what changed and the full state of the main event, read from its data. `modification` is `None`
|
|
139
|
+
for every other event.
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
if received_event.modification is not None:
|
|
143
|
+
if received_event.modification.change == EventChange.ACKNOWLEDGED:
|
|
144
|
+
...
|
|
145
|
+
end = received_event.modification.state.end # the full, cumulative state
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
`change` is a string: `EventChange.ACKNOWLEDGED`, `EventChange.ENDED`, or a change added later, kept as received. A
|
|
149
|
+
secondary event whose data is not `{ change, state }` with the change of its type and a valid state is rejected
|
|
150
|
+
like any other invalid event. The main event is not in it: `root_event_id` gives its id.
|
|
151
|
+
|
|
152
|
+
## Reading the state of a modified event
|
|
153
|
+
|
|
154
|
+
`EventStateDecoder.decode(json)` reads the state the backend gives a modified event
|
|
155
|
+
([Event-Model.md §8.3](https://github.com/industream/industream-event-hub/blob/main/Docs/Event-Model.md#83-content-data)),
|
|
156
|
+
from parsed JSON: the `state` of a value of the `eventhub-latest` bucket, of a secondary event or of a command reply.
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
state = EventStateDecoder.decode(value["state"])
|
|
160
|
+
# state.acknowledgement: Acknowledgement(actor=Actor(type, id, proof), time, comment) or None
|
|
161
|
+
# state.end: EventEnd(actor, time, comment) or None
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
The values are read in kebab-case (`"hub-token"` gives `ActorProof.HUB_TOKEN`), the times as RFC 3339 times
|
|
165
|
+
(`datetime` with their offset), and a field it does not know is ignored. An invalid state raises an `EventDecodeError`
|
|
166
|
+
that names the wrong field (`'acknowledgement.actor.type' is unknown: 'robot'`).
|
|
167
|
+
|
|
168
|
+
A value of the `eventhub-latest` bucket (`EventContract.LATEST_VERSION_BUCKET`), the latest version of each modified
|
|
169
|
+
event, is read with `LatestEventVersionDecoder.decode(json)`: `event`, the main event decoded as `EventDecoder` does
|
|
170
|
+
with its `nats_subject`, and `state`. The pending secondary event the backend may keep there is ignored.
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
bucket = await connection.jetstream().key_value(EventContract.LATEST_VERSION_BUCKET)
|
|
174
|
+
entry = await bucket.get(event_id)
|
|
175
|
+
latest_version = LatestEventVersionDecoder.decode(json.loads(entry.value))
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## NATS subject
|
|
179
|
+
|
|
180
|
+
The publisher chooses the NATS subject of its events; it only has to start with `eventhub.`, the root the EventHub
|
|
181
|
+
stream captures ([why](https://github.com/industream/industream-event-hub/blob/main/Docs/Event-Model.md#72-nats-subjects)).
|
|
182
|
+
|
|
183
|
+
`subject` of the model always means the CloudEvents subject, the object the event is about (`tuyere/12`); the NATS
|
|
184
|
+
subject an event is published on is always named `nats_subject` (`publish`, `PublishedEvent`, `ReceivedEvent`,
|
|
185
|
+
`InvalidMessage`).
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
from industream.eventhub.client import EventNatsSubject
|
|
189
|
+
|
|
190
|
+
EventNatsSubject.validate("eventhub.raceway.process.alarm.thermalalarm") # raises ValueError if invalid
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
A subject is rejected when it does not start with `eventhub.`, has an empty token, contains whitespace or contains a
|
|
194
|
+
wildcard (`*`, `>`: subscriptions only). `EventNatsSubject.ALL` (`eventhub.>`) covers every EventHub NATS subject.
|
|
195
|
+
|
|
196
|
+
A subscription filter accepts wildcards as whole tokens, `>` only last:
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
EventNatsSubject.validate_filter("eventhub.*.*.alarm.>")
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
## Publishing an event
|
|
203
|
+
|
|
204
|
+
```python
|
|
205
|
+
import nats
|
|
206
|
+
|
|
207
|
+
from industream.eventhub.client import EventFactory, EventPublisher
|
|
208
|
+
|
|
209
|
+
connection = await nats.connect("nats://localhost:4222")
|
|
210
|
+
publisher = EventPublisher(connection)
|
|
211
|
+
|
|
212
|
+
cloud_event = EventFactory.create(thermal_alarm)
|
|
213
|
+
published = await publisher.publish(cloud_event, "eventhub.raceway.process.alarm.thermalalarm")
|
|
214
|
+
# published.event_id, published.nats_subject, published.stream_sequence, published.duplicate
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
The application opens the NATS connection itself, with nats-py.
|
|
218
|
+
|
|
219
|
+
`publish` takes a CloudEvent built with `EventFactory`, then:
|
|
220
|
+
|
|
221
|
+
- checks the NATS subject (`EventNatsSubject.validate`), and that the event is at most 900 KB of JSON
|
|
222
|
+
(`EventContract.MAX_EVENT_SIZE`): a larger one raises a `ValueError` without calling NATS;
|
|
223
|
+
- publishes the CloudEvent as structured JSON, with the `Content-Type: application/cloudevents+json` header and the
|
|
224
|
+
`Nats-Msg-Id` header set to the event `id`: JetStream ignores the same event published again within its duplicate
|
|
225
|
+
window, and `duplicate` is then `True`;
|
|
226
|
+
- waits for the JetStream acknowledgement. When no stream stores the subject, when the NATS rights of the connection
|
|
227
|
+
refuse the NATS subject (NATS drops the event without answering: nothing is stored), when the acknowledgement does not
|
|
228
|
+
come in time (NATS slow or unreachable: the event may be stored), or when JetStream refuses the event, it raises an
|
|
229
|
+
`EventPublishError`. As in the .NET client, one message gives the first three causes. Connection errors (a closed
|
|
230
|
+
connection…) come as the nats-py errors.
|
|
231
|
+
|
|
232
|
+
To publish an event again after an error, publish **the same CloudEvent**: it keeps its `id`, so JetStream stores it
|
|
233
|
+
only once. Building it again from the `EventModel` would give it a new `id`, and the event would be stored twice.
|
|
234
|
+
|
|
235
|
+
Never change the `id` or the `time` of a CloudEvent, and never give its `id` to another event: EventHub finds an
|
|
236
|
+
event by its `id` alone, and a reused `id` breaks the history and the commands of that event
|
|
237
|
+
([Event-Model.md](https://github.com/industream/industream-event-hub/blob/main/Docs/Event-Model.md#id) explains why).
|
|
238
|
+
|
|
239
|
+
## Subscribing
|
|
240
|
+
|
|
241
|
+
```python
|
|
242
|
+
import asyncio
|
|
243
|
+
import logging
|
|
244
|
+
|
|
245
|
+
from industream.eventhub.client import ConsumeOptions, EventSubscriber, HandlerFailure, ReceivedEvent
|
|
246
|
+
|
|
247
|
+
subscriber = EventSubscriber(connection)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
async def handle(received_event: ReceivedEvent) -> None:
|
|
251
|
+
# react to received_event (decoded by EventDecoder)
|
|
252
|
+
print(received_event.id)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def report(failure: HandlerFailure) -> None:
|
|
256
|
+
logging.error("Event %s failed", failure.event.id, exc_info=failure.exception)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
consumption = asyncio.create_task(
|
|
260
|
+
subscriber.consume(
|
|
261
|
+
"recipemaker-analyses",
|
|
262
|
+
"eventhub.materialcatalog.>",
|
|
263
|
+
handle,
|
|
264
|
+
ConsumeOptions(on_handler_failure=report),
|
|
265
|
+
)
|
|
266
|
+
)
|
|
267
|
+
# consumption.cancel() ends the consumption
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
The consumer name may not be empty nor contain whitespace, `.`, `*`, `>`, `/` or `\`, and `max_deliveries` must be
|
|
271
|
+
at least 1: `consume` raises a `ValueError` otherwise. `consume` runs until its task is cancelled, even before it has
|
|
272
|
+
started: it then hands no more event (those already received come back next time), and the handler is cancelled at
|
|
273
|
+
its next `await`. A cancelled handler is not a failure of the event. It uses a **durable consumer**: NATS remembers
|
|
274
|
+
where the consumer named `consumer_name` stopped, and the next `consume` with the same name resumes there, so an
|
|
275
|
+
application that was stopped receives the events it missed.
|
|
276
|
+
|
|
277
|
+
- Every received event carries the NATS subject it was published on, `nats_subject`, and its position in the stream,
|
|
278
|
+
`stream_sequence`.
|
|
279
|
+
- An event is acknowledged once the handler succeeds. When the handler raises, the failure is passed to
|
|
280
|
+
`on_handler_failure` and the event comes back a second later, up to `max_deliveries` deliveries (5 by default).
|
|
281
|
+
After the last one (`is_last_attempt`), the consumer gives the event up; it stays in the stream.
|
|
282
|
+
- Events are handed one at a time, and delivered **at least once**: an event comes back when the application stops
|
|
283
|
+
before acknowledging it, or when its handler runs longer than the acknowledgement wait of NATS (30 s). A handler
|
|
284
|
+
must accept an event it has already handled (the event `id` tells).
|
|
285
|
+
- A message that is not an EventHub event is passed to `on_invalid_message` (an `InvalidMessage`: its NATS subject,
|
|
286
|
+
stream sequence, body and error) and set aside for good, so that it does not come back in a loop.
|
|
287
|
+
- `start` only matters the first time the consumer is created: `SubscriptionStart.NEW_EVENTS` (default) receives the
|
|
288
|
+
events published from then on, `SubscriptionStart.ALL_STORED_EVENTS` also receives the events still stored. A later
|
|
289
|
+
`consume` with the same name keeps the position of the consumer, and updates its filter and `max_deliveries`.
|
|
290
|
+
- A callback that raises (`on_invalid_message`, `on_handler_failure`) ends `consume` with its exception, once the
|
|
291
|
+
message is set aside or asked for again.
|
|
292
|
+
- `consume` goes on through a NATS restart: when JetStream answers that it is not available (503), it asks again a
|
|
293
|
+
second later, as the .NET and TypeScript clients do.
|
|
294
|
+
- To stop, cancel the `consume` task first, then drain the connection (`await connection.drain()`): the other way
|
|
295
|
+
round, the drain ends `consume` with a `ConnectionClosedError`.
|
|
296
|
+
|
|
297
|
+
To read the past (replay), `read_from` returns, in order, the events stored from a start, then stops once caught up.
|
|
298
|
+
`follow_from` reads the same way, then goes on with the new events as they are published, until its task is
|
|
299
|
+
cancelled:
|
|
300
|
+
|
|
301
|
+
```python
|
|
302
|
+
async for received_event in subscriber.read_from(ReadStart.at(since), "eventhub.raceway.>"):
|
|
303
|
+
...
|
|
304
|
+
|
|
305
|
+
async for received_event in subscriber.follow_from(ReadStart.after(last_sequence), "eventhub.raceway.>"):
|
|
306
|
+
last_sequence = received_event.stream_sequence
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
- The start is a date with a time zone (`ReadStart.at`) or the stream sequence of an event already read
|
|
310
|
+
(`ReadStart.after`): every received event carries its position in the stream, `stream_sequence`. NATS cannot look
|
|
311
|
+
an event up by its `id`.
|
|
312
|
+
- Unlike `consume`, they leave nothing behind in NATS: to resume later, the application keeps the `stream_sequence`
|
|
313
|
+
of the last event it handled. A loop left before its end (a `break`) releases its NATS consumer when the generator
|
|
314
|
+
is closed, which Python does later: wrap the generator in `contextlib.aclosing` to release it at once. Either way,
|
|
315
|
+
NATS deletes a consumer nobody reads after a minute.
|
|
316
|
+
- A read survives the loss of its NATS consumer: NATS deletes it when the application takes more than a minute on the
|
|
317
|
+
events fetched ahead (up to 256), or on a restart. The read then goes on right after the last event read, each event
|
|
318
|
+
once and in order.
|
|
319
|
+
- They skip messages that are not EventHub events, after passing them to `ReadOptions.on_invalid_message`.
|
|
320
|
+
- When `ReadStart.after` asks for events already removed by the stream retention, `ReadOptions.on_missed_events` gets
|
|
321
|
+
the requested and the oldest stored sequences before the read goes on from the oldest stored event. A start at a date
|
|
322
|
+
cannot tell: NATS does not keep the time of the removed events.
|
|
323
|
+
|
|
324
|
+
All three check the filter with `EventNatsSubject.validate_filter`: wildcards as whole tokens, `>` only last. Like
|
|
325
|
+
`EventNatsSubject.validate_filter`, they name it `subject_filter`, since `filter` is a Python built-in.
|
|
326
|
+
|
|
327
|
+
## Modifying an event
|
|
328
|
+
|
|
329
|
+
Only the EventHub backend modifies an event: `EventModifier` sends it the **commands** (NATS Request-Reply, see the
|
|
330
|
+
[backend README](https://github.com/industream/industream-event-hub/blob/main/Backend/README.md#commands)) and returns
|
|
331
|
+
the event with its full new state.
|
|
332
|
+
|
|
333
|
+
```python
|
|
334
|
+
from industream.eventhub.client import CommandActor, EventModifier
|
|
335
|
+
|
|
336
|
+
modifier = EventModifier(connection)
|
|
337
|
+
actor = CommandActor.application("raceway")
|
|
338
|
+
|
|
339
|
+
acknowledged = await modifier.acknowledge(received_event.id, actor, "Coal injection reduced.")
|
|
340
|
+
ended = await modifier.end(received_event.id, actor, "Back to normal.")
|
|
341
|
+
# ended.state.acknowledgement, ended.state.end: actor (type, id, proof), time, comment
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
- `acknowledge` records that the actor has taken the event into account: any event, once, with an optional comment.
|
|
345
|
+
`end` records that an event that lasts (`lasting`, an alarm) is over: once, with an optional comment; it
|
|
346
|
+
acknowledges it too when it is not acknowledged yet (in the name and at the time of the end, without the comment).
|
|
347
|
+
An acknowledged alarm stays active until it is ended. A comment is at most 1000 characters
|
|
348
|
+
(`EventComment.MAX_LENGTH`, an emoji counting as one, the spaces around it not counted): a longer one raises a
|
|
349
|
+
`ValueError` before the command is sent, as the backend would refuse it.
|
|
350
|
+
- The actor decides the subject and the headers of the command, and the backend records it with the modification:
|
|
351
|
+
|
|
352
|
+
| Actor | Who | Subject |
|
|
353
|
+
|---|---|---|
|
|
354
|
+
| `CommandActor.user(hub_token)` | A user, proven by their Industream Hub access token (`Authorization` header) | `eventhubcmd.<command>.user` |
|
|
355
|
+
| `CommandActor.declared_user(user_name)` | A user named without proof (`Eventhub-Actor` header), for a backend whose authentication is off | `eventhubcmd.<command>.user` |
|
|
356
|
+
| `CommandActor.application(application_name)` | An application, proven by the NATS permissions of its NATS user | `eventhubcmd.<command>.application.<name>` |
|
|
357
|
+
| `CommandActor.flow(flow_name)` | A FlowMaker flow (`Eventhub-Actor` header), sent by the FlowMaker box | `eventhubcmd.<command>.flow` |
|
|
358
|
+
|
|
359
|
+
An empty token, a blank name, a name with a control character, or an application name that is not a single
|
|
360
|
+
subject token (whitespace, `.`, `*`, `>`) raises a `ValueError`, as does an empty event id.
|
|
361
|
+
- When the backend refuses the command, an `EventModificationError` carries its `status` (the HTTP meaning: 400
|
|
362
|
+
instantaneous event or invalid request, 401 Hub token missing or invalid, 404 unknown event, 409 already acknowledged
|
|
363
|
+
or ended, 503 event not stored yet: send again), `title` and `detail`, for the `reason` `BackendErrorReason.REFUSED`. When no backend answers
|
|
364
|
+
(`NO_BACKEND`), or not within 10 seconds (`TIMEOUT`), or its reply cannot be read (`UNREADABLE_REPLY`), `status`
|
|
365
|
+
is `None`. After a timeout, the modification may have been recorded: sent again, it gets 409. A timeout also
|
|
366
|
+
comes when the NATS rights of the connection refuse the NATS subject of the command: NATS drops the command without
|
|
367
|
+
answering.
|
|
368
|
+
|
|
369
|
+
## Reading the history
|
|
370
|
+
|
|
371
|
+
The stream keeps the events for its retention only (30 days by default), and NATS filters them by subject and date
|
|
372
|
+
only. The backend keeps every event in its database: `EventHistoryReader` reads them through its read queries (NATS
|
|
373
|
+
Request-Reply, see the [backend README](https://github.com/industream/industream-event-hub/blob/main/Backend/README.md#queries)),
|
|
374
|
+
with the state of each event.
|
|
375
|
+
|
|
376
|
+
```python
|
|
377
|
+
from datetime import UTC, datetime, timedelta
|
|
378
|
+
|
|
379
|
+
from industream.eventhub.client import EventHistoryFilter, EventHistoryReader, EventSeverity
|
|
380
|
+
|
|
381
|
+
reader = EventHistoryReader(connection)
|
|
382
|
+
history_filter = EventHistoryFilter(
|
|
383
|
+
from_=datetime.now(UTC) - timedelta(days=7),
|
|
384
|
+
projects=["raceway"],
|
|
385
|
+
severities=[EventSeverity.ALARM],
|
|
386
|
+
in_progress=True,
|
|
387
|
+
attributes={"tuyere": 12},
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
page = await reader.read_history(history_filter, offset=0, limit=50)
|
|
391
|
+
# page.total; page.events: LatestEventVersion (event with its nats_subject, state), most recent first
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
- Every filter is optional: the period `[from_, to[` (times with a time zone), projects, severities, categories,
|
|
395
|
+
`acknowledged`, `in_progress` (events that last and are not ended), `has_sop`, publisher attributes (equality as text: 12
|
|
396
|
+
finds 12 and "12") and `text` (contained in the type, the CloudEvents subject or an attribute value, whatever the
|
|
397
|
+
case).
|
|
398
|
+
- `window` chooses which events of the period to keep: `EventWindow.STARTS` (the default) the events that start in it,
|
|
399
|
+
`EventWindow.OVERLAPS` also the lasting events that started before it and are not ended before its start. The
|
|
400
|
+
statistics refuse `OVERLAPS` when they group by time.
|
|
401
|
+
- `selectors` gives groups of conditions, each an `EventSelector` with `projects` and `attributes`: an event is kept
|
|
402
|
+
when it meets every condition of at least one selector, on top of the other filters. The backend refuses an empty
|
|
403
|
+
selector and more than 100 selectors (an `EventQueryError`, 400).
|
|
404
|
+
- `ids` keeps the events of these ids, whatever their time, on top of the other filters: an id not stored gives no
|
|
405
|
+
event, so the ids missing from the page are those not found. The backend refuses an id that is not a UUID and more
|
|
406
|
+
than 100 ids (an `EventQueryError`, 400).
|
|
407
|
+
- `acknowledged_by` and `ended_by` keep the events acknowledged (or ended) by one of these actors, named by their id
|
|
408
|
+
(a user, an application or a flow), whole and whatever the case: `"JDupont"` finds `jdupont`, `"dupont"` finds
|
|
409
|
+
nothing. `acknowledged_from`/`acknowledged_to` and `ended_from`/`ended_to` keep the events acknowledged (or ended)
|
|
410
|
+
in that period, from included, to excluded, with a time zone; the end period keeps only the lasting events ended by
|
|
411
|
+
a modification, never an instantaneous event. The backend refuses a blank name and an empty period (an
|
|
412
|
+
`EventQueryError`, 400).
|
|
413
|
+
- The caller chooses the page: `offset` and `limit` (50 by default, 500 at most). `total` counts the events of the
|
|
414
|
+
filter, all pages included. A page of large events holds fewer than `limit` (a reply stays under the 1 MB of a NATS
|
|
415
|
+
message): the next page starts at `offset` + the events received.
|
|
416
|
+
- Only the main events are listed, each with the full state its modifications gave it (`EventState`, no acknowledgement
|
|
417
|
+
and no end when never modified).
|
|
418
|
+
- When the backend refuses the query (400: an invalid filter or page), an `EventQueryError` carries its `status`,
|
|
419
|
+
`title` and `detail`, for the `reason` `BackendErrorReason.REFUSED`; when no backend answers (`NO_BACKEND`), or not
|
|
420
|
+
within 10 seconds (`TIMEOUT`), or its reply cannot be read (`UNREADABLE_REPLY`), `status` is `None`. A timeout
|
|
421
|
+
also comes when the NATS rights of the connection refuse the NATS subject of the query. The queries are open: every
|
|
422
|
+
NATS user that reads the stream may send them, without Hub token.
|
|
423
|
+
|
|
424
|
+
### Statistics
|
|
425
|
+
|
|
426
|
+
`read_statistics` counts the main events of a history filter per group: per project, per severity, per time bucket,
|
|
427
|
+
per publisher attribute… One call gives one grouping; a screen that shows several (the Overview of the UI) makes
|
|
428
|
+
several calls.
|
|
429
|
+
|
|
430
|
+
```python
|
|
431
|
+
from industream.eventhub.client import StatisticsDimension, StatisticsOrder
|
|
432
|
+
|
|
433
|
+
to = datetime.now(UTC)
|
|
434
|
+
history_filter = EventHistoryFilter(from_=to - timedelta(hours=24), to=to, projects=["raceway"])
|
|
435
|
+
|
|
436
|
+
per_hour = await reader.read_statistics(
|
|
437
|
+
history_filter,
|
|
438
|
+
[StatisticsDimension.TIME, StatisticsDimension.SEVERITY],
|
|
439
|
+
bucket_size=timedelta(hours=1),
|
|
440
|
+
order_by=StatisticsOrder.KEY,
|
|
441
|
+
)
|
|
442
|
+
# per_hour.groups: time, severity and count of each group; total, group_count
|
|
443
|
+
|
|
444
|
+
open_alarms_per_tuyere = await reader.read_statistics(
|
|
445
|
+
EventHistoryFilter(severities=[EventSeverity.ALARM], in_progress=True),
|
|
446
|
+
[StatisticsDimension.attribute("tuyere")],
|
|
447
|
+
)
|
|
448
|
+
# open_alarms_per_tuyere.groups[0].attributes["tuyere"]: 12, as published
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
- The dimensions: `PROJECT`, `SEVERITY`, `CATEGORY`, `TYPE`, `ACKNOWLEDGED`, `IN_PROGRESS`, `ACKNOWLEDGED_BY`,
|
|
452
|
+
`ENDED_BY`, `TIME` and `attribute(name)`, each at most once. A group gives the keys of its dimensions only, the
|
|
453
|
+
others are `None`.
|
|
454
|
+
- `ACKNOWLEDGED_BY` and `ENDED_BY` give the id of the actor; the events nobody acknowledged (or ended) make a group
|
|
455
|
+
where it is `None`. Ending an event acknowledges it too, by the same actor, when it was not acknowledged yet.
|
|
456
|
+
- `TIME` needs `bucket_size`, in whole seconds, and the `from_` of the filter: the buckets start at `from_`, every
|
|
457
|
+
`bucket_size`, and `time` is the start of a bucket, in UTC. The buckets without events are not given: the caller
|
|
458
|
+
fills them with 0.
|
|
459
|
+
- `attributes` keeps the published values: 12 and "12" are two groups, a `None` value groups the events without the
|
|
460
|
+
attribute.
|
|
461
|
+
- `order_by`: `COUNT` (by default) gives the most numerous groups first, `KEY` orders them by their keys, in the order
|
|
462
|
+
of the dimensions. `limit` (1000 by default and at most) cuts the groups; `total` and `group_count` are computed
|
|
463
|
+
before it.
|
|
464
|
+
- Same errors as the history: an `EventQueryError`.
|
|
465
|
+
|
|
466
|
+
## Differences with the .NET client
|
|
467
|
+
|
|
468
|
+
What Python imposes, everything else being a translation:
|
|
469
|
+
|
|
470
|
+
- `EventSeverity` and `EventCategory` are enums with `UPPER_CASE` members, the Python convention:
|
|
471
|
+
`EventSeverity.ALARM` is `EventSeverity.Alarm` in .NET. The value of an `EventSeverity` is its OpenTelemetry number,
|
|
472
|
+
as in .NET; the value of an `EventCategory` is the name used by the contract (`"Process"`).
|
|
473
|
+
- An invalid value raises a `ValueError`, the Python counterpart of `ArgumentException`.
|
|
474
|
+
- `time` is a `datetime` that must have a time zone: a naive `datetime` would be read in the local time of the
|
|
475
|
+
machine, a silent error.
|
|
476
|
+
- A publisher attribute is a `str`, a 32-bit `int`, a `bool` or a `datetime`: Python has no URI type, so a URI is
|
|
477
|
+
given as a `str`.
|
|
478
|
+
- `CloudEvent` is a type of this client, a read-only mapping of the structured JSON, not the class of the CloudEvents
|
|
479
|
+
SDK as in .NET. The Python SDK (`cloudevents` 2.x) checks almost none of the rules of the contract: it accepts any
|
|
480
|
+
extension value, reads a time at `24:00` or written with a lowercase `t` or `z`, and writes the time to the
|
|
481
|
+
microsecond (`…42.318000Z`) where the contract wants `…42.318Z`. Every rule would then have to be written around it
|
|
482
|
+
anyway, in two places and with two more dependencies (`cloudevents`, `python-dateutil`). Instead, `EventFactory`,
|
|
483
|
+
`EventJson` and `EventDecoder` follow the CloudEvents rules themselves, held by the shared contract cases, as the
|
|
484
|
+
TypeScript client does.
|
|
485
|
+
- `ReceivedEvent` gives `None` for a missing value, `root_event_id` as a `UUID` (the `Guid` of .NET), `time` as a
|
|
486
|
+
`datetime` in UTC (to the microsecond, the precision of `datetime`), and `data` as parsed JSON.
|
|
487
|
+
- `EventDecoder` checks what the .NET SDK checks: the required attributes (`id`, `source`, `type`, `specversion`
|
|
488
|
+
1.0, and `time` for EventHub), the types of the standard attributes (an RFC 3339 `time`, a URI reference
|
|
489
|
+
`source`…), and extension values of the CloudEvents type system only. It also rejects `NaN` and `Infinity`, which
|
|
490
|
+
the `json` module reads although they are not JSON.
|
|
491
|
+
- The client is asynchronous (asyncio), as nats-py is. Cancelling the task replaces the .NET `CancellationToken`, the
|
|
492
|
+
asyncio convention: `consume`, `read_from` and `follow_from` take no token, and the handler only gets the event.
|
|
493
|
+
A cancelled `consume` or `follow_from` ends with `asyncio.CancelledError`, as any cancelled coroutine, where .NET
|
|
494
|
+
returns quietly; nothing else is raised, and a cancelled handler is not reported as a failure. To stop an
|
|
495
|
+
application, cancel these tasks first, then close or drain the connection: once the connection is closed, nats-py
|
|
496
|
+
ends what still waits for messages with a `ConnectionClosedError`.
|
|
497
|
+
- The error messages are those of .NET, in the Python words of the TypeScript client where the types differ
|
|
498
|
+
(`max_deliveries`, `None`, `int`): the shared contract cases check the same parts of them.
|
|
499
|
+
- `publish` takes no cancellation either: cancelling its task stops the wait for the acknowledgement. Nor do
|
|
500
|
+
`acknowledge`, `end`, `read_history` and `read_statistics`: cancelling their task stops the wait for the reply.
|
|
501
|
+
- `EventHistoryFilter.from_` is the `From` of .NET: `from` is a keyword of Python. A time of the filter without time
|
|
502
|
+
zone raises a `ValueError`, as `ReadStart.at` does.
|
|
503
|
+
- `ActorType` and `ActorProof` are enums with `UPPER_CASE` members (`ActorProof.HUB_TOKEN`), valued with the .NET
|
|
504
|
+
names (`"HubToken"`); the times of `EventState` are `datetime`s in UTC.
|
|
505
|
+
- `StatisticsOrder` is an enum in the same way (`StatisticsOrder.KEY`, valued `"Key"`), and the constants of
|
|
506
|
+
`StatisticsDimension` are `UPPER_CASE` (`StatisticsDimension.IN_PROGRESS`); the `time` of a statistics group is a
|
|
507
|
+
`datetime` in UTC. The filter of `read_history` and `read_statistics` is `history_filter`: `filter` is a built-in of
|
|
508
|
+
Python.
|
|
509
|
+
- `HandlerFailure.exception` is the `Exception` the handler raised; the callbacks of `ConsumeOptions` and
|
|
510
|
+
`ReadOptions` are plain functions, as the `Action` callbacks of .NET.
|
|
511
|
+
- `follow_from` reads with an ordered consumer of this client, where .NET uses the one of NATS.Net: an ephemeral pull
|
|
512
|
+
consumer kept in memory, created again right after the last event read when it is lost (a NATS restart, a
|
|
513
|
+
disconnection or a reader slower than a minute) or when a message is missing. `read_from` reads with the same one,
|
|
514
|
+
stopping once caught up, as .NET recreates its read consumer. The ordered consumer of nats-py is not used: when
|
|
515
|
+
it creates its consumer again, it keeps the start date next to the new start sequence, which the server refuses
|
|
516
|
+
(`follow_from` would then wait for good), and it starts from the beginning of the stream when no event was read yet.
|
|
517
|
+
|
|
518
|
+
## Build and test
|
|
519
|
+
|
|
520
|
+
From this folder, with [uv](https://docs.astral.sh/uv/):
|
|
521
|
+
|
|
522
|
+
```bash
|
|
523
|
+
uv sync
|
|
524
|
+
uv run ruff check
|
|
525
|
+
uv run ruff format --check
|
|
526
|
+
uv run mypy
|
|
527
|
+
uv run pytest
|
|
528
|
+
```
|
|
529
|
+
|
|
530
|
+
`uv run pytest tests/unit` runs the unit tests only; `uv run pytest tests/e2e` runs the end-to-end tests, which start a
|
|
531
|
+
throwaway NATS server with Testcontainers: Docker must be running.
|