-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(backend-python): add basic telestion library for python
- Loading branch information
cb0s
committed
Mar 13, 2024
1 parent
1196031
commit fa72884
Showing
10 changed files
with
248 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
.venv/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2024 WüSpace e. V. | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
# Telestion Python Backend | ||
|
||
This repository contains everything to build a working Telestion backend in Python. | ||
Additional examples help in setting everything up. | ||
|
||
The Python backend is mainly added to allow for easier interfacing with many scientific libraries, such as numpy, | ||
scipy, tensorflow or pytorch. | ||
Creating static graphs with Matplotlib that can be rendered in the frontend could also be created. |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
nats-py~=2.7.2 # TODO: decide if we want to specify versions | ||
pydantic~=2.6.4 |
Empty file.
Empty file.
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
import argparse | ||
import json | ||
import os | ||
from pathlib import Path | ||
from typing import Any, TypeVar | ||
|
||
from pydantic import BaseModel, Field | ||
|
||
|
||
class TelestionConfig(BaseModel): | ||
dev: bool = False | ||
nats_url: str = Field(alias="NATS_URL") | ||
nats_user: str | None = Field(alias="NATS_USER", default=None) | ||
nats_password: str | None = Field(alias="NATS_PASSWORD", default=None) | ||
config_file: Path | None = Field(alias="CONFIG_FILE", default=None) | ||
config_key: str | None = Field(alias="CONFIG_KEY", default=None) | ||
service_name: str = Field(alias="SERVICE_NAME") | ||
data_dir: Path = Field(alias="DATA_DIR") | ||
|
||
unparsed_cli: list[str] = Field(alias="_telestion_validator_unparsed_cli") | ||
|
||
|
||
# With this we allow users to extend TelestionConfig for finer control over custom config fields | ||
_TelestionConfigT = TypeVar("_TelestionConfigT", bound=TelestionConfig, default=TelestionConfig) | ||
|
||
|
||
def build_config() -> _TelestionConfigT: | ||
cli_args, additional_args = _parse_cli() | ||
|
||
def _from_env_or_cli(key: str): | ||
return cli_args.get(key, os.environ.get(key, None)) | ||
|
||
config_p = _from_env_or_cli('CONFIG_FILE') | ||
config_key = _from_env_or_cli('CONFIG_KEY') | ||
|
||
config_assembly: dict[str, Any] = dict() | ||
if 'dev' in cli_args: | ||
# 1. Add default config | ||
config_assembly.update(defaults()) | ||
|
||
if config_p is not None: | ||
config_p = Path(config_p) | ||
# 2. Insert config file | ||
config_assembly.update(_parse_config_file(config_p, config_key)) | ||
|
||
# 3. Add Environment Variables | ||
config_assembly.update(os.environ) | ||
|
||
# 4. Add CLI args | ||
config_assembly.update(cli_args) | ||
|
||
# 5. Add args that cannot be parsed by the pipeline, i.e. service specific config | ||
config_assembly['_telestion_validator_unparsed_cli'] = additional_args | ||
|
||
return TelestionConfig(**config_assembly) | ||
|
||
|
||
def defaults() -> dict[str, Any]: | ||
return { | ||
'NATS_URL': "nats://localhost:4222", | ||
'SERVICE_NAME': f"dev-{os.getpid()}", | ||
'DATA_DIR': Path("./data") | ||
} | ||
|
||
|
||
def _parse_cli() -> tuple[dict[str, Any], list[str]]: | ||
description = "CLI Interface for the Telestion Services. This is one way to setup your Telestion application." | ||
epilog = "For more information please visit https://github.com/wuespace/telestion or \ | ||
https://telestion.wuespace.de/" | ||
parser = argparse.ArgumentParser( | ||
description=description, | ||
epilog=epilog, | ||
prog="Telestion-CLI (Python)", | ||
) | ||
|
||
parser.add_argument("--dev", action='store_true', help="If set, program will start in development mode") | ||
parser.add_argument("--version", action='version', version="%(prog)s v1.0-alpha") | ||
|
||
parser.add_argument("--NATS_URL", help="NATS url of the server the service can connect to") | ||
parser.add_argument("--NATS_USER", help="NATS user name for the authentication with the server") | ||
parser.add_argument("--NATS_PASSWORD", help="NATS password for the authentication with the server \ | ||
(Note: It is recommended to set this via the environment variables or the config!)") | ||
|
||
parser.add_argument("--CONFIG_FILE", help="file path to the config of the service", type=Path) | ||
parser.add_argument("--CONFIG_KEY", help="object key of a config file") | ||
|
||
parser.add_argument("--SERVICE_NAME", help="name of the service also used in the nats service registration") | ||
parser.add_argument("--DATA_DIR", help="path where the service can store persistent data", type=Path) | ||
|
||
namespace, args = parser.parse_known_args() | ||
return vars(namespace), args | ||
|
||
|
||
def _parse_config_file(config_p: Path, key: str = None) -> dict[str, Any]: | ||
with open(config_p, 'r') as config_f: | ||
content = json.load(config_f) | ||
|
||
if key is None: | ||
return content | ||
|
||
return content[key] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
import json | ||
from dataclasses import dataclass, replace | ||
from pathlib import Path | ||
from typing import Any | ||
|
||
import nats | ||
from nats.aio.client import Client as NatsClient # mostly for type hinting | ||
|
||
from telestion.backend.config import TelestionConfig, build_config | ||
|
||
|
||
@dataclass | ||
class Service: | ||
nc: NatsClient | None # None if Options.nats = False | ||
data_dir: Path | ||
service_name: str | ||
config: TelestionConfig | ||
|
||
|
||
@dataclass | ||
class Options: | ||
nats: bool = True | ||
# (officially) we don't support int keys, btw... | ||
overwrite_args: dict[str, Any] | None = None | ||
custom_nc: NatsClient | None = None | ||
|
||
def without_nats(self) -> 'Options': | ||
return replace(self, nats=False) | ||
|
||
def with_overwrite_args(self, **kwargs) -> 'Options': | ||
return replace(self, overwrite_args=kwargs) | ||
|
||
def with_custom_nc(self, nats_client: NatsClient) -> 'Options': | ||
return replace(self, custom_nc=nats_client) | ||
|
||
|
||
async def start_service(opts: Options = None) -> Service: | ||
if opts is None: | ||
opts = Options() | ||
|
||
config = build_config() | ||
if opts.overwrite_args is not None: | ||
config.update(opts.overwrite_args) | ||
|
||
service = Service(opts.custom_nc, config.data_dir, config.service_name, config) | ||
|
||
if not opts.nats or opts.custom_nc is not None: | ||
return service | ||
|
||
nc = await nats.connect(servers=_prepare_nats_url(config)) | ||
# Setup healthcheck | ||
await nc.subscribe( | ||
'__telestion__.health', | ||
cb=lambda msg: msg.respond( | ||
json_encode({ | ||
"errors": 0, | ||
"name": config.service_name | ||
}) | ||
) | ||
) | ||
|
||
return replace(service, nc=nc) | ||
|
||
|
||
# Macros | ||
def json_encode(msg: Any, encoding='utf-8', **dumps_kwargs) -> bytes: | ||
""" | ||
Helper function to encode messages to json. | ||
This convenience macro helps to reduce encoding/decoding boilerplate. | ||
For finer control implement this function by your own and customize to your needs. | ||
:param msg: message to encode | ||
:param encoding: encoding to use (default: utf-8) | ||
:param dumps_kwargs: additional arguments to pass to json.dumps | ||
:return: encoded json message as utf-8 bytes | ||
""" | ||
return json.dumps(msg, **dumps_kwargs).encode(encoding=encoding) | ||
|
||
|
||
def json_decode(msg: str | bytes | bytearray, encoding='utf-8', **loads_kwargs) -> Any: | ||
""" | ||
Helper function to decode messages from json into an object. | ||
This convenience macro helps to reduce encoding/decoding boilerplate. | ||
For finer control implement this function by your own and customize to your needs. | ||
:param msg: message to decode | ||
:param encoding: encoding used to encode the bytes | ||
:param loads_kwargs: | ||
:return: | ||
""" | ||
if not isinstance(msg, str): | ||
# ensure to support any encoding supported by python | ||
msg = msg.decode(encoding=encoding) | ||
|
||
return json.loads(msg, **loads_kwargs) | ||
|
||
|
||
def _prepare_nats_url(config: TelestionConfig) -> str: | ||
""" | ||
Helper function that creates the valid url for the NATS client. | ||
Because the Python interface does not support user authentication out of the box with a separate design this is done | ||
via the connecting url. | ||
:param config: parsed config from all sources | ||
:return: created url from parsed config url, user and password | ||
""" | ||
url = config.nats_url | ||
|
||
if config.nats_user is None or config.nats_password is None: | ||
return url | ||
|
||
if '://' in url: | ||
_, url = url.split('://', 1) | ||
|
||
return f"nats://{config.username}:{config.password}@{url}" |