hexkit 9.0.3__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.
Files changed (94) hide show
  1. hexkit-11.0.0/MANIFEST.in +7 -0
  2. {hexkit-9.0.3/src/hexkit.egg-info → hexkit-11.0.0}/PKG-INFO +36 -61
  3. hexkit-11.0.0/README.md +92 -0
  4. {hexkit-9.0.3 → hexkit-11.0.0}/pyproject.toml +7 -11
  5. hexkit-11.0.0/src/hexkit/.agents/skills/hexkit/SKILL.md +112 -0
  6. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/log.py +2 -2
  7. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/opentelemetry/instrumentation.py +48 -3
  8. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/protocols/dao.py +359 -18
  9. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/protocols/daopub.py +3 -1
  10. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/protocols/objstorage.py +3 -0
  11. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/akafka/provider/eventsub.py +364 -72
  12. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/akafka/testcontainer.py +1 -1
  13. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/akafka/testutils.py +32 -12
  14. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongodb/migrations/_manager.py +19 -10
  15. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongodb/migrations/_utils.py +6 -0
  16. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongodb/migrations/helpers.py +2 -2
  17. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongodb/provider/__init__.py +4 -4
  18. hexkit-11.0.0/src/hexkit/providers/mongodb/provider/dao.py +861 -0
  19. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongodb/provider/utils.py +5 -2
  20. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongodb/testutils.py +1 -1
  21. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongokafka/provider/daopub.py +376 -105
  22. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongokafka/provider/persistent_pub.py +2 -2
  23. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/redis/testutils.py +1 -1
  24. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/provider/objstorage.py +5 -3
  25. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/testutils/_fixtures.py +2 -2
  26. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/testing/dao.py +176 -31
  27. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/testing/objstorage.py +14 -4
  28. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/vault/testutils.py +15 -14
  29. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/utils.py +2 -2
  30. {hexkit-9.0.3 → hexkit-11.0.0/src/hexkit.egg-info}/PKG-INFO +36 -61
  31. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit.egg-info/SOURCES.txt +1 -0
  32. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit.egg-info/requires.txt +5 -5
  33. hexkit-9.0.3/MANIFEST.in +0 -2
  34. hexkit-9.0.3/README.md +0 -118
  35. hexkit-9.0.3/src/hexkit/providers/mongodb/provider/dao.py +0 -535
  36. {hexkit-9.0.3 → hexkit-11.0.0}/LICENSE +0 -0
  37. {hexkit-9.0.3 → hexkit-11.0.0}/setup.cfg +0 -0
  38. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/__init__.py +0 -0
  39. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/__main__.py +0 -0
  40. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/base.py +0 -0
  41. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/config.py +0 -0
  42. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/correlation.py +0 -0
  43. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/custom_types.py +0 -0
  44. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/opentelemetry/__init__.py +0 -0
  45. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/opentelemetry/testutils.py +0 -0
  46. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/protocols/__init__.py +0 -0
  47. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/protocols/daosub.py +0 -0
  48. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/protocols/eventpub.py +0 -0
  49. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/protocols/eventsub.py +0 -0
  50. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/protocols/kvstore.py +0 -0
  51. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/__init__.py +0 -0
  52. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/akafka/__init__.py +0 -0
  53. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/akafka/config.py +0 -0
  54. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/akafka/provider/__init__.py +0 -0
  55. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/akafka/provider/daosub.py +0 -0
  56. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/akafka/provider/eventpub.py +0 -0
  57. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/akafka/provider/utils.py +0 -0
  58. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongodb/__init__.py +0 -0
  59. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongodb/config.py +0 -0
  60. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongodb/migrations/__init__.py +0 -0
  61. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongodb/provider/client.py +0 -0
  62. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongodb/provider/kvstore.py +0 -0
  63. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongokafka/__init__.py +0 -0
  64. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongokafka/config.py +0 -0
  65. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongokafka/provider/__init__.py +0 -0
  66. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/mongokafka/testutils.py +0 -0
  67. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/redis/__init__.py +0 -0
  68. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/redis/config.py +0 -0
  69. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/redis/provider/__init__.py +0 -0
  70. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/redis/provider/client.py +0 -0
  71. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/redis/provider/kvstore.py +0 -0
  72. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/__init__.py +0 -0
  73. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/config.py +0 -0
  74. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/provider/__init__.py +0 -0
  75. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/provider/kvstore.py +0 -0
  76. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/test_files/__init__.py +0 -0
  77. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/test_files/test_file1.yaml +0 -0
  78. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/test_files/test_file2.yaml +0 -0
  79. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/test_files/test_file3.yaml +0 -0
  80. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/test_files/test_file4.yaml +0 -0
  81. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/testutils/__init__.py +0 -0
  82. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/testutils/_typical_workflow.py +0 -0
  83. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/s3/testutils/_utils.py +0 -0
  84. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/testing/__init__.py +0 -0
  85. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/testing/eventpub.py +0 -0
  86. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/testing/kvstore.py +0 -0
  87. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/vault/__init__.py +0 -0
  88. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/vault/config.py +0 -0
  89. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/vault/provider/__init__.py +0 -0
  90. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/vault/provider/client.py +0 -0
  91. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/providers/vault/provider/kvstore.py +0 -0
  92. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit/py.typed +0 -0
  93. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit.egg-info/dependency_links.txt +0 -0
  94. {hexkit-9.0.3 → hexkit-11.0.0}/src/hexkit.egg-info/top_level.txt +0 -0
@@ -0,0 +1,7 @@
1
+ include src/hexkit/py.typed
2
+ include src/hexkit/providers/s3/test_files/*.yaml
3
+ # The tests run in the monorepo; setuptools would ship only tests/test*.py, a broken suite.
4
+ prune tests
5
+ # The agent skill ships in the wheel for tools that read it from site-packages;
6
+ # its eval suite stays out by not being listed.
7
+ include src/hexkit/.agents/skills/hexkit/SKILL.md
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hexkit
3
- Version: 9.0.3
3
+ Version: 11.0.0
4
4
  Summary: A Toolkit for Building Microservices using the Hexagonal Architecture
5
5
  Author-email: "German Human Genome Phenome Archive (GHGA)" <contact@ghga.de>
6
6
  License-Expression: Apache-2.0
@@ -15,6 +15,7 @@ Classifier: Programming Language :: Python :: 3.11
15
15
  Classifier: Programming Language :: Python :: 3.12
16
16
  Classifier: Programming Language :: Python :: 3.13
17
17
  Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
18
19
  Classifier: Topic :: Software Development :: Libraries
19
20
  Classifier: Intended Audience :: Developers
20
21
  Requires-Python: >=3.11
@@ -68,20 +69,20 @@ Requires-Dist: hexkit[opentelemetry-fastapi]; extra == "opentelemetry"
68
69
  Requires-Dist: hexkit[opentelemetry-s3]; extra == "opentelemetry"
69
70
  Provides-Extra: test-akafka
70
71
  Requires-Dist: hexkit[akafka]; extra == "test-akafka"
71
- Requires-Dist: testcontainers[kafka]<5,>=4.14; extra == "test-akafka"
72
+ Requires-Dist: testcontainers[kafka]<5,>=4.15; extra == "test-akafka"
72
73
  Provides-Extra: test-s3
73
74
  Requires-Dist: hexkit[s3]; extra == "test-s3"
74
75
  Requires-Dist: httpx2<3,>=2.9.1; extra == "test-s3"
75
- Requires-Dist: testcontainers<5,>=4.14; extra == "test-s3"
76
+ Requires-Dist: testcontainers<5,>=4.15; extra == "test-s3"
76
77
  Provides-Extra: test-mongodb
77
78
  Requires-Dist: hexkit[mongodb]; extra == "test-mongodb"
78
- Requires-Dist: testcontainers[mongodb]<5,>=4.14; extra == "test-mongodb"
79
+ Requires-Dist: testcontainers[mongodb]<5,>=4.15; extra == "test-mongodb"
79
80
  Provides-Extra: test-redis
80
81
  Requires-Dist: hexkit[redis]; extra == "test-redis"
81
- Requires-Dist: testcontainers[redis]<5,>=4.14; extra == "test-redis"
82
+ Requires-Dist: testcontainers[redis]<5,>=4.15; extra == "test-redis"
82
83
  Provides-Extra: test-vault
83
84
  Requires-Dist: hexkit[vault]; extra == "test-vault"
84
- Requires-Dist: testcontainers<5,>=4.14; extra == "test-vault"
85
+ Requires-Dist: testcontainers<5,>=4.15; extra == "test-vault"
85
86
  Provides-Extra: test
86
87
  Requires-Dist: hexkit[test-akafka,test-mongodb,test-s3,test-vault]; extra == "test"
87
88
  Provides-Extra: all
@@ -89,20 +90,18 @@ Requires-Dist: hexkit[test]; extra == "all"
89
90
  Requires-Dist: hexkit[opentelemetry]; extra == "all"
90
91
  Dynamic: license-file
91
92
 
93
+ <!-- rumdl-disable MD013 -->
92
94
  [![PyPI version shields.io](https://img.shields.io/pypi/v/hexkit.svg)](https://pypi.org/project/hexkit/)
93
95
  [![PyPI pyversions](https://img.shields.io/pypi/pyversions/hexkit.svg)](https://pypi.org/project/hexkit/)
94
96
  [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
95
97
  [![Checked with mypy](https://www.mypy-lang.org/static/mypy_badge.svg)](https://mypy-lang.org/)
98
+ <!-- rumdl-enable MD013 -->
96
99
 
97
100
  # hexkit
98
101
 
99
- *A chassis library for building domain-focused, infrastructure-agnostic,
100
- and event-driven microservices in Python*
102
+ *A chassis library for building domain-focused, infrastructure-agnostic, and event-driven microservices in Python.*
101
103
 
102
- Read the short summary below, or jump straight to our full
103
- 📖 **[User Guide](https://ghga-de.github.io/ghga/hexkit/user-guide/)** to learn the abstract
104
- concepts and patterns as well as the concrete infrastructure integrations and testing
105
- tools that hexkit provides for building better microservices.
104
+ Read the short summary below, or jump straight to our full 📖 **[User Guide](https://ghga-de.github.io/ghga/hexkit/user-guide/)** to learn the abstract concepts and patterns as well as the concrete infrastructure integrations and testing tools that hexkit provides for building better microservices.
106
105
 
107
106
  <!--
108
107
  NOTE: This README doubles as the landing page of the documentation site built with
@@ -112,24 +111,14 @@ great-docs. Therefore, all links must be absolute URLs — repo-relative links l
112
111
 
113
112
  ## In a Nutshell
114
113
 
115
- hexkit implements the *Triple Hexagonal Architecture* pattern, an optimization of the
116
- ordinary
117
- [Hexagonal Architecture](https://alistair.cockburn.us/hexagonal-architecture/) for
118
- use with microservices: adapters (as per the hexagonal architecture) are divided into
119
- two parts. One part called *translator* is specific to one individual microservice
120
- and its domain-oriented ports. The other part called *provider* is service-agnostic
121
- but specific to one technology of the surrounding infrastructure. Both parts interact
122
- through a high-level interface called *protocol* (not to be confused with Python's
123
- typing.Protocol) which is neither specific to the technology nor to the microservice.
124
-
125
- As a chassis lib, hexkit reduces redundancy and boilerplate across microservices by
126
- providing the service-independent building blocks — protocols and providers — ready
127
- to use. The only task that remains for an individual service is to implement
128
- service-specific translators between the service's ports and the general-purpose
129
- protocols (in addition to implementing the domain functionality of the service, of
130
- course). For an in-depth introduction to the pattern, please read the
131
- [Architectural Concepts](https://ghga-de.github.io/ghga/hexkit/user-guide/arch_concepts/)
132
- chapter of the User Guide.
114
+ hexkit implements the *Triple Hexagonal Architecture* pattern, an optimization of the ordinary [Hexagonal Architecture](https://alistair.cockburn.us/hexagonal-architecture/) for use with microservices: adapters (as per the hexagonal architecture) are divided into two parts.
115
+ One part called *translator* is specific to one individual microservice and its domain-oriented ports.
116
+ The other part called *provider* is service-agnostic but specific to one technology of the surrounding infrastructure.
117
+ Both parts interact through a high-level interface called *protocol* (not to be confused with Python's typing.Protocol) which is neither specific to the technology nor to the microservice.
118
+
119
+ As a chassis lib, hexkit reduces redundancy and boilerplate across microservices by providing the service-independent building blocks — protocols and providers — ready to use.
120
+ The only task that remains for an individual service is to implement service-specific translators between the service's ports and the general-purpose protocols (in addition to implementing the domain functionality of the service, of course).
121
+ For an in-depth introduction to the pattern, please read the [Architectural Concepts](https://ghga-de.github.io/ghga/hexkit/user-guide/arch_concepts/) chapter of the User Guide.
133
122
 
134
123
  The following protocols and providers are currently available:
135
124
 
@@ -141,29 +130,21 @@ The following protocols and providers are currently available:
141
130
  | Object Storage | S3(-compatible) |
142
131
  | Key-Value Store | MongoDB, Redis, S3, HashiCorp Vault |
143
132
 
144
- In-memory implementations and per-backend test utilities are also included to
145
- support testing without real infrastructure.
133
+ In-memory implementations and per-backend test utilities are also included to support testing without real infrastructure.
146
134
 
147
135
  You are not forced to go all-in on the idea of Triple Hexagonal Architecture.
148
- You can use it just for the technologies where you see benefits and use another
149
- approach for the rest. For example, you could use hexkit for simplifying the exchange
150
- of events between microservices but use a classical web framework such as FastAPI for
151
- designing REST APIs and an ORM like SQLAlchemy for interacting with databases.
136
+ You can use it just for the technologies where you see benefits and use another approach for the rest.
137
+ For example, you could use hexkit for simplifying the exchange of events between microservices but use a classical web framework such as FastAPI for designing REST APIs and an ORM like SQLAlchemy for interacting with databases.
152
138
 
153
139
  ## Getting Started
154
140
 
155
- The 📖 [User Guide](https://ghga-de.github.io/ghga/hexkit/user-guide/) covers all
156
- protocols, providers, testing utilities, and observability tools with example code,
157
- and the [API Reference](https://ghga-de.github.io/ghga/hexkit/reference/) documents all
158
- public classes and functions.
141
+ The 📖 [User Guide](https://ghga-de.github.io/ghga/hexkit/user-guide/) covers all protocols, providers, testing utilities, and observability tools with example code, and the [API Reference](https://ghga-de.github.io/ghga/hexkit/reference/) documents all public classes and functions.
142
+
143
+ For a complete example service built with hexkit, have a look at the [stream_calc](https://github.com/ghga-de/ghga/tree/main/libs/hexkit/examples/stream_calc) example application.
144
+ We also put a lot of effort into making the code self-documenting: you can find the protocols being defined at [src/hexkit/protocols](https://github.com/ghga-de/ghga/tree/main/libs/hexkit/src/hexkit/protocols) and the providers being implemented at [src/hexkit/providers](https://github.com/ghga-de/ghga/tree/main/libs/hexkit/src/hexkit/providers).
159
145
 
160
- For a complete example service built with hexkit, have a look at the
161
- [stream_calc](https://github.com/ghga-de/ghga/tree/main/libs/hexkit/examples/stream_calc)
162
- example application. We also put a lot of effort into making the code
163
- self-documenting: you can find the protocols being defined at
164
- [src/hexkit/protocols](https://github.com/ghga-de/ghga/tree/main/libs/hexkit/src/hexkit/protocols)
165
- and the providers being implemented at
166
- [src/hexkit/providers](https://github.com/ghga-de/ghga/tree/main/libs/hexkit/src/hexkit/providers).
146
+ Coding agents get an [agent skill](https://agentskills.io) for hexkit with the package, at `hexkit/.agents/skills/hexkit/SKILL.md` in `site-packages`, where tools such as [library-skills](https://library-skills.io) find it.
147
+ The docs site publishes the same file, so `npx skills add https://ghga-de.github.io/ghga/hexkit` installs it as well.
167
148
 
168
149
  ## Installation
169
150
 
@@ -183,27 +164,21 @@ The following extras are available:
183
164
  - `s3`: when interacting with S3-compatible object storages or key-value stores
184
165
  - `redis`: when using Redis-based key-value stores
185
166
  - `vault`: when using HashiCorp Vault-based key-value stores
186
- - `opentelemetry`: observability instrumentation (also available per backend, e.g.
187
- `opentelemetry-akafka`, `opentelemetry-mongodb`, `opentelemetry-fastapi`)
188
- - `test-akafka`, `test-mongodb`, `test-s3`, `test-redis`, `test-vault`: testing
189
- utils for the respective backend (`test` is a union of all of them)
167
+ - `opentelemetry`: observability instrumentation (also available per backend, e.g. `opentelemetry-akafka`, `opentelemetry-mongodb`, `opentelemetry-fastapi`)
168
+ - `test-akafka`, `test-mongodb`, `test-s3`, `test-redis`, `test-vault`: testing utils for the respective backend (`test` is a union of all of them)
190
169
  - `all`: a union of all the above
191
170
 
192
171
  ## Contributing
193
172
 
194
- Contributions are welcome! hexkit is developed in the
195
- [GHGA monorepo](https://github.com/ghga-de/ghga) under `libs/hexkit`, together with the
196
- services that build on it. Please see the
197
- [contribution guide](https://github.com/ghga-de/ghga/blob/main/libs/hexkit/CONTRIBUTING.md)
198
- for how to set up the development environment and build the documentation locally.
173
+ Contributions are welcome!
174
+ hexkit is developed in the [GHGA monorepo](https://github.com/ghga-de/ghga) under `libs/hexkit`, together with the services that build on it.
175
+ Please see the [contribution guide](https://github.com/ghga-de/ghga/blob/main/libs/hexkit/CONTRIBUTING.md) for how to set up the development environment and build the documentation locally.
199
176
 
200
177
  ## Credits
201
178
 
202
- The hexkit library is developed and maintained by the developer team of GHGA. We would especially
203
- like to thank its original author, Kersten Breuer, who came up with the idea for the
204
- library and designed and coded its first versions.
179
+ The hexkit library is developed and maintained by the developer team of GHGA.
180
+ We would especially like to thank its original author, Kersten Breuer, who came up with the idea for the library and designed and coded its first versions.
205
181
 
206
182
  ## License
207
183
 
208
- hexkit is free to use and modify according to the
209
- [Apache 2.0 License](https://github.com/ghga-de/ghga/blob/main/libs/hexkit/LICENSE).
184
+ hexkit is free to use and modify according to the [Apache 2.0 License](https://github.com/ghga-de/ghga/blob/main/libs/hexkit/LICENSE).
@@ -0,0 +1,92 @@
1
+ <!-- rumdl-disable MD013 -->
2
+ [![PyPI version shields.io](https://img.shields.io/pypi/v/hexkit.svg)](https://pypi.org/project/hexkit/)
3
+ [![PyPI pyversions](https://img.shields.io/pypi/pyversions/hexkit.svg)](https://pypi.org/project/hexkit/)
4
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
5
+ [![Checked with mypy](https://www.mypy-lang.org/static/mypy_badge.svg)](https://mypy-lang.org/)
6
+ <!-- rumdl-enable MD013 -->
7
+
8
+ # hexkit
9
+
10
+ *A chassis library for building domain-focused, infrastructure-agnostic, and event-driven microservices in Python.*
11
+
12
+ Read the short summary below, or jump straight to our full 📖 **[User Guide](https://ghga-de.github.io/ghga/hexkit/user-guide/)** to learn the abstract concepts and patterns as well as the concrete infrastructure integrations and testing tools that hexkit provides for building better microservices.
13
+
14
+ <!--
15
+ NOTE: This README doubles as the landing page of the documentation site built with
16
+ great-docs. Therefore, all links must be absolute URLs — repo-relative links like
17
+ ./examples or ./src would resolve correctly on GitHub but break on the site.
18
+ -->
19
+
20
+ ## In a Nutshell
21
+
22
+ hexkit implements the *Triple Hexagonal Architecture* pattern, an optimization of the ordinary [Hexagonal Architecture](https://alistair.cockburn.us/hexagonal-architecture/) for use with microservices: adapters (as per the hexagonal architecture) are divided into two parts.
23
+ One part called *translator* is specific to one individual microservice and its domain-oriented ports.
24
+ The other part called *provider* is service-agnostic but specific to one technology of the surrounding infrastructure.
25
+ Both parts interact through a high-level interface called *protocol* (not to be confused with Python's typing.Protocol) which is neither specific to the technology nor to the microservice.
26
+
27
+ As a chassis lib, hexkit reduces redundancy and boilerplate across microservices by providing the service-independent building blocks — protocols and providers — ready to use.
28
+ The only task that remains for an individual service is to implement service-specific translators between the service's ports and the general-purpose protocols (in addition to implementing the domain functionality of the service, of course).
29
+ For an in-depth introduction to the pattern, please read the [Architectural Concepts](https://ghga-de.github.io/ghga/hexkit/user-guide/arch_concepts/) chapter of the User Guide.
30
+
31
+ The following protocols and providers are currently available:
32
+
33
+ | Protocol | Providers |
34
+ | ------------------ | -------------------------------------- |
35
+ | Event Publishing | Apache Kafka, MongoDB + Kafka (outbox) |
36
+ | Event Subscription | Apache Kafka |
37
+ | Data Access Object | MongoDB |
38
+ | Object Storage | S3(-compatible) |
39
+ | Key-Value Store | MongoDB, Redis, S3, HashiCorp Vault |
40
+
41
+ In-memory implementations and per-backend test utilities are also included to support testing without real infrastructure.
42
+
43
+ You are not forced to go all-in on the idea of Triple Hexagonal Architecture.
44
+ You can use it just for the technologies where you see benefits and use another approach for the rest.
45
+ For example, you could use hexkit for simplifying the exchange of events between microservices but use a classical web framework such as FastAPI for designing REST APIs and an ORM like SQLAlchemy for interacting with databases.
46
+
47
+ ## Getting Started
48
+
49
+ The 📖 [User Guide](https://ghga-de.github.io/ghga/hexkit/user-guide/) covers all protocols, providers, testing utilities, and observability tools with example code, and the [API Reference](https://ghga-de.github.io/ghga/hexkit/reference/) documents all public classes and functions.
50
+
51
+ For a complete example service built with hexkit, have a look at the [stream_calc](https://github.com/ghga-de/ghga/tree/main/libs/hexkit/examples/stream_calc) example application.
52
+ We also put a lot of effort into making the code self-documenting: you can find the protocols being defined at [src/hexkit/protocols](https://github.com/ghga-de/ghga/tree/main/libs/hexkit/src/hexkit/protocols) and the providers being implemented at [src/hexkit/providers](https://github.com/ghga-de/ghga/tree/main/libs/hexkit/src/hexkit/providers).
53
+
54
+ Coding agents get an [agent skill](https://agentskills.io) for hexkit with the package, at `hexkit/.agents/skills/hexkit/SKILL.md` in `site-packages`, where tools such as [library-skills](https://library-skills.io) find it.
55
+ The docs site publishes the same file, so `npx skills add https://ghga-de.github.io/ghga/hexkit` installs it as well.
56
+
57
+ ## Installation
58
+
59
+ This package is available at PyPI:
60
+ <https://pypi.org/project/hexkit>
61
+
62
+ You can install it from there using:
63
+
64
+ ```sh
65
+ pip install hexkit
66
+ ```
67
+
68
+ The following extras are available:
69
+
70
+ - `akafka`: when using the Apache Kafka-based event publishing or subscription
71
+ - `mongodb`: when using MongoDB as backend for the DAO protocol or key-value stores
72
+ - `s3`: when interacting with S3-compatible object storages or key-value stores
73
+ - `redis`: when using Redis-based key-value stores
74
+ - `vault`: when using HashiCorp Vault-based key-value stores
75
+ - `opentelemetry`: observability instrumentation (also available per backend, e.g. `opentelemetry-akafka`, `opentelemetry-mongodb`, `opentelemetry-fastapi`)
76
+ - `test-akafka`, `test-mongodb`, `test-s3`, `test-redis`, `test-vault`: testing utils for the respective backend (`test` is a union of all of them)
77
+ - `all`: a union of all the above
78
+
79
+ ## Contributing
80
+
81
+ Contributions are welcome!
82
+ hexkit is developed in the [GHGA monorepo](https://github.com/ghga-de/ghga) under `libs/hexkit`, together with the services that build on it.
83
+ Please see the [contribution guide](https://github.com/ghga-de/ghga/blob/main/libs/hexkit/CONTRIBUTING.md) for how to set up the development environment and build the documentation locally.
84
+
85
+ ## Credits
86
+
87
+ The hexkit library is developed and maintained by the developer team of GHGA.
88
+ We would especially like to thank its original author, Kersten Breuer, who came up with the idea for the library and designed and coded its first versions.
89
+
90
+ ## License
91
+
92
+ hexkit is free to use and modify according to the [Apache 2.0 License](https://github.com/ghga-de/ghga/blob/main/libs/hexkit/LICENSE).
@@ -18,12 +18,13 @@ classifiers = [
18
18
  "Programming Language :: Python :: 3.12",
19
19
  "Programming Language :: Python :: 3.13",
20
20
  "Programming Language :: Python :: 3.14",
21
+ "Programming Language :: Python :: 3.15",
21
22
  "Topic :: Software Development :: Libraries",
22
23
  "Intended Audience :: Developers",
23
24
  ]
24
25
  name = "hexkit"
25
26
  # 9.0.2 is spent on TestPyPI: a pypi-publish.yaml rehearsal uploaded it there.
26
- version = "9.0.3"
27
+ version = "11.0.0"
27
28
  description = "A Toolkit for Building Microservices using the Hexagonal Architecture"
28
29
  license = "Apache-2.0"
29
30
  dependencies = [
@@ -90,24 +91,24 @@ opentelemetry = [
90
91
  ]
91
92
  test-akafka = [
92
93
  "hexkit[akafka]",
93
- "testcontainers[kafka] >=4.14, <5",
94
+ "testcontainers[kafka] >=4.15, <5",
94
95
  ]
95
96
  test-s3 = [
96
97
  "hexkit[s3]",
97
98
  "httpx2 >=2.9.1, <3",
98
- "testcontainers >=4.14, <5",
99
+ "testcontainers >=4.15, <5",
99
100
  ]
100
101
  test-mongodb = [
101
102
  "hexkit[mongodb]",
102
- "testcontainers[mongodb] >=4.14, <5",
103
+ "testcontainers[mongodb] >=4.15, <5",
103
104
  ]
104
105
  test-redis = [
105
106
  "hexkit[redis]",
106
- "testcontainers[redis] >=4.14, <5",
107
+ "testcontainers[redis] >=4.15, <5",
107
108
  ]
108
109
  test-vault = [
109
110
  "hexkit[vault]",
110
- "testcontainers >=4.14, <5",
111
+ "testcontainers >=4.15, <5",
111
112
  ]
112
113
  test = [
113
114
  "hexkit[test-akafka,test-s3,test-mongodb,test-vault]",
@@ -128,11 +129,6 @@ where = [
128
129
  "src",
129
130
  ]
130
131
 
131
- [tool.pytest.ini_options]
132
- minversion = "9.0"
133
- asyncio_mode = "strict"
134
- asyncio_default_fixture_loop_scope = "function"
135
-
136
132
  [tool.coverage.paths]
137
133
  source = [
138
134
  "src",
@@ -0,0 +1,112 @@
1
+ ---
2
+ name: hexkit
3
+ description: Write or change Python service code that uses hexkit, the hexagonal-architecture toolkit - DAOs on MongoDB, Kafka events, the outbox, dead letter queues, migrations, config, dependency injection, and hexkit's test fixtures. Use whenever code imports hexkit.
4
+ license: Apache-2.0
5
+ ---
6
+
7
+ # hexkit
8
+
9
+ This skill covers hexkit 10.
10
+ It holds the choices and the traps; the [user guide](https://ghga-de.github.io/ghga/hexkit/user-guide/index.md) holds the details and examples.
11
+ Every guide page linked here is Markdown, so fetch the one for the task at hand rather than guessing an API.
12
+ The [API reference](https://ghga-de.github.io/ghga/hexkit/reference/index.html) has every signature.
13
+
14
+ ## Choose the building block
15
+
16
+ | Need | Protocol, in `hexkit.protocols` | Provider | Guide |
17
+ |---|---|---|---|
18
+ | Store resources | `dao.Dao`, `dao.DaoFactoryProtocol` | `MongoDbDaoFactory` | [DAO](https://ghga-de.github.io/ghga/hexkit/user-guide/protocols/dao.md), [MongoDB](https://ghga-de.github.io/ghga/hexkit/user-guide/providers/mongodb.md) |
19
+ | Store resources and tell other services their latest state | `daopub.DaoPublisher` | `MongoKafkaDaoPublisherFactory` | [DAO Publisher](https://ghga-de.github.io/ghga/hexkit/user-guide/protocols/daopublisher.md) |
20
+ | Keep a copy of another service's resources | `daosub.DaoSubscriberProtocol` | `KafkaOutboxSubscriber` | [DAO Subscriber](https://ghga-de.github.io/ghga/hexkit/user-guide/protocols/daosubscriber.md) |
21
+ | Publish events | `eventpub.EventPublisherProtocol` | `KafkaEventPublisher`, or `PersistentKafkaPublisher` to re-emit them | [Publisher](https://ghga-de.github.io/ghga/hexkit/user-guide/providers/kafka/publisher.md), [Publisher Variants](https://ghga-de.github.io/ghga/hexkit/user-guide/developer_help/outbox_v_persistent_pub.md) |
22
+ | Consume events | `eventsub.EventSubscriberProtocol` | `KafkaEventSubscriber` | [Subscriber](https://ghga-de.github.io/ghga/hexkit/user-guide/providers/kafka/subscriber.md) |
23
+ | Store files | `objstorage.ObjectStorageProtocol` | `S3ObjectStorage` | [Object Storage](https://ghga-de.github.io/ghga/hexkit/user-guide/protocols/objstorage.md), [S3](https://ghga-de.github.io/ghga/hexkit/user-guide/providers/s3.md) |
24
+ | Key-value pairs | `kvstore.KeyValueStoreProtocol` | `InMem*`, `Redis*`, `MongoDb*`, `S3*`, `Vault*KeyValueStore` | [Protocols](https://ghga-de.github.io/ghga/hexkit/user-guide/protocols/index.md) |
25
+ | Change the shape of stored documents | – | `MigrationDefinition`, `MigrationManager` | [MongoDB Migrations](https://ghga-de.github.io/ghga/hexkit/user-guide/providers/mongodb_migrations.md) |
26
+
27
+ Each provider family sits behind an extra (`akafka`, `mongodb`, `s3`, `redis`, `vault`); the test fixtures behind `test-akafka`, `test-mongodb`, `test-s3` and so on.
28
+ Look at the stored data, not the event, when choosing between the outbox and the persistent publisher: the outbox publishes the latest state of a stored resource, the persistent publisher stores events that are not a resource, such as a command that starts a flow.
29
+
30
+ ## Structure and wiring
31
+
32
+ - The core depends on ports only: `Protocol`s or abstract classes, received through keyword-only constructor parameters, the config among them.
33
+ No hexkit provider, FastAPI or other infrastructure import belongs in the core ([Triple Hexagonal Architecture](https://ghga-de.github.io/ghga/hexkit/user-guide/arch_concepts/triple_hexagonal_arch.md)).
34
+ - Translators sit between: an inbound one receives an event and calls a core port, an outbound one gives the core a domain method such as `publish_user_created()` and calls the provider.
35
+ - Wire everything in one composition root, `inject.py`, as async context managers: `prepare_core` yields the core's inbound port, and `prepare_rest_app` and `prepare_event_subscriber` build on it ([Dependency Injection](https://ghga-de.github.io/ghga/hexkit/user-guide/arch_concepts/dependency_injection.md)).
36
+ No dependency injection framework.
37
+ - Open every provider that holds a connection with `async with Provider.construct(config=...)`, once per process, and share it within that process; one `MongoDbDaoFactory` serves every DAO.
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
+ - Each entrypoint creates the config, calls `configure_logging` exactly once (a second call duplicates every line), and uses one prepare function.
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)).
43
+
44
+ ## Configuration
45
+
46
+ - One config class inherits every hexkit config it needs (`KafkaConfig`, `MongoDbConfig` or `MigrationConfig`, `LoggingConfig`, `OpenTelemetryConfig`) plus the service's own fields ([Configuration](https://ghga-de.github.io/ghga/hexkit/user-guide/configuration.md)).
47
+ - Decorate it with `@config_from_yaml(prefix="my_service")` and always pass the prefix: it names `.my_service.yaml` and prefixes every environment variable (`MY_SERVICE_KAFKA_SERVERS`).
48
+ A wrong prefix or casing fails silently, and the setting keeps its default.
49
+ - The resulting config is frozen; in tests, build a new instance instead of assigning to a field.
50
+ - Declare credentials as `SecretStr` or `Secret[...]`, or they appear in the config dump `configure_logging` writes at startup.
51
+ - Keep topic and event-type names in config fields, not literals in code.
52
+
53
+ ## DAOs
54
+
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.
56
+ - `insert` fails on an existing ID, `update` and `delete` on a missing one; use `upsert` only where create-or-replace is meant.
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=`.
60
+ - `find_all` is not awaited: it returns a lazy `FindResult` with `to_list()` and `total_count()`.
61
+ Always pass `sort` with `skip` and `limit`.
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.
63
+ - MongoDB keeps milliseconds: create timestamps with `hexkit.utils.now_utc_ms_prec()`, timezone-aware, or a value read back no longer equals the one written.
64
+ - MongoDB query operators (`{"$gt": 3}`) tie the caller to MongoDB; keep them in the outbound adapter.
65
+ - Declare indexes with `MongoDbIndex` in `get_dao(indexes=...)`, using model field names, never `_id`.
66
+ - Catch the `DaoError` subclasses (`ResourceNotFoundError`, ...) in the adapter and raise the core's own errors.
67
+ `with_transaction()` is not implemented by any provider yet.
68
+
69
+ ## Events
70
+
71
+ - Topic, type and key are ASCII; make the key the ID of the affected resource, since order holds per key.
72
+ - `publish()` returns once the broker has the event; a `KafkaEventPublisher` keeps no record of it, so use a persistent or outbox publisher where events must be re-emittable.
73
+ - A subscriber translator sets `topics_of_interest` and `types_of_interest` and implements `_consume_validated()`: validate the payload with a Pydantic model and raise `self.MalformedPayloadError` when it does not fit.
74
+ - Delivery is at least once, so every translator is idempotent.
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)).
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)).
78
+ - One subscriber takes one translator; combine several, outbox translators included, with `ComboTranslator`.
79
+ - `service_name` is the consumer group, so all instances of a service share the events.
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)).
81
+
82
+ ## The outbox
83
+
84
+ - A `DaoPublisher` is used like a DAO; each write publishes the resource's latest state as an `upserted` event, each delete a `deleted` event with an empty payload, keyed by the ID.
85
+ - `dto_to_event` decides what leaves the service: drop internal fields there, or return `None` to publish nothing for that change.
86
+ Use one topic per resource type.
87
+ - A deleted resource keeps a stub with a `__metadata__` field in the collection; read and write it only through the DAO.
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.
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)).
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.
95
+ - On the consuming side, implement `changed()` as an upsert and let `deleted()` accept a resource that is already gone.
96
+
97
+ ## Migrations
98
+
99
+ - Version 1 is reserved for the framework, so the first migration a service writes is version 2.
100
+ - Inherit the service config from `MigrationConfig`, map each version to its `MigrationDefinition` in a migration map, and run `MigrationManager(...).migrate_or_wait()` before the service starts work; a separate command, such as an init container, keeps migration failures apart.
101
+ - When the migration runs separately, the service checks with `check_db_version()` at startup and refuses a database that is behind or ahead.
102
+ - Implement `unapply()` (the `Reversible` mixin) unless the migration drops data that it cannot restore.
103
+
104
+ ## Tests
105
+
106
+ - Test the core without infrastructure: a mock DAO class from `new_mock_dao_class(dto_model=..., id_field=...)`, which understands a subset of MongoDB's operators, `InMemEventPublisher` (its `event_store.get(topic)` raises `TopicExhaustedError` when nothing was published) and the `InMem*KeyValueStore` classes.
107
+ - Test a translator by calling its `consume()` directly; test a REST route through the prepare function's override with an `AsyncMock` core.
108
+ - Test adapters against real backends with the testcontainers fixtures, which need Docker.
109
+ Import the session-scoped container fixture and the function-scoped fixture together, each with `# noqa: F401`, for example `mongodb_container_fixture` and `mongodb_fixture` from `hexkit.providers.mongodb.testutils`, then take `mongodb: MongoDbFixture` (its `dao_factory`), `kafka: KafkaFixture` or `s3: S3Fixture` as a test argument.
110
+ The `get_*_fixture()` functions build the same fixtures with another scope or name.
111
+ - With `KafkaFixture`, feed events in with `publish_event()` and check what the code publishes with `expect_events()` (exact count and order) or `record_events()`; `run(forever=False)` consumes one event and waits until one arrives, so publish first ([Kafka Test Utils](https://ghga-de.github.io/ghga/hexkit/user-guide/providers/kafka/test_utils.md)).
112
+ - The clean fixtures empty their backend before every test; the `persistent_*` variants keep state across tests.
@@ -17,7 +17,7 @@
17
17
  """Configurable logging tools with JSON output."""
18
18
 
19
19
  import json
20
- from datetime import datetime, timezone
20
+ from datetime import UTC, datetime
21
21
  from logging import Formatter, Logger, LogRecord, StreamHandler, addLevelName, getLogger
22
22
  from typing import Any, Literal
23
23
 
@@ -150,7 +150,7 @@ class RecordCompiler(StreamHandler):
150
150
  """Set custom record attributes"""
151
151
  log_record = record.__dict__
152
152
  timestamp = datetime.fromtimestamp(log_record["created"])
153
- timestamp = timestamp.astimezone(timezone.utc)
153
+ timestamp = timestamp.astimezone(UTC)
154
154
  iso_timestamp = timestamp.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
155
155
  extras = {
156
156
  key: value
@@ -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.resources import SERVICE_NAME, Resource
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 = Resource(attributes={SERVICE_NAME: service_name})
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()