faust-tools 1.0.5__py3-none-any.whl
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.
- faust_tools/decorators.py +63 -0
- faust_tools/fields.py +18 -0
- faust_tools/response.py +18 -0
- faust_tools/serializer.py +50 -0
- faust_tools-1.0.5.dist-info/METADATA +30 -0
- faust_tools-1.0.5.dist-info/RECORD +9 -0
- faust_tools-1.0.5.dist-info/WHEEL +5 -0
- faust_tools-1.0.5.dist-info/licenses/LICENSE +21 -0
- faust_tools-1.0.5.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
from functools import wraps
|
|
5
|
+
from typing import Callable, TypeVar
|
|
6
|
+
|
|
7
|
+
from faust import App, Stream, TopicT
|
|
8
|
+
from faust.agents import AgentT
|
|
9
|
+
|
|
10
|
+
from .response import Response
|
|
11
|
+
from .serializer import ReadStream, StreamSerializer, WriteStream
|
|
12
|
+
|
|
13
|
+
_logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
_T = TypeVar("_T")
|
|
16
|
+
|
|
17
|
+
StreamFunction = Callable[[StreamSerializer], Response]
|
|
18
|
+
StreamDecorator = Callable[[StreamFunction], AgentT[_T]]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def stream(
|
|
22
|
+
app: App, topic: TopicT, **kwargs
|
|
23
|
+
) -> Callable[[StreamDecorator], AgentT[_T]]:
|
|
24
|
+
def decorator(func: StreamFunction) -> AgentT[_T]:
|
|
25
|
+
@wraps(func)
|
|
26
|
+
async def streaming(stream: Stream):
|
|
27
|
+
async for value in stream:
|
|
28
|
+
if not isinstance(value, StreamSerializer) or value.validate():
|
|
29
|
+
continue
|
|
30
|
+
|
|
31
|
+
# Always call func correctly and ensure result is a Response
|
|
32
|
+
if inspect.iscoroutinefunction(func):
|
|
33
|
+
result = await func(value)
|
|
34
|
+
else:
|
|
35
|
+
result = func(value)
|
|
36
|
+
if not isinstance(result, Response):
|
|
37
|
+
raise TypeError(
|
|
38
|
+
f"Function {func.__name__} did not return a Response instance"
|
|
39
|
+
f", got {type(result)}"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
response: Response = result
|
|
43
|
+
response.id = value.id
|
|
44
|
+
_logger.info(
|
|
45
|
+
f"<{stream.channel}--{value.action}> :: {response.id} :: "
|
|
46
|
+
f"{response.status.value} ({response.status.phrase})"
|
|
47
|
+
)
|
|
48
|
+
yield response.__dict__
|
|
49
|
+
|
|
50
|
+
agent_kwargs = {
|
|
51
|
+
"sink": [app.topic(os.environ["SERVICE_NAME"])],
|
|
52
|
+
**kwargs,
|
|
53
|
+
}
|
|
54
|
+
operation = os.getenv("SERVICE_OPERATION", "rw").lower()
|
|
55
|
+
if operation in ("r", "read") and issubclass(topic.value_type, ReadStream):
|
|
56
|
+
return app.agent(topic, **agent_kwargs)(streaming)
|
|
57
|
+
if operation in ("w", "write") and issubclass(topic.value_type, WriteStream):
|
|
58
|
+
return app.agent(topic, **agent_kwargs)(streaming)
|
|
59
|
+
if operation in ("rw", "read_write"):
|
|
60
|
+
return app.agent(topic, **agent_kwargs)(streaming)
|
|
61
|
+
return func
|
|
62
|
+
|
|
63
|
+
return decorator
|
faust_tools/fields.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from collections.abc import Iterable
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from faust.exceptions import ValidationError
|
|
5
|
+
from faust.models import FieldDescriptor
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ChoiceField(FieldDescriptor[str]):
|
|
9
|
+
def __init__(self, choices: list[str], **kwargs: Any) -> None:
|
|
10
|
+
self.choices = choices
|
|
11
|
+
# Must pass any custom args to init,
|
|
12
|
+
# so we pass the choices keyword argument also here.
|
|
13
|
+
super().__init__(choices=choices, **kwargs)
|
|
14
|
+
|
|
15
|
+
def validate(self, value: str) -> Iterable[ValidationError]:
|
|
16
|
+
if value not in self.choices:
|
|
17
|
+
choices = ", ".join(self.choices)
|
|
18
|
+
yield self.validation_error(f"{self.field} must be one of {choices}")
|
faust_tools/response.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from http import HTTPStatus
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Response:
|
|
5
|
+
id: str | None
|
|
6
|
+
status: HTTPStatus
|
|
7
|
+
detail: dict | None
|
|
8
|
+
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
*,
|
|
12
|
+
id: str | None = None,
|
|
13
|
+
status: HTTPStatus = HTTPStatus.OK,
|
|
14
|
+
detail: dict | None = None,
|
|
15
|
+
):
|
|
16
|
+
self.id = id
|
|
17
|
+
self.status = status
|
|
18
|
+
self.detail = detail
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from collections.abc import Mapping
|
|
2
|
+
|
|
3
|
+
import faust
|
|
4
|
+
from faust.types.models import ModelT
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class StreamSerializer(faust.Record):
|
|
8
|
+
"""
|
|
9
|
+
Main Stream Serializer
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
id: str
|
|
13
|
+
action: str
|
|
14
|
+
detail: dict | None = None
|
|
15
|
+
|
|
16
|
+
@classmethod
|
|
17
|
+
def from_data(
|
|
18
|
+
cls, data: Mapping, *, preferred_type: type[ModelT] | None = None
|
|
19
|
+
) -> faust.Record:
|
|
20
|
+
attribute_type = preferred_type.__annotations__
|
|
21
|
+
record = super().from_data(data, preferred_type=preferred_type)
|
|
22
|
+
if record.detail and "detail" in attribute_type:
|
|
23
|
+
detail_type = attribute_type["detail"]
|
|
24
|
+
if (
|
|
25
|
+
isinstance(record.detail, list)
|
|
26
|
+
and hasattr(detail_type, "__args__")
|
|
27
|
+
and getattr(detail_type.__args__[0], "_auto_assign", None)
|
|
28
|
+
):
|
|
29
|
+
for index, value in enumerate(record.detail):
|
|
30
|
+
record.detail[index] = detail_type.__args__[0](**value)
|
|
31
|
+
elif isinstance(record.detail, dict) and getattr(
|
|
32
|
+
detail_type, "_auto_assign", None
|
|
33
|
+
):
|
|
34
|
+
record.detail = detail_type(**record.detail)
|
|
35
|
+
|
|
36
|
+
return record
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ReadStream(StreamSerializer):
|
|
40
|
+
"""
|
|
41
|
+
Read Stream Serializer
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class WriteStream(StreamSerializer):
|
|
46
|
+
"""
|
|
47
|
+
Write Stream Serializer
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
detail: dict | None
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: faust-tools
|
|
3
|
+
Version: 1.0.5
|
|
4
|
+
Summary: Faust Tools
|
|
5
|
+
Author-email: Biszx <isares.br@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: faust-streaming>=0.11.3
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
# Faust Tools
|
|
14
|
+
|
|
15
|
+
Make it easier to faust application
|
|
16
|
+
|
|
17
|
+
## Feature
|
|
18
|
+
|
|
19
|
+
### Decorator
|
|
20
|
+
|
|
21
|
+
- stream
|
|
22
|
+
|
|
23
|
+
### Field
|
|
24
|
+
|
|
25
|
+
- ChoiceField
|
|
26
|
+
|
|
27
|
+
### Serializer (Record)
|
|
28
|
+
|
|
29
|
+
- ReadSerializer
|
|
30
|
+
- Write Serializer
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
faust_tools/decorators.py,sha256=U5VMaXBcNeyrDezS9NC7paYLn8eH3jDhrIQ4LboJurc,2259
|
|
2
|
+
faust_tools/fields.py,sha256=r5LvF7hxForXlsO9NSDcJsIerCa9QevasP9_qQW91Bk,678
|
|
3
|
+
faust_tools/response.py,sha256=qj3Gz2djvhi_M2mMR-7m1bu-Xot-5xnRzgH2hJBNGFc,353
|
|
4
|
+
faust_tools/serializer.py,sha256=-VjxQx43SCswe1TUIndcZsLQyBqbguDUOdZxiurLyuo,1347
|
|
5
|
+
faust_tools-1.0.5.dist-info/licenses/LICENSE,sha256=ov-g_s6VBWsRTyUjaVCIomAmB8pgc_b2MOHD-0J5EzU,1070
|
|
6
|
+
faust_tools-1.0.5.dist-info/METADATA,sha256=3_xuDR5cENx4BxPwNOku8XSuCA2EOfyYzg-2KgMcC4Y,454
|
|
7
|
+
faust_tools-1.0.5.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
8
|
+
faust_tools-1.0.5.dist-info/top_level.txt,sha256=eQEbYFCnbkOgljK-mzI9djd5a5894rkr7lS8QLREVZ0,12
|
|
9
|
+
faust_tools-1.0.5.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2020 Trinity Roots
|
|
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 @@
|
|
|
1
|
+
faust_tools
|