Skip to content

Commit

Permalink
fix(python): add support for '=' in additional args, add support for …
Browse files Browse the repository at this point in the history
…custom arguments in `build_config()` and fix tests
  • Loading branch information
cb0s committed Dec 23, 2024
1 parent 50e3d24 commit 2db5a83
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 8 deletions.
14 changes: 11 additions & 3 deletions backend-python/src/telestion/backend/config.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import argparse
import json
import os
import re
import sys
from pathlib import Path
from typing import Any, TypeVar

Expand All @@ -29,7 +27,7 @@ class TelestionConfig(BaseModel):
_TelestionConfigT = TypeVar("_TelestionConfigT", bound=TelestionConfig)


def build_config(clazz: type[_TelestionConfigT] = None) -> _TelestionConfigT:
def build_config(clazz: type[_TelestionConfigT] = None, **kwargs) -> _TelestionConfigT:
if clazz is None:
clazz = TelestionConfig

Expand Down Expand Up @@ -57,6 +55,9 @@ def _from_env_or_cli(key: str):
# 4. Add CLI args
config_assembly.update(cli_args)

# 5. Add manual overwrites
config_assembly.update(kwargs)

return clazz(**config_assembly)


Expand Down Expand Up @@ -122,6 +123,13 @@ def _parse_unknown_args(unknown_args: list[str], parsed_args: dict[str, Any]) ->
key: str = ""
for unknown_arg in unknown_args:
if unknown_arg.startswith("-"):
if '=' in unknown_arg:
# handle case of equal signs in args
split = unknown_arg.split('=')
_parse_unknown_args([split[0], *split[1:]], parsed_args)
key = ""
continue

# handles 2.
if key not in parsed_args and key != "":
parsed_args[key] = True
Expand Down
13 changes: 10 additions & 3 deletions backend-python/src/telestion/backend/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,19 @@ async def close(self) -> None:
await self.nc.close()


async def start_service(nats_disabled: bool = False, config: _TelestionConfigT = None) -> Service:
async def start_service(
nats_disabled: bool = False,
config: _TelestionConfigT = None,
nats_connecting_options: dict[str, Any] | None = None
) -> Service:
"""Creates a Service with the parsed config and spins up a new NATS client if configured to do so."""
if config is None:
config = build_config()
config = build_config(_nats_connecting_options=nats_connecting_options)

nc = None if nats_disabled else await nats.connect(servers=_prepare_nats_url(config))
if nats_connecting_options is None:
nats_connecting_options = {}

nc = None if nats_disabled else await nats.connect(servers=_prepare_nats_url(config), **nats_connecting_options)
return Service(nc, config.data_dir, config.service_name, config)


Expand Down
23 changes: 21 additions & 2 deletions backend-python/testbed.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,25 @@ async def main():
}

try:
service = await start_service(nats_disabled=os.getenv("X_DISABLE_NATS") == "1")
nats_connection_options = {
"allow_reconnect": False, # only try to connect once
"max_reconnect_attempts": 0, # test
"connect_timeout": 1, # fail after 1 sec.
"pedantic": True,
"verbose": True,
}
service = await start_service(
nats_disabled=os.getenv("X_DISABLE_NATS") == "1",
nats_connecting_options=nats_connection_options
)
result["started"] = True
result["config"] = service.config.model_dump(by_alias=True, mode='json', exclude_none=True)

if (nc := service.nc) is not None:
result["nats_api_available"] = True
result["nats_connected"] = nc.is_connected
if nc.is_connected:
await nc.close()
except BaseException as e:
result["error"] = str(e)
finally:
Expand All @@ -30,5 +42,12 @@ async def main():


if __name__ == '__main__':
# sys.argv.extend([
# "--dev",
# "--NATS_URL=nats:4222",
# "--NATS_USER=nats",
# "--NATS_PASSWORD=password",
# ])
# asyncio.run(main())
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait_for(main(), 1))
loop.run_until_complete(asyncio.wait_for(main(), 1)) # fail automatically after one second

0 comments on commit 2db5a83

Please sign in to comment.