irmy-common 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.
- irmy_common-1.0.0/LICENSE +21 -0
- irmy_common-1.0.0/PKG-INFO +342 -0
- irmy_common-1.0.0/README.md +304 -0
- irmy_common-1.0.0/irmy_common/__init__.py +4 -0
- irmy_common-1.0.0/irmy_common/_config.py +183 -0
- irmy_common-1.0.0/irmy_common/_logger.py +66 -0
- irmy_common-1.0.0/irmy_common/_models.py +125 -0
- irmy_common-1.0.0/irmy_common/_redis_client.py +129 -0
- irmy_common-1.0.0/irmy_common/exceptions.py +49 -0
- irmy_common-1.0.0/irmy_common/jwt_dependencies.py +215 -0
- irmy_common-1.0.0/irmy_common/metrics.py +49 -0
- irmy_common-1.0.0/irmy_common/openapi.py +124 -0
- irmy_common-1.0.0/irmy_common/py.typed +0 -0
- irmy_common-1.0.0/irmy_common/response_codes.py +39 -0
- irmy_common-1.0.0/irmy_common/responses.py +37 -0
- irmy_common-1.0.0/irmy_common/validation.py +95 -0
- irmy_common-1.0.0/irmy_common.egg-info/PKG-INFO +342 -0
- irmy_common-1.0.0/irmy_common.egg-info/SOURCES.txt +28 -0
- irmy_common-1.0.0/irmy_common.egg-info/dependency_links.txt +1 -0
- irmy_common-1.0.0/irmy_common.egg-info/requires.txt +13 -0
- irmy_common-1.0.0/irmy_common.egg-info/top_level.txt +1 -0
- irmy_common-1.0.0/pyproject.toml +59 -0
- irmy_common-1.0.0/setup.cfg +4 -0
- irmy_common-1.0.0/tests/test_config.py +219 -0
- irmy_common-1.0.0/tests/test_jwt_dependencies.py +167 -0
- irmy_common-1.0.0/tests/test_logger.py +22 -0
- irmy_common-1.0.0/tests/test_metrics.py +37 -0
- irmy_common-1.0.0/tests/test_openapi.py +86 -0
- irmy_common-1.0.0/tests/test_redis_client.py +148 -0
- irmy_common-1.0.0/tests/test_validation.py +110 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bendyna V. S.R.L.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: irmy-common
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Common building blocks for IRMy Python services: config, logging, Redis client, JWT auth and FastAPI error handling
|
|
5
|
+
Author-email: "Bendyna V. S.R.L." <info@irmy.tech>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://irmy.tech
|
|
8
|
+
Project-URL: Documentation, https://irmy.tech/docs/
|
|
9
|
+
Project-URL: Source, https://github.com/IRMy-tech/irmy-common
|
|
10
|
+
Project-URL: Issues, https://github.com/IRMy-tech/irmy-common/issues
|
|
11
|
+
Project-URL: Changelog, https://github.com/IRMy-tech/irmy-common/blob/main/CHANGELOG.md
|
|
12
|
+
Keywords: irmy,fastapi,config,jwt,redis,logging,prometheus
|
|
13
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Framework :: FastAPI
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: fastapi<1,>=0.141.1
|
|
26
|
+
Requires-Dist: starlette<2,>=1.3.1
|
|
27
|
+
Requires-Dist: PyJWT[crypto]<3,>=2.13.0
|
|
28
|
+
Requires-Dist: cryptography>=50.0.0
|
|
29
|
+
Requires-Dist: pydantic<3,>=2.13.5
|
|
30
|
+
Requires-Dist: httpx<1,>=0.28.1
|
|
31
|
+
Requires-Dist: PyYAML<7,>=6.0.3
|
|
32
|
+
Requires-Dist: redis<8,>=7.4.1
|
|
33
|
+
Requires-Dist: prometheus-client<1,>=0.26.0
|
|
34
|
+
Provides-Extra: test
|
|
35
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
36
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == "test"
|
|
37
|
+
Dynamic: license-file
|
|
38
|
+
|
|
39
|
+
# irmy-common
|
|
40
|
+
|
|
41
|
+
Common building blocks for IRMy Python services: configuration, logging, an async Redis
|
|
42
|
+
client, FastAPI JWT authentication and standard API error/response handling.
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install irmy-common
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Requires Python 3.12+. The import package is `irmy_common`.
|
|
49
|
+
|
|
50
|
+
Contents:
|
|
51
|
+
* [Logging](#logging)
|
|
52
|
+
* [Config Usage](#class-config-usage)
|
|
53
|
+
* [Redis client](#redis-client)
|
|
54
|
+
* [JWT dependencies](#jwt-dependencies)
|
|
55
|
+
* [Exceptions](#exceptions)
|
|
56
|
+
* [OpenAPI documentation](#openapi-documentation)
|
|
57
|
+
* [Input validation](#input-validation)
|
|
58
|
+
* [Metrics](#metrics)
|
|
59
|
+
|
|
60
|
+
## Usage
|
|
61
|
+
|
|
62
|
+
### Logging
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import uuid
|
|
66
|
+
from irmy_common import get_logger
|
|
67
|
+
|
|
68
|
+
logger = get_logger(log_level="DEBUG",
|
|
69
|
+
name="app_logger",
|
|
70
|
+
app_name="my-application",
|
|
71
|
+
app_id=str(uuid.uuid4()))
|
|
72
|
+
logger.info("Some info message")
|
|
73
|
+
logger.error("Some error message")
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### class Config usage
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from irmy_common import Config
|
|
80
|
+
|
|
81
|
+
config = Config()
|
|
82
|
+
|
|
83
|
+
# Get PostgreSQL URL
|
|
84
|
+
print(config.get_postgres_url())
|
|
85
|
+
|
|
86
|
+
# Specific component property
|
|
87
|
+
print(config.postgres_schema)
|
|
88
|
+
|
|
89
|
+
# Specific secret:
|
|
90
|
+
print(config.hmac_secret)
|
|
91
|
+
|
|
92
|
+
# RabbitMQ exchange to publish/consume on
|
|
93
|
+
print(config.rabbitmq_exchange_name)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`Config` reads `global_config.yaml` (path from `CONFIG_LOCATION`, default `/global_config.yaml`),
|
|
97
|
+
secret files (directory from `SECRETS_LOCATION`, default `/var/run`) and environment variables.
|
|
98
|
+
Precedence for every field: **env var > YAML/secret file > default**.
|
|
99
|
+
|
|
100
|
+
| Field | YAML key / secret file | Env var | Default |
|
|
101
|
+
|---|---|---|---|
|
|
102
|
+
| Public host | `irmyHost` | `IRMY_HOST` | required |
|
|
103
|
+
| Public protocol | `irmyProtocol` | `IRMY_PROTOCOL` | `https` |
|
|
104
|
+
| PostgreSQL | `postgreSQLHost`, `postgreSQLPort`, `postgreSQLDatabaseName`, `postgreSQLSchemaName` | `POSTGRESQL_HOST`, `POSTGRESQL_PORT`, `POSTGRESQL_DATABASE`, `POSTGRESQL_SCHEMA` | host required, `5432`, `irmy`, `public` |
|
|
105
|
+
| RabbitMQ | `rabbitmqHost`, `rabbitmqPort`, `rabbitmqVHost`, `rabbitmqExchangeName` | `RABBITMQ_HOST`, `RABBITMQ_PORT`, `RABBITMQ_VHOST`, `RABBITMQ_EXCHANGE_NAME` | host required, `5672`, `/`, exchange required |
|
|
106
|
+
| Redis | `redisHost`, `redisPort` | `REDIS_HOST`, `REDIS_PORT` | host required, `6379` |
|
|
107
|
+
| Secrets | `postgreSQLUser`, `postgreSQLPassword`, `rabbitUser`, `rabbitPassword`, `redisUser`, `redisPassword`, `jwtPrivateKey`, `jwtPublicKey`, `encryptionKey`, `hmacSecret` (files) | upper snake case, e.g. `POSTGRESQL_PASSWORD`, `RABBITMQ_USER`, `HMAC_SECRET` | none |
|
|
108
|
+
| Service | — | `APP_PORT`, `LOG_LEVEL`, `PLATFORM_VERSION`, `CHART_VERSION` | `80`, `INFO`, required, none |
|
|
109
|
+
|
|
110
|
+
The RabbitMQ vhost is used as given (`dev` and `/dev` are two different vhosts) and is
|
|
111
|
+
percent-encoded in `get_rabbit_url()` (`/` becomes `%2F`). An empty `RABBITMQ_VHOST` counts as
|
|
112
|
+
not set. Loading fails when the resulting vhost is empty or starts or ends with whitespace.
|
|
113
|
+
Only the `rabbitmqVHost` key is read.
|
|
114
|
+
|
|
115
|
+
The service version is read from `version=<x.y.z>` in `Release.txt` in the working directory.
|
|
116
|
+
|
|
117
|
+
#### Garbage collection
|
|
118
|
+
|
|
119
|
+
`config.garbage_collection` is the optional `garbageCollection` block, read from the YAML only —
|
|
120
|
+
no environment variable overrides it. Without the block it is disabled with the defaults below.
|
|
121
|
+
|
|
122
|
+
```yaml
|
|
123
|
+
garbageCollection:
|
|
124
|
+
enabled: true # default false
|
|
125
|
+
schedule: "0 3 * * *" # 5-field cron, UTC
|
|
126
|
+
batchSize: 5000 # 100..50000 rows per delete
|
|
127
|
+
maxDurationMinutes: 20 # 1..25, time budget of one run
|
|
128
|
+
retentionMonths: # a missing key = that data is never purged
|
|
129
|
+
alerts: 12
|
|
130
|
+
incidents: 24
|
|
131
|
+
auditLog: 36
|
|
132
|
+
onCall: 12
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Redis client
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
import uuid
|
|
139
|
+
from irmy_common import RedisClient, Config, get_logger
|
|
140
|
+
|
|
141
|
+
# Create logger instance
|
|
142
|
+
logger = get_logger(log_level="DEBUG",
|
|
143
|
+
name="app_logger",
|
|
144
|
+
app_name="my-application",
|
|
145
|
+
app_id=str(uuid.uuid4()))
|
|
146
|
+
|
|
147
|
+
config = Config()
|
|
148
|
+
redis_client = RedisClient(url=config.get_redis_url(), logger=logger)
|
|
149
|
+
|
|
150
|
+
async def main():
|
|
151
|
+
await redis_client.put(key="test", value="test", expire=10)
|
|
152
|
+
await redis_client.get("test")
|
|
153
|
+
await redis_client.healthcheck()
|
|
154
|
+
await redis_client.disconnect()
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Streams (`XADD` / `XTRIM` / `XRANGE`):
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
from irmy_common import StreamBatch
|
|
161
|
+
|
|
162
|
+
async def logs():
|
|
163
|
+
# one MULTI/EXEC: keep the last 1000 entries, none older than the given id
|
|
164
|
+
ok = await redis_client.stream_add([
|
|
165
|
+
StreamBatch("pluginLogs:slack", [{"level": "ERROR", "message": "boom"}],
|
|
166
|
+
max_len=1000, min_id="1760430000000-0"),
|
|
167
|
+
]) # False if Redis failed even after reconnecting
|
|
168
|
+
newest = await redis_client.stream_range("pluginLogs:slack", count=100, reverse=True)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### JWT dependencies
|
|
172
|
+
During start of the application:
|
|
173
|
+
|
|
174
|
+
```python
|
|
175
|
+
import uuid
|
|
176
|
+
from irmy_common import jwt_dependencies, Config, RedisClient, get_logger
|
|
177
|
+
|
|
178
|
+
logger = get_logger(log_level="DEBUG",
|
|
179
|
+
name="app_logger",
|
|
180
|
+
app_name="my-application",
|
|
181
|
+
app_id=str(uuid.uuid4()))
|
|
182
|
+
config = Config()
|
|
183
|
+
redis_client = RedisClient(url=config.get_redis_url(), logger=logger)
|
|
184
|
+
|
|
185
|
+
jwt_dependencies.init_dependencies(logger=logger, config=config, redis_client=redis_client)
|
|
186
|
+
```
|
|
187
|
+
Then, in your API endpoints:
|
|
188
|
+
```python
|
|
189
|
+
from fastapi import Depends
|
|
190
|
+
from irmy_common.jwt_dependencies import JWTData, verify_jwt, GlobalPermission
|
|
191
|
+
|
|
192
|
+
async def my_api(jwt_data: JWTData = Depends(verify_jwt)):
|
|
193
|
+
print(f"{jwt_data.requester} requests something")
|
|
194
|
+
print(f"Permissions: {jwt_data.Permissions}")
|
|
195
|
+
print(f"Does user has write permissions to Applications: {jwt_data.has_permission(GlobalPermission.MANAGE_SERVICES_APPS_ENVS)}")
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
### Exceptions
|
|
199
|
+
|
|
200
|
+
Raise HTTP Exception:
|
|
201
|
+
```python
|
|
202
|
+
from irmy_common.exceptions import IrmyHTTPException
|
|
203
|
+
from irmy_common.response_codes import ApiErrorCodes
|
|
204
|
+
|
|
205
|
+
raise IrmyHTTPException(status_code=ApiErrorCodes.BAD_REQUEST, message="Bad request")
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Raise general exception:
|
|
209
|
+
```python
|
|
210
|
+
from irmy_common.exceptions import IrmyException
|
|
211
|
+
|
|
212
|
+
raise IrmyException(message="Some exception")
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
Register API exceptions handlers
|
|
216
|
+
```python
|
|
217
|
+
from fastapi import FastAPI
|
|
218
|
+
from irmy_common.exceptions import register_exceptions_handler
|
|
219
|
+
|
|
220
|
+
app = FastAPI()
|
|
221
|
+
register_exceptions_handler(app)
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Usage of API response for CREATE, UPDATE and DELETE actions:
|
|
225
|
+
|
|
226
|
+
```python
|
|
227
|
+
import uuid
|
|
228
|
+
from fastapi import FastAPI
|
|
229
|
+
from irmy_common.responses import basic_http_response
|
|
230
|
+
from irmy_common.response_codes import ApiResponseCodes, COMMON_RESPONSES, COMMON_UPDATE_RESPONSES, COMMON_CREATE_RESPONSES
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
app = FastAPI()
|
|
234
|
+
|
|
235
|
+
@app.post("/update", responses={**COMMON_RESPONSES, **COMMON_UPDATE_RESPONSES})
|
|
236
|
+
async def do_update_request():
|
|
237
|
+
return basic_http_response(response_code=ApiResponseCodes.UPDATE_DELETE)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
@app.post("/create_one", responses={**COMMON_RESPONSES, **COMMON_CREATE_RESPONSES})
|
|
241
|
+
async def do_create_request():
|
|
242
|
+
return basic_http_response(response_code=ApiResponseCodes.CREATE, resource_id=uuid.uuid4())
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
@app.post("/create_many", responses={**COMMON_RESPONSES, **COMMON_CREATE_RESPONSES})
|
|
246
|
+
async def create_many_resources():
|
|
247
|
+
return basic_http_response(response_code=ApiResponseCodes.CREATE, many_resource_ids=[uuid.uuid4()])
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
### OpenAPI documentation
|
|
251
|
+
|
|
252
|
+
Helpers for the platform standard "API documentation (OpenAPI)" (Confluence INF →
|
|
253
|
+
Standards). Declare exactly the error codes an endpoint returns; each gets the
|
|
254
|
+
body schema (`ErrorResponse`, or `ValidationErrorResponse` for 400), a description
|
|
255
|
+
and an example. `configure_openapi` removes FastAPI's auto-generated 422 response,
|
|
256
|
+
because validation errors are returned as 400 by `register_exceptions_handler`.
|
|
257
|
+
|
|
258
|
+
```python
|
|
259
|
+
from fastapi import FastAPI
|
|
260
|
+
from irmy_common.exceptions import register_exceptions_handler
|
|
261
|
+
from irmy_common.openapi import configure_openapi, error_responses
|
|
262
|
+
from irmy_common.responses import CreateResourceModel
|
|
263
|
+
|
|
264
|
+
app = FastAPI(title="Application management", version="1.2.3")
|
|
265
|
+
register_exceptions_handler(app)
|
|
266
|
+
configure_openapi(app)
|
|
267
|
+
|
|
268
|
+
@app.post(
|
|
269
|
+
"/api/v1/services/",
|
|
270
|
+
operation_id="create_service",
|
|
271
|
+
summary="Create a service",
|
|
272
|
+
description="Creates a service. The name must be unique.",
|
|
273
|
+
status_code=201,
|
|
274
|
+
response_model=CreateResourceModel,
|
|
275
|
+
responses=error_responses(400, 401, 403, 409, 500,
|
|
276
|
+
descriptions={409: "A service with this name already exists"}),
|
|
277
|
+
)
|
|
278
|
+
async def create_service(body: CreateServiceRequest): ...
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
`COMMON_RESPONSES`, `COMMON_CREATE_RESPONSES`, `COMMON_UPDATE_RESPONSES` and
|
|
282
|
+
`COMMON_DELETE_RESPONSES` carry the same schemas, but they are legacy: they may
|
|
283
|
+
declare codes an endpoint never returns.
|
|
284
|
+
|
|
285
|
+
### Input validation
|
|
286
|
+
|
|
287
|
+
Constrained types for request models, per "User input validation" (Confluence
|
|
288
|
+
INF). Strings are trimmed before validation, so a whitespace-only value is empty
|
|
289
|
+
and fails where a value is required. Violations are returned as 400 with
|
|
290
|
+
`{error, details}`, and the constraints appear in the OpenAPI schema.
|
|
291
|
+
|
|
292
|
+
```python
|
|
293
|
+
from pydantic import BaseModel
|
|
294
|
+
from irmy_common.validation import Tags, TimeZoneName, name_str, text_str
|
|
295
|
+
|
|
296
|
+
class CreateServiceRequest(BaseModel):
|
|
297
|
+
serviceName: name_str(128) # A-Za-z0-9_- and spaces, 1..128
|
|
298
|
+
serviceDescription: text_str(512) | None = None
|
|
299
|
+
tags: Tags | None = None # <= 10 entries, key A-Za-z0-9_- <= 64, value <= 256
|
|
300
|
+
timezone: TimeZoneName | None = None # IANA time zone, e.g. "Europe/Kyiv"
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
| Type | Rule |
|
|
304
|
+
|---|---|
|
|
305
|
+
| `name_str(n)` | `A-Za-z0-9_-` and spaces, 1..n characters |
|
|
306
|
+
| `text_str(n, required=False)` | any characters, up to n (at least 1 if `required`); NUL and lone surrogates are written out as `\u0000` text |
|
|
307
|
+
| `key_str(n=64)` | `A-Za-z0-9_-`, 1..n characters |
|
|
308
|
+
| `Tags` | up to 10 entries, `key_str(64)` keys, `text_str(256)` values |
|
|
309
|
+
| `TimeZoneName` | a valid IANA time zone name |
|
|
310
|
+
|
|
311
|
+
PostgreSQL cannot store NUL (`\u0000`) or a lone UTF-16 surrogate (`\ud800`..`\udfff`).
|
|
312
|
+
`storable_text(value)` replaces each with its escape written out as text (`"a\x00b"` →
|
|
313
|
+
`"a\\u0000b"`), so the value is saved and shows what was sent; `storable(value)` does the
|
|
314
|
+
same for every string of a JSON-like value, dict keys included. `text_str` applies it before
|
|
315
|
+
trimming and the length check.
|
|
316
|
+
|
|
317
|
+
```python
|
|
318
|
+
from irmy_common.validation import storable
|
|
319
|
+
|
|
320
|
+
body = storable(json.loads(raw)) # webhook body / event payload, ready for the database
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
### Metrics
|
|
324
|
+
|
|
325
|
+
Service-level metrics, registered in the default `prometheus_client` registry, so
|
|
326
|
+
they are served by the service's `/metrics` endpoint together with the HTTP
|
|
327
|
+
metrics of the instrumentator and the metrics of irmy-messaging / irmy-db.
|
|
328
|
+
Call once at startup; repeated calls are safe.
|
|
329
|
+
|
|
330
|
+
```python
|
|
331
|
+
from irmy_common import Config
|
|
332
|
+
from irmy_common.metrics import register_build_info, set_up
|
|
333
|
+
|
|
334
|
+
config = Config()
|
|
335
|
+
register_build_info(config, service_name="my-service")
|
|
336
|
+
set_up(True) # and set_up(False) on shutdown
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
| Metric | Type | Labels |
|
|
340
|
+
|---|---|---|
|
|
341
|
+
| `irmy_build_info` | Gauge, always `1` | `service`, `version`, `platform_version`, `chart_version` (empty when not set) |
|
|
342
|
+
| `irmy_up` | Gauge, `1` / `0` | — |
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
# irmy-common
|
|
2
|
+
|
|
3
|
+
Common building blocks for IRMy Python services: configuration, logging, an async Redis
|
|
4
|
+
client, FastAPI JWT authentication and standard API error/response handling.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pip install irmy-common
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Requires Python 3.12+. The import package is `irmy_common`.
|
|
11
|
+
|
|
12
|
+
Contents:
|
|
13
|
+
* [Logging](#logging)
|
|
14
|
+
* [Config Usage](#class-config-usage)
|
|
15
|
+
* [Redis client](#redis-client)
|
|
16
|
+
* [JWT dependencies](#jwt-dependencies)
|
|
17
|
+
* [Exceptions](#exceptions)
|
|
18
|
+
* [OpenAPI documentation](#openapi-documentation)
|
|
19
|
+
* [Input validation](#input-validation)
|
|
20
|
+
* [Metrics](#metrics)
|
|
21
|
+
|
|
22
|
+
## Usage
|
|
23
|
+
|
|
24
|
+
### Logging
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
import uuid
|
|
28
|
+
from irmy_common import get_logger
|
|
29
|
+
|
|
30
|
+
logger = get_logger(log_level="DEBUG",
|
|
31
|
+
name="app_logger",
|
|
32
|
+
app_name="my-application",
|
|
33
|
+
app_id=str(uuid.uuid4()))
|
|
34
|
+
logger.info("Some info message")
|
|
35
|
+
logger.error("Some error message")
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### class Config usage
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from irmy_common import Config
|
|
42
|
+
|
|
43
|
+
config = Config()
|
|
44
|
+
|
|
45
|
+
# Get PostgreSQL URL
|
|
46
|
+
print(config.get_postgres_url())
|
|
47
|
+
|
|
48
|
+
# Specific component property
|
|
49
|
+
print(config.postgres_schema)
|
|
50
|
+
|
|
51
|
+
# Specific secret:
|
|
52
|
+
print(config.hmac_secret)
|
|
53
|
+
|
|
54
|
+
# RabbitMQ exchange to publish/consume on
|
|
55
|
+
print(config.rabbitmq_exchange_name)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
`Config` reads `global_config.yaml` (path from `CONFIG_LOCATION`, default `/global_config.yaml`),
|
|
59
|
+
secret files (directory from `SECRETS_LOCATION`, default `/var/run`) and environment variables.
|
|
60
|
+
Precedence for every field: **env var > YAML/secret file > default**.
|
|
61
|
+
|
|
62
|
+
| Field | YAML key / secret file | Env var | Default |
|
|
63
|
+
|---|---|---|---|
|
|
64
|
+
| Public host | `irmyHost` | `IRMY_HOST` | required |
|
|
65
|
+
| Public protocol | `irmyProtocol` | `IRMY_PROTOCOL` | `https` |
|
|
66
|
+
| PostgreSQL | `postgreSQLHost`, `postgreSQLPort`, `postgreSQLDatabaseName`, `postgreSQLSchemaName` | `POSTGRESQL_HOST`, `POSTGRESQL_PORT`, `POSTGRESQL_DATABASE`, `POSTGRESQL_SCHEMA` | host required, `5432`, `irmy`, `public` |
|
|
67
|
+
| RabbitMQ | `rabbitmqHost`, `rabbitmqPort`, `rabbitmqVHost`, `rabbitmqExchangeName` | `RABBITMQ_HOST`, `RABBITMQ_PORT`, `RABBITMQ_VHOST`, `RABBITMQ_EXCHANGE_NAME` | host required, `5672`, `/`, exchange required |
|
|
68
|
+
| Redis | `redisHost`, `redisPort` | `REDIS_HOST`, `REDIS_PORT` | host required, `6379` |
|
|
69
|
+
| Secrets | `postgreSQLUser`, `postgreSQLPassword`, `rabbitUser`, `rabbitPassword`, `redisUser`, `redisPassword`, `jwtPrivateKey`, `jwtPublicKey`, `encryptionKey`, `hmacSecret` (files) | upper snake case, e.g. `POSTGRESQL_PASSWORD`, `RABBITMQ_USER`, `HMAC_SECRET` | none |
|
|
70
|
+
| Service | — | `APP_PORT`, `LOG_LEVEL`, `PLATFORM_VERSION`, `CHART_VERSION` | `80`, `INFO`, required, none |
|
|
71
|
+
|
|
72
|
+
The RabbitMQ vhost is used as given (`dev` and `/dev` are two different vhosts) and is
|
|
73
|
+
percent-encoded in `get_rabbit_url()` (`/` becomes `%2F`). An empty `RABBITMQ_VHOST` counts as
|
|
74
|
+
not set. Loading fails when the resulting vhost is empty or starts or ends with whitespace.
|
|
75
|
+
Only the `rabbitmqVHost` key is read.
|
|
76
|
+
|
|
77
|
+
The service version is read from `version=<x.y.z>` in `Release.txt` in the working directory.
|
|
78
|
+
|
|
79
|
+
#### Garbage collection
|
|
80
|
+
|
|
81
|
+
`config.garbage_collection` is the optional `garbageCollection` block, read from the YAML only —
|
|
82
|
+
no environment variable overrides it. Without the block it is disabled with the defaults below.
|
|
83
|
+
|
|
84
|
+
```yaml
|
|
85
|
+
garbageCollection:
|
|
86
|
+
enabled: true # default false
|
|
87
|
+
schedule: "0 3 * * *" # 5-field cron, UTC
|
|
88
|
+
batchSize: 5000 # 100..50000 rows per delete
|
|
89
|
+
maxDurationMinutes: 20 # 1..25, time budget of one run
|
|
90
|
+
retentionMonths: # a missing key = that data is never purged
|
|
91
|
+
alerts: 12
|
|
92
|
+
incidents: 24
|
|
93
|
+
auditLog: 36
|
|
94
|
+
onCall: 12
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### Redis client
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
import uuid
|
|
101
|
+
from irmy_common import RedisClient, Config, get_logger
|
|
102
|
+
|
|
103
|
+
# Create logger instance
|
|
104
|
+
logger = get_logger(log_level="DEBUG",
|
|
105
|
+
name="app_logger",
|
|
106
|
+
app_name="my-application",
|
|
107
|
+
app_id=str(uuid.uuid4()))
|
|
108
|
+
|
|
109
|
+
config = Config()
|
|
110
|
+
redis_client = RedisClient(url=config.get_redis_url(), logger=logger)
|
|
111
|
+
|
|
112
|
+
async def main():
|
|
113
|
+
await redis_client.put(key="test", value="test", expire=10)
|
|
114
|
+
await redis_client.get("test")
|
|
115
|
+
await redis_client.healthcheck()
|
|
116
|
+
await redis_client.disconnect()
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Streams (`XADD` / `XTRIM` / `XRANGE`):
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from irmy_common import StreamBatch
|
|
123
|
+
|
|
124
|
+
async def logs():
|
|
125
|
+
# one MULTI/EXEC: keep the last 1000 entries, none older than the given id
|
|
126
|
+
ok = await redis_client.stream_add([
|
|
127
|
+
StreamBatch("pluginLogs:slack", [{"level": "ERROR", "message": "boom"}],
|
|
128
|
+
max_len=1000, min_id="1760430000000-0"),
|
|
129
|
+
]) # False if Redis failed even after reconnecting
|
|
130
|
+
newest = await redis_client.stream_range("pluginLogs:slack", count=100, reverse=True)
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### JWT dependencies
|
|
134
|
+
During start of the application:
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
import uuid
|
|
138
|
+
from irmy_common import jwt_dependencies, Config, RedisClient, get_logger
|
|
139
|
+
|
|
140
|
+
logger = get_logger(log_level="DEBUG",
|
|
141
|
+
name="app_logger",
|
|
142
|
+
app_name="my-application",
|
|
143
|
+
app_id=str(uuid.uuid4()))
|
|
144
|
+
config = Config()
|
|
145
|
+
redis_client = RedisClient(url=config.get_redis_url(), logger=logger)
|
|
146
|
+
|
|
147
|
+
jwt_dependencies.init_dependencies(logger=logger, config=config, redis_client=redis_client)
|
|
148
|
+
```
|
|
149
|
+
Then, in your API endpoints:
|
|
150
|
+
```python
|
|
151
|
+
from fastapi import Depends
|
|
152
|
+
from irmy_common.jwt_dependencies import JWTData, verify_jwt, GlobalPermission
|
|
153
|
+
|
|
154
|
+
async def my_api(jwt_data: JWTData = Depends(verify_jwt)):
|
|
155
|
+
print(f"{jwt_data.requester} requests something")
|
|
156
|
+
print(f"Permissions: {jwt_data.Permissions}")
|
|
157
|
+
print(f"Does user has write permissions to Applications: {jwt_data.has_permission(GlobalPermission.MANAGE_SERVICES_APPS_ENVS)}")
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Exceptions
|
|
161
|
+
|
|
162
|
+
Raise HTTP Exception:
|
|
163
|
+
```python
|
|
164
|
+
from irmy_common.exceptions import IrmyHTTPException
|
|
165
|
+
from irmy_common.response_codes import ApiErrorCodes
|
|
166
|
+
|
|
167
|
+
raise IrmyHTTPException(status_code=ApiErrorCodes.BAD_REQUEST, message="Bad request")
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Raise general exception:
|
|
171
|
+
```python
|
|
172
|
+
from irmy_common.exceptions import IrmyException
|
|
173
|
+
|
|
174
|
+
raise IrmyException(message="Some exception")
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
Register API exceptions handlers
|
|
178
|
+
```python
|
|
179
|
+
from fastapi import FastAPI
|
|
180
|
+
from irmy_common.exceptions import register_exceptions_handler
|
|
181
|
+
|
|
182
|
+
app = FastAPI()
|
|
183
|
+
register_exceptions_handler(app)
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Usage of API response for CREATE, UPDATE and DELETE actions:
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
import uuid
|
|
190
|
+
from fastapi import FastAPI
|
|
191
|
+
from irmy_common.responses import basic_http_response
|
|
192
|
+
from irmy_common.response_codes import ApiResponseCodes, COMMON_RESPONSES, COMMON_UPDATE_RESPONSES, COMMON_CREATE_RESPONSES
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
app = FastAPI()
|
|
196
|
+
|
|
197
|
+
@app.post("/update", responses={**COMMON_RESPONSES, **COMMON_UPDATE_RESPONSES})
|
|
198
|
+
async def do_update_request():
|
|
199
|
+
return basic_http_response(response_code=ApiResponseCodes.UPDATE_DELETE)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@app.post("/create_one", responses={**COMMON_RESPONSES, **COMMON_CREATE_RESPONSES})
|
|
203
|
+
async def do_create_request():
|
|
204
|
+
return basic_http_response(response_code=ApiResponseCodes.CREATE, resource_id=uuid.uuid4())
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@app.post("/create_many", responses={**COMMON_RESPONSES, **COMMON_CREATE_RESPONSES})
|
|
208
|
+
async def create_many_resources():
|
|
209
|
+
return basic_http_response(response_code=ApiResponseCodes.CREATE, many_resource_ids=[uuid.uuid4()])
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
### OpenAPI documentation
|
|
213
|
+
|
|
214
|
+
Helpers for the platform standard "API documentation (OpenAPI)" (Confluence INF →
|
|
215
|
+
Standards). Declare exactly the error codes an endpoint returns; each gets the
|
|
216
|
+
body schema (`ErrorResponse`, or `ValidationErrorResponse` for 400), a description
|
|
217
|
+
and an example. `configure_openapi` removes FastAPI's auto-generated 422 response,
|
|
218
|
+
because validation errors are returned as 400 by `register_exceptions_handler`.
|
|
219
|
+
|
|
220
|
+
```python
|
|
221
|
+
from fastapi import FastAPI
|
|
222
|
+
from irmy_common.exceptions import register_exceptions_handler
|
|
223
|
+
from irmy_common.openapi import configure_openapi, error_responses
|
|
224
|
+
from irmy_common.responses import CreateResourceModel
|
|
225
|
+
|
|
226
|
+
app = FastAPI(title="Application management", version="1.2.3")
|
|
227
|
+
register_exceptions_handler(app)
|
|
228
|
+
configure_openapi(app)
|
|
229
|
+
|
|
230
|
+
@app.post(
|
|
231
|
+
"/api/v1/services/",
|
|
232
|
+
operation_id="create_service",
|
|
233
|
+
summary="Create a service",
|
|
234
|
+
description="Creates a service. The name must be unique.",
|
|
235
|
+
status_code=201,
|
|
236
|
+
response_model=CreateResourceModel,
|
|
237
|
+
responses=error_responses(400, 401, 403, 409, 500,
|
|
238
|
+
descriptions={409: "A service with this name already exists"}),
|
|
239
|
+
)
|
|
240
|
+
async def create_service(body: CreateServiceRequest): ...
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
`COMMON_RESPONSES`, `COMMON_CREATE_RESPONSES`, `COMMON_UPDATE_RESPONSES` and
|
|
244
|
+
`COMMON_DELETE_RESPONSES` carry the same schemas, but they are legacy: they may
|
|
245
|
+
declare codes an endpoint never returns.
|
|
246
|
+
|
|
247
|
+
### Input validation
|
|
248
|
+
|
|
249
|
+
Constrained types for request models, per "User input validation" (Confluence
|
|
250
|
+
INF). Strings are trimmed before validation, so a whitespace-only value is empty
|
|
251
|
+
and fails where a value is required. Violations are returned as 400 with
|
|
252
|
+
`{error, details}`, and the constraints appear in the OpenAPI schema.
|
|
253
|
+
|
|
254
|
+
```python
|
|
255
|
+
from pydantic import BaseModel
|
|
256
|
+
from irmy_common.validation import Tags, TimeZoneName, name_str, text_str
|
|
257
|
+
|
|
258
|
+
class CreateServiceRequest(BaseModel):
|
|
259
|
+
serviceName: name_str(128) # A-Za-z0-9_- and spaces, 1..128
|
|
260
|
+
serviceDescription: text_str(512) | None = None
|
|
261
|
+
tags: Tags | None = None # <= 10 entries, key A-Za-z0-9_- <= 64, value <= 256
|
|
262
|
+
timezone: TimeZoneName | None = None # IANA time zone, e.g. "Europe/Kyiv"
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
| Type | Rule |
|
|
266
|
+
|---|---|
|
|
267
|
+
| `name_str(n)` | `A-Za-z0-9_-` and spaces, 1..n characters |
|
|
268
|
+
| `text_str(n, required=False)` | any characters, up to n (at least 1 if `required`); NUL and lone surrogates are written out as `\u0000` text |
|
|
269
|
+
| `key_str(n=64)` | `A-Za-z0-9_-`, 1..n characters |
|
|
270
|
+
| `Tags` | up to 10 entries, `key_str(64)` keys, `text_str(256)` values |
|
|
271
|
+
| `TimeZoneName` | a valid IANA time zone name |
|
|
272
|
+
|
|
273
|
+
PostgreSQL cannot store NUL (`\u0000`) or a lone UTF-16 surrogate (`\ud800`..`\udfff`).
|
|
274
|
+
`storable_text(value)` replaces each with its escape written out as text (`"a\x00b"` →
|
|
275
|
+
`"a\\u0000b"`), so the value is saved and shows what was sent; `storable(value)` does the
|
|
276
|
+
same for every string of a JSON-like value, dict keys included. `text_str` applies it before
|
|
277
|
+
trimming and the length check.
|
|
278
|
+
|
|
279
|
+
```python
|
|
280
|
+
from irmy_common.validation import storable
|
|
281
|
+
|
|
282
|
+
body = storable(json.loads(raw)) # webhook body / event payload, ready for the database
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
### Metrics
|
|
286
|
+
|
|
287
|
+
Service-level metrics, registered in the default `prometheus_client` registry, so
|
|
288
|
+
they are served by the service's `/metrics` endpoint together with the HTTP
|
|
289
|
+
metrics of the instrumentator and the metrics of irmy-messaging / irmy-db.
|
|
290
|
+
Call once at startup; repeated calls are safe.
|
|
291
|
+
|
|
292
|
+
```python
|
|
293
|
+
from irmy_common import Config
|
|
294
|
+
from irmy_common.metrics import register_build_info, set_up
|
|
295
|
+
|
|
296
|
+
config = Config()
|
|
297
|
+
register_build_info(config, service_name="my-service")
|
|
298
|
+
set_up(True) # and set_up(False) on shutdown
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
| Metric | Type | Labels |
|
|
302
|
+
|---|---|---|
|
|
303
|
+
| `irmy_build_info` | Gauge, always `1` | `service`, `version`, `platform_version`, `chart_version` (empty when not set) |
|
|
304
|
+
| `irmy_up` | Gauge, `1` / `0` | — |
|