aspyx-service 0.9.0__tar.gz → 0.10.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of aspyx-service might be problematic. Click here for more details.

@@ -0,0 +1,505 @@
1
+ Metadata-Version: 2.4
2
+ Name: aspyx_service
3
+ Version: 0.10.1
4
+ Summary: Aspyx Service framework
5
+ Author-email: Andreas Ernst <andreas.ernst7@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 Andreas Ernst
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ License-File: LICENSE
28
+ Requires-Python: >=3.9
29
+ Requires-Dist: aspyx>=1.5.0
30
+ Requires-Dist: fastapi~=0.115.13
31
+ Requires-Dist: httpx~=0.28.1
32
+ Requires-Dist: msgpack~=1.1.1
33
+ Requires-Dist: python-consul2~=0.1.5
34
+ Requires-Dist: uvicorn[standard]
35
+ Description-Content-Type: text/markdown
36
+
37
+ # Service
38
+
39
+ - [Introduction](#introduction)
40
+ - [Features](#features)
41
+ - [Service and Component declaration](#service-and-component-declaration)
42
+ - [Service and Component implementation](#service-and-component-implementation)
43
+ - [Health Checks](#health-checks)
44
+ - [Service Manager](#service-manager)
45
+ - [Component Registry](#component-registry)
46
+ - [Channels](#channels)
47
+ - [Performance](#performance)
48
+ - [Rest Calls](#rest-calls)
49
+ - [Intercepting calls](#intercepting-calls)
50
+ - [FastAPI server](#fastapi-server)
51
+ - [Implementing Channels](#implementing-channels)
52
+ - [Version History](#version-history)
53
+
54
+ ## Introduction
55
+
56
+ The Aspyx service library is built on top of the DI core framework and adds a microservice based architecture,
57
+ that lets you deploy, discover and call services with different remoting protocols and pluggable discovery services.
58
+
59
+ The basic design consists of four different concepts:
60
+
61
+ !!! info "Service"
62
+ defines a group of methods that can be called either locally or remotely.
63
+ These methods represent the functional interface exposed to clients — similar to an interface in traditional programming
64
+
65
+ !!! info "Component"
66
+ a component bundles one or more services and declares the channels (protocols) used to expose them.
67
+ Think of a component as a deployment unit or module.
68
+
69
+ !!! info "Component Registry "
70
+ acts as the central directory for managing available components.
71
+ It allows the framework to register, discover, and resolve components and their services.
72
+
73
+ !!! info "Channel"
74
+ is a pluggable transport layer that defines how service method invocations are transmitted and handled.
75
+
76
+ Let's look at the "interface" layer first.
77
+
78
+ **Example**:
79
+ ```python
80
+ @service(name="test-service", description="test service")
81
+ class TestService(Service):
82
+ @abstractmethod
83
+ def hello(self, message: str) -> str:
84
+ pass
85
+
86
+ @component(name="test-component", services =[TestService])
87
+ class TestComponent(Component):
88
+ pass
89
+ ```
90
+
91
+ After booting the DI infrastructure with a main module we could already call a service:
92
+
93
+ **Example**:
94
+ ```python
95
+ @module(imports=[ServiceModule])
96
+ class Module:
97
+ def __init__(self):
98
+ pass
99
+
100
+ @create()
101
+ def create_registry(self) -> ConsulComponentRegistry:
102
+ return ConsulComponentRegistry(Server.port, "http://localhost:8500") # a consul based registry!
103
+
104
+ environment = Environment(Module)
105
+ service_manager = environment.get(ServiceManager)
106
+
107
+ service = service_manager.get_service(TestService)
108
+
109
+ service.hello("world")
110
+ ```
111
+
112
+ The technical details are completely transparent, as a dynamic proxy encapsulates the internals.
113
+
114
+ As we can also host implementations, lets look at this side as well:
115
+
116
+ ```python
117
+ @implementation()
118
+ class TestComponentImpl(AbstractComponent, TestComponent):
119
+ # constructor
120
+
121
+ def __init__(self):
122
+ super().__init__()
123
+
124
+ # implement Component
125
+
126
+ def get_addresses(self, port: int) -> list[ChannelAddress]:
127
+ return [ChannelAddress("dispatch-json", f"http://{Server.get_local_ip()}:{port}")]
128
+
129
+ @implementation()
130
+ class TestServiceImpl(TestService):
131
+ def __init__(self):
132
+ pass
133
+
134
+ def hello(self, message: str) -> str:
135
+ return f"hello {message}"
136
+ ```
137
+
138
+ The interesting part if the `get_addresses` method that return a list of channel addresses, that can be used to execute remote calls.
139
+ In this case a channel is used that exposes a single http endpoint, that will dispatch to the correct service method.
140
+ This information is registered with the appropriate component registry and is used by other processes.
141
+
142
+ The required - `FastAPI` - infrastructure to expose those services is started with the call:
143
+
144
+ ```python
145
+ server = FastAPIServer(host="0.0.0.0", port=8000)
146
+
147
+ environment = server.boot(Module)
148
+ ```
149
+
150
+ Of course, service can also be called locally. In case of multiple possible channels, a keyword argument is used to
151
+ determine a specific channel. As a local channel has the name "local", the appropriate call is:
152
+
153
+ ```python
154
+ service = service_manager.get_service(TestService, preferred_channel="local")
155
+ ```
156
+
157
+ ## Features
158
+
159
+ The library offers:
160
+
161
+ - sync and async support
162
+ - multiple - extensible - channel implementations supporting dataclasses and pydantic data models.
163
+ - ability to customize http calls with interceptors ( via the AOP abilities )
164
+ - `fastapi` based channels covering simple rest endpoints including `msgpack` support.
165
+ - `httpx` based clients for dispatching channels and simple rest endpoint with the help of low-level decorators.
166
+ - first registry implementation based on `consul`
167
+ - support for configurable health checks
168
+
169
+ As well as the DI and AOP core, all mechanisms are heavily optimized.
170
+ A simple benchmark resulted in message roundtrips in significanlty under a ms per call.
171
+
172
+ Let's see some details
173
+
174
+ ## Service and Component declaration
175
+
176
+ Every service needs to inherit from the "tagging interface" `Service`
177
+
178
+ ```python
179
+ @service(name="test-service", description="test service")
180
+ class TestService(Service):
181
+ @abstractmethod
182
+ def hello(self, message: str) -> str:
183
+ pass
184
+ ```
185
+
186
+ The decorator can add a name and a description. If `name` is not set, the class name converted to snake case is used.
187
+
188
+ A component needs to derive from `Component`:
189
+
190
+ ```python
191
+ @component(services =[TestService])
192
+ class TestComponent(Component):
193
+ pass
194
+ ```
195
+
196
+ The `services` argument references a list of service interfaces that are managed by this component, meaning that they all are
197
+ exposed by the same channels.
198
+
199
+ `Component` defines the abstract methods:
200
+
201
+ - `def startup(self) -> None`
202
+ called initially after booting the system
203
+
204
+ - `def shutdown(self) -> None:`
205
+ called before shutting fown the system
206
+
207
+ - `def get_addresses(self, port: int) -> list[ChannelAddress]:`
208
+ return a list of available `ChannelAddress`es that this component exposes
209
+
210
+ - `def get_status(self) -> ComponentStatus:`
211
+ return the status of this component ( one of the `ComponentStatus` enums `VIRGIN`, `RUNNING`, and `STOPPED`)
212
+
213
+ - `async def get_health(self) -> HealthCheckManager.Health:`
214
+ return the health status of a component implementation.
215
+
216
+ ## Service and Component implementation
217
+
218
+ Service implementations implement the corresponding interface and are decorated with `@implementation`
219
+
220
+ ```python
221
+ @implementation()
222
+ class TestServiceImpl(TestService):
223
+ def __init__(self):
224
+ pass
225
+ ```
226
+
227
+ The constructor is required since the instances are managed by the DI framework.
228
+
229
+ Component implementations derive from the interface and the abstract base class `AbstractComponent`
230
+
231
+ ```python
232
+ @implementation()
233
+ class TestComponentImpl(AbstractComponent, TestComponent):
234
+ # constructor
235
+
236
+ def __init__(self):
237
+ super().__init__()
238
+
239
+ # implement Component
240
+
241
+ def get_addresses(self, port: int) -> list[ChannelAddress]:
242
+ return [ChannelAddress("dispatch-json", f"http://{Server.get_local_ip()}:{port}")]
243
+ ```
244
+
245
+ As a minimum you have to declare the constructor and the `get_addresses` method, that exposes channel addresses
246
+
247
+ ## Health Checks
248
+
249
+ Every component can declare a HTTP health endpoint and the corresponding logic to compute the current status.
250
+
251
+ Two additional things have to be done:
252
+
253
+ - adding a `@health(<endpoint>)` decorator to the class
254
+ - implementing the `get_health()` method that returns a `HealthCheckManager.Health`
255
+
256
+ While you can instantiate the `Health` class directly via
257
+
258
+ ```
259
+ HealthCheckManager.Health(HealtStatus.OK)
260
+ ```
261
+
262
+ it typically makes more sense to let the system execute a number of configured checks and compute the overall result automatically.
263
+
264
+ For this purpose injectable classes can be decorated with `@health_checks()` that contain methods in turn decorated with `@health_check`
265
+
266
+ **Example**:
267
+
268
+ ```python
269
+ @health_checks()
270
+ @injectable()
271
+ class Checks:
272
+ def __init__(self):
273
+ pass
274
+
275
+ @health_check(fail_if_slower_than=1)
276
+ def check_performance(self, result: HealthCheckManager.Result):
277
+ ... # should be done in under a second
278
+
279
+ @health_check(name="check", cache=10)
280
+ def check(self, result: HealthCheckManager.Result):
281
+ ok = ...
282
+ result.set_status(if ok HealthStatus.OK else HealthStatus.ERROR)
283
+ ```
284
+
285
+ The methods are expected to have a single parameter of type `HealthCheckManager.Result` that can be used to set the status including detail information with
286
+
287
+ ```
288
+ set_status(status: HealthStatus, details = "")
289
+ ```
290
+
291
+ When called, the default is already `OK`.
292
+
293
+ The decorator accepts a couple of parameters:
294
+
295
+ - `fail_if_slower_than=0`
296
+ time in `s` that the check is expected to take as a maximum. As soon as the time is exceeded, the status is set to `ERROR`
297
+ - `cache`
298
+ time in 's' that the last result is cached. This is done in order to prevent health-checks putting even more strain on a heavily used system.
299
+
300
+ ## Service Manager
301
+
302
+ `ServiceManager` is the central class used to retrieve service proxies.
303
+
304
+ ```python
305
+ def get_service(self, service_type: Type[T], preferred_channel="") -> T
306
+ ```
307
+
308
+ - `type` is the requested service interface
309
+ - `preferred_channel` the name of the preferred channel.
310
+
311
+ If not specified, the first registered channel is used, which btw. is a local channel - called `local` - in case of implementing services.
312
+
313
+ ## Component Registry
314
+
315
+ The component registry is the place where component implementations are registered and retrieved.
316
+
317
+ In addition to a `LocalComponentRegistry` ( which is used for testing purposes ) the only implementation is
318
+
319
+ `ConsulComponentRegistry`
320
+
321
+ Constructor arguments are
322
+
323
+ - `port: int` the own port
324
+ - `consul: Consul` the consul instance
325
+
326
+ The component registry is also responsible to execute regular health-checks to track component healths.
327
+ As soon as - in our case consul - decides that a component is not alive anymore, it will notify the clients via regular heartbeats about address changes
328
+ which will be propagated to channels talking to the appropriate component.
329
+
330
+ Currently, this only affects the list of possible URLs which are required by the channels!
331
+
332
+ ## Channels
333
+
334
+ Channels implement the possible transport layer protocols. In the sense of a dynamic proxy, they are the invocation handlers!
335
+
336
+ Several channels are implemented:
337
+
338
+ - `dispatch-json`
339
+ channel that dispatches generic `Request` objects via a `invoke` POST-call
340
+ - `dispatch-msgpack`
341
+ channel that dispatches generic `Request` objects via a `invoke` POST-call after packing the json with msgpack
342
+ - `rest`
343
+ channel that executes regular rest-calls as defined by a couple of decorators.
344
+
345
+ All channels react on changed URLs as provided by the component registry.
346
+
347
+ A so called `URLSelector` is used internally to provide URLs for every single call. Two subclasses exist that offer a different logic
348
+
349
+ - `FirstURLSelector` always returns the first URL of the list of possible URLs
350
+ - `RoundRobinURLSelector` switches sequentially between all URLs.
351
+
352
+ To customize the behavior, an around advice can be implemented easily:
353
+
354
+ **Example**:
355
+
356
+ ```python
357
+ @advice
358
+ class ChannelAdvice:
359
+ def __init__(self):
360
+ pass
361
+
362
+ @advice
363
+ class ChannelAdvice:
364
+ def __init__(self):
365
+ pass
366
+
367
+ @around(methods().named("customize").of_type(Channel))
368
+ def customize_channel(self, invocation: Invocation):
369
+ channel = cast(Channel, invocation.args[0])
370
+
371
+ channel.select_round_robin() # or select_first_url()
372
+
373
+ return invocation.proceed()
374
+ ```
375
+
376
+ ### Performance
377
+
378
+ I benchmarked the different implementations with a recursive dataclass as an argument and return value.
379
+ The avg response times - on a local server - where all below 1ms per call.
380
+
381
+ - rest calls are the slowest ( about 0.7ms )
382
+ - dispatching-json 20% faster
383
+ - dispatching-msgpack 30% faster
384
+
385
+ The biggest advantage of the dispatching flavors is, that you don't have to worry about the additional decorators!
386
+
387
+ ### Rest Calls
388
+
389
+ Invoking rest calls requires decorators and some marker annotations.
390
+
391
+ **Example**:
392
+
393
+ ```python
394
+ @service()
395
+ @rest("/api")
396
+ class TestService(Service):
397
+ @get("/hello/{message}")
398
+ def hello(self, message: str) -> str:
399
+ pass
400
+
401
+ @post("/post/")
402
+ def set_data(self, data: Body(Data)) -> Data:
403
+ pass
404
+ ```
405
+
406
+ The decorators `get`, `put`, `post` and `delete` specify the methods.
407
+
408
+ If the class is decorated with `@rest(<prefix>)`, the corresponding prefix will be appended at the beginning.
409
+
410
+ Additional annotations are
411
+ - `Body` the post body
412
+ - `QueryParam`marked for query params
413
+
414
+ ### Intercepting calls
415
+
416
+ The client side HTTP calling is done with `httpx` instances of type `Httpx.Client` or `Httpx.AsyncClient`.
417
+
418
+ To add the possibility to add interceptors - for token handling, etc. - the channel base class `HTTPXChannel` defines
419
+ the methods `make_client()` and `make_async_client` that can be modified with an around advice.
420
+
421
+ **Example**:
422
+
423
+ ```python
424
+ class InterceptingClient(httpx.Client):
425
+ # constructor
426
+
427
+ def __init__(self, *args, **kwargs):
428
+ self.token_provider = ...
429
+ super().__init__(*args, **kwargs)
430
+
431
+ # override
432
+
433
+ def request(self, method, url, *args, **kwargs):
434
+ headers = kwargs.pop("headers", {})
435
+ headers["Authorization"] = f"Bearer {self.token_provider()}"
436
+ kwargs["headers"] = headers
437
+
438
+ return super().request(method, url, *args, **kwargs)
439
+
440
+ @advice
441
+ class ChannelAdvice:
442
+ def __init__(self):
443
+ pass
444
+
445
+ @around(methods().named("make_client").of_type(HTTPXChannel))
446
+ def make_client(self, invocation: Invocation):
447
+ return InterceptingClient()
448
+ ```
449
+
450
+ ## FastAPI server
451
+
452
+ In order to expose components via HTTP, the corresponding infrastructure in form of a FastAPI server needs to be setup.
453
+
454
+
455
+ ```python
456
+ @module()
457
+ class Module():
458
+ def __init__(self):
459
+ pass
460
+
461
+ server = FastAPIServer(host="0.0.0.0", port=8000)
462
+
463
+ environment = server.boot(Module) # will start the http server
464
+ ```
465
+
466
+ This setup will also expose all service interfaces decorated with the corresponding http decorators!
467
+ No need to add any FastAPI decorators, since the mapping is already done internally!
468
+
469
+ ## Implementing Channels
470
+
471
+ To implement a new channel, you only need to derive from one of the possible base classes ( `Channel` or `HTTPXChannel` that already has a `httpx` client)
472
+ and decorate it with `@channel(<name>)`
473
+
474
+ The main methods to implement are `ìnvoke` and `ìnvoke_async`
475
+
476
+ **Example**:
477
+
478
+ ```python
479
+ @channel("fancy")
480
+ class FancyChannel(Channel):
481
+ # constructor
482
+
483
+ def __init__(self):
484
+ super().__init__()
485
+
486
+ # override
487
+
488
+ def invoke(self, invocation: DynamicProxy.Invocation):
489
+ return ...
490
+
491
+ async def invoke_async(self, invocation: DynamicProxy.Invocation):
492
+ return await ...
493
+
494
+ ```
495
+
496
+ # Version History
497
+
498
+ **0.10.0**
499
+
500
+ - first release version
501
+
502
+
503
+
504
+
505
+