0
# Minos Microservice Networks
1
2
A comprehensive Python library providing networking core functionality for the Minos Framework. It implements components for building reactive microservices using Event Sourcing, CQRS, and message-driven architecture patterns.
3
4
## Package Information
5
6
- **Package Name**: minos-microservice-networks
7
- **Package Type**: pypi
8
- **Language**: Python 3.9+
9
- **Installation**: `pip install minos-microservice-networks`
10
- **License**: MIT
11
12
## Core Imports
13
14
```python
15
import minos.networks
16
```
17
18
Common import patterns:
19
20
```python
21
from minos.networks import (
22
enroute,
23
BrokerClient,
24
BrokerHandler,
25
HttpPort,
26
Request,
27
Response
28
)
29
```
30
31
For decorators:
32
33
```python
34
from minos.networks import enroute
35
36
# Use decorators
37
@enroute.broker.command("user.create")
38
@enroute.rest.query("/users", method="GET")
39
@enroute.periodic.event("0 */5 * * * *")
40
```
41
42
## Basic Usage
43
44
### Creating a Simple Microservice with Decorators
45
46
```python
47
from minos.networks import enroute, Request, Response
48
49
class UserService:
50
@enroute.broker.command("user.create")
51
async def create_user(self, request: Request) -> Response:
52
user_data = await request.content()
53
# Process user creation logic
54
return Response({"id": "123", "status": "created"})
55
56
@enroute.rest.query("/users/{user_id}", method="GET")
57
async def get_user(self, request: Request) -> Response:
58
params = await request.params()
59
user_id = params["user_id"]
60
# Fetch user logic
61
return Response({"id": user_id, "name": "John Doe"})
62
63
@enroute.periodic.event("0 */5 * * * *") # Every 5 minutes
64
async def cleanup_task(self, request: Request) -> Response:
65
# Periodic cleanup logic
66
return Response({"status": "cleanup_completed"})
67
```
68
69
### Setting up Broker Communication
70
71
```python
72
from minos.networks import BrokerClient, BrokerPublisher, BrokerSubscriber
73
from minos.common import Config
74
75
# Create configuration
76
config = Config("config.yml")
77
78
# Create broker client
79
client = BrokerClient.from_config(config, topic="my.topic")
80
81
# Send a message
82
message = BrokerMessageV1("user.created", payload=payload)
83
await client.send(message)
84
85
# Receive messages
86
async for message in client.receive_many(count=10):
87
print(f"Received: {message.content}")
88
```
89
90
### Setting up HTTP Services
91
92
```python
93
from minos.networks import HttpPort
94
from minos.common import Config
95
96
# Create HTTP port from configuration
97
config = Config("config.yml")
98
http_port = HttpPort.from_config(config)
99
100
# Start the HTTP server
101
await http_port.start()
102
```
103
104
## Architecture
105
106
The Minos Networks library implements a reactive microservices architecture with these key components:
107
108
- **Decorators**: The `enroute` system provides unified decorators for broker, HTTP, and periodic handlers
109
- **Message Brokers**: Publish/subscribe messaging with queuing, filtering, and validation
110
- **HTTP Services**: RESTful API support with request/response abstractions
111
- **Routing**: Smart routing based on decorator types and configurations
112
- **Scheduling**: Cron-based periodic task execution
113
- **Discovery**: Service registration and discovery mechanisms
114
115
The library follows reactive manifesto principles: responsive, resilient, elastic, and message-driven.
116
117
## Capabilities
118
119
### Decorators and Routing
120
121
The `enroute` decorator system provides unified handler registration for different transport types. Supports broker commands/queries/events, REST endpoints, and periodic tasks with automatic routing and middleware integration.
122
123
```python { .api }
124
class Enroute:
125
broker: BrokerEnroute
126
rest: RestEnroute
127
periodic: PeriodicEnroute
128
129
class BrokerEnroute:
130
command: type[BrokerCommandEnrouteDecorator]
131
query: type[BrokerQueryEnrouteDecorator]
132
event: type[BrokerEventEnrouteDecorator]
133
134
class RestEnroute:
135
command: type[RestCommandEnrouteDecorator]
136
query: type[RestQueryEnrouteDecorator]
137
138
class PeriodicEnroute:
139
event: type[PeriodicEventEnrouteDecorator]
140
141
enroute: Enroute
142
```
143
144
[Decorators and Routing](./decorators.md)
145
146
### Message Broker System
147
148
Comprehensive message broker implementation supporting publish/subscribe patterns, message queuing, filtering, validation, and multiple delivery strategies. Includes both in-memory and database-backed implementations.
149
150
```python { .api }
151
class BrokerClient:
152
def __init__(self, topic: str, publisher: BrokerPublisher, subscriber: BrokerSubscriber): ...
153
async def send(self, message: BrokerMessage) -> None: ...
154
async def receive(self) -> BrokerMessage: ...
155
async def receive_many(self, count: int, timeout: float = 60) -> AsyncIterator[BrokerMessage]: ...
156
157
class BrokerMessage:
158
topic: str
159
identifier: UUID
160
content: Any
161
headers: dict[str, str]
162
163
class BrokerHandler:
164
def __init__(self, dispatcher: BrokerDispatcher, subscriber: BrokerSubscriber, concurrency: int = 5): ...
165
async def run(self) -> NoReturn: ...
166
```
167
168
[Message Broker System](./brokers.md)
169
170
### HTTP Services
171
172
HTTP server functionality with REST support, request/response abstractions, routing, and connector patterns. Provides foundation for building HTTP APIs and web services.
173
174
```python { .api }
175
class HttpPort:
176
connector: HttpConnector
177
async def start(self) -> None: ...
178
async def stop(self) -> None: ...
179
180
class HttpRequest:
181
user: Optional[UUID]
182
headers: dict[str, str]
183
content_type: str
184
async def url_params(self, type_: Optional[type] = None) -> Any: ...
185
async def query_params(self, type_: Optional[type] = None) -> Any: ...
186
187
class HttpResponse:
188
def __init__(self, content_type: str = "application/json"): ...
189
status: int
190
async def content(self) -> Any: ...
191
```
192
193
[HTTP Services](./http.md)
194
195
### Request and Response Handling
196
197
Core request/response abstractions used across all transport types. Provides unified interfaces for handling different types of requests with content, parameters, and user context.
198
199
```python { .api }
200
class Request:
201
user: Optional[UUID]
202
has_content: bool
203
has_params: bool
204
async def content(self) -> Any: ...
205
async def params(self) -> dict[str, Any]: ...
206
207
class Response:
208
def __init__(self, data: Any = None, status: int = 200): ...
209
has_content: bool
210
status: int
211
async def content(self) -> Any: ...
212
213
class InMemoryRequest:
214
def __init__(self, content: Any = None, params: dict[str, Any] = None, user: Optional[UUID] = None): ...
215
```
216
217
[Request and Response Handling](./requests.md)
218
219
### Task Scheduling
220
221
Cron-based periodic task scheduling with async execution, lifecycle management, and integration with the decorator system. Supports complex scheduling patterns and error handling.
222
223
```python { .api }
224
class CronTab:
225
def __init__(self, pattern: Union[str, CrontTabImpl]): ...
226
repetitions: Union[int, float]
227
async def sleep_until_next(self) -> None: ...
228
get_delay_until_next(self, now: Optional[datetime] = None) -> float: ...
229
230
class PeriodicTask:
231
def __init__(self, crontab: Union[str, CronTab], fn: Callable): ...
232
crontab: CronTab
233
started: bool
234
running: bool
235
async def start(self) -> None: ...
236
async def stop(self, timeout: Optional[float] = None) -> None: ...
237
238
class PeriodicPort:
239
scheduler: PeriodicTaskScheduler
240
```
241
242
[Task Scheduling](./scheduling.md)
243
244
### Service Discovery
245
246
Service registration and discovery mechanisms for microservice coordination. Supports multiple discovery backends and automatic service lifecycle management.
247
248
```python { .api }
249
class DiscoveryClient:
250
def __init__(self, host: str, port: int): ...
251
route: str
252
async def subscribe(self, host: str, port: int, name: str, endpoints: list[dict]) -> None: ...
253
async def unsubscribe(self, name: str) -> None: ...
254
255
class DiscoveryConnector:
256
def __init__(self, client: DiscoveryClient, name: str, endpoints: list[dict], host: str, port: Optional[int] = None): ...
257
async def subscribe(self) -> None: ...
258
async def unsubscribe(self) -> None: ...
259
```
260
261
[Service Discovery](./discovery.md)
262
263
### API Specification Services
264
265
Built-in services for generating OpenAPI and AsyncAPI specifications from decorated handlers. Provides automated API documentation and specification generation.
266
267
```python { .api }
268
class OpenAPIService:
269
def __init__(self, config: Config): ...
270
spec: dict
271
async def generate_specification(self, request: Request) -> Response: ...
272
273
class AsyncAPIService:
274
def __init__(self, config: Config): ...
275
spec: dict
276
async def generate_specification(self, request: Request) -> Response: ...
277
```
278
279
[API Specification Services](./specs.md)
280
281
### System and Utilities
282
283
System health endpoints, network utilities, and various helper functions for microservice operations.
284
285
```python { .api }
286
class SystemService:
287
async def check_health(self, request: Request) -> Response: ...
288
289
def get_host_ip() -> str: ...
290
def get_host_name() -> str: ...
291
def get_ip(name: str) -> str: ...
292
async def consume_queue(queue, max_count: int) -> None: ...
293
```
294
295
[System and Utilities](./system-utils.md)
296
297
### Routing System
298
299
Abstract interfaces and concrete implementations for handling route registration and management across different transport types. Routers aggregate decorated handlers and provide structured access to routing information.
300
301
```python { .api }
302
class Router:
303
routes: dict[Any, Callable]
304
def build_routes(self) -> None: ...
305
def get_routes(self) -> dict[Any, Callable]: ...
306
307
class BrokerRouter(Router): ...
308
class HttpRouter(Router): ...
309
class RestHttpRouter(HttpRouter): ...
310
class PeriodicRouter(Router): ...
311
```
312
313
[Routing System](./routers.md)
314
315
## Types
316
317
### Core Types
318
319
```python { .api }
320
from typing import Callable, Union, Optional, Any, Awaitable
321
from uuid import UUID
322
from datetime import datetime
323
324
Handler = Callable[[Request], Union[Optional[Response], Awaitable[Optional[Response]]]]
325
Checker = Callable[[Request], Union[Optional[bool], Awaitable[Optional[bool]]]]
326
327
class BrokerMessageV1Status(Enum):
328
SUCCESS = 200
329
ERROR = 400
330
SYSTEM_ERROR = 500
331
UNKNOWN = 600
332
333
class BrokerMessageV1Strategy(Enum):
334
UNICAST = "unicast"
335
MULTICAST = "multicast"
336
337
class EnrouteDecoratorKind(Enum):
338
Command = auto()
339
Query = auto()
340
Event = auto()
341
```
342
343
### Context Variables
344
345
```python { .api }
346
from contextvars import ContextVar
347
348
REQUEST_USER_CONTEXT_VAR: ContextVar[Optional[UUID]]
349
REQUEST_HEADERS_CONTEXT_VAR: ContextVar[Optional[dict[str, str]]]
350
REQUEST_REPLY_TOPIC_CONTEXT_VAR: ContextVar[Optional[str]]
351
```
352
353
**Usage Examples:**
354
355
```python
356
from minos.networks import REQUEST_USER_CONTEXT_VAR, REQUEST_HEADERS_CONTEXT_VAR
357
358
# Context variables are automatically managed by the framework
359
# Access current request user in any handler
360
current_user = REQUEST_USER_CONTEXT_VAR.get()
361
request_headers = REQUEST_HEADERS_CONTEXT_VAR.get()
362
```
363
364
### Exception Types
365
366
```python { .api }
367
class MinosNetworkException(MinosException): ...
368
class MinosDiscoveryConnectorException(MinosNetworkException): ...
369
class MinosInvalidDiscoveryClient(MinosNetworkException): ...
370
class MinosHandlerException(MinosNetworkException): ...
371
class MinosActionNotFoundException(MinosHandlerException): ...
372
class MinosHandlerNotFoundEnoughEntriesException(MinosHandlerException): ...
373
class NotSatisfiedCheckerException(MinosHandlerException): ...
374
class MinosEnrouteDecoratorException(MinosNetworkException): ...
375
class MinosMultipleEnrouteDecoratorKindsException(MinosEnrouteDecoratorException): ...
376
class MinosRedefinedEnrouteDecoratorException(MinosEnrouteDecoratorException): ...
377
class RequestException(MinosNetworkException): ...
378
class NotHasContentException(RequestException): ...
379
class NotHasParamsException(RequestException): ...
380
class ResponseException(MinosException):
381
def __init__(self, status: int = 400): ...
382
status: int
383
```