Skip to content

Commit cd8fe6e

Browse files
authored
Rewrite configuration system (#78)
1 parent e6eb10d commit cd8fe6e

File tree

10 files changed

+280
-220
lines changed

10 files changed

+280
-220
lines changed

config.dist.yml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@ kanae:
2626
# Whether the Prometheus exporter is enabled or not
2727
enabled: False
2828

29+
# The host that the Prometheus exporter will bind to. By default,
30+
# it will always be set to 127.0.0.1
31+
host: "localhost"
32+
33+
# The port used for the Prometheus exporter. By default,
34+
# it will always be set to 9555
35+
port: 9555
36+
2937
# Settings for Kanae's custom rate limiters
3038
limiter:
3139

mise.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ depends = ["server:docker:up"]
3030
alias = ["server:up", "server:dev"]
3131
description = "Start backend development server. Save file(s) to see changes through reloading"
3232
env._.path = ".venv/bin"
33-
dir = "{{ config_root }}/server"
34-
run = "uvicorn launcher:app --reload"
33+
dir = "{{ config_root }}"
34+
run = "uvicorn launcher:app --app-dir=server --reload"
3535

3636
[tasks."server:lint"]
3737
description = "Lints the codebase by type checking and general linting"

server/core.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ def _decode_jsonb(value):
157157
class SupertokensQuerier(Querier):
158158
def __init__(self, recipe_id: str, *, config: KanaeConfig):
159159
super().__init__(
160-
self._get_normalized_host_supertokens(config["auth"]["connection_uri"]),
160+
self._get_normalized_host_supertokens(config.auth.connection_uri),
161161
recipe_id,
162162
)
163163

@@ -463,15 +463,15 @@ def __init__(
463463
supertokens_init(
464464
app_info=InputAppInfo(
465465
app_name="ucmacm-website",
466-
api_domain=config["auth"]["api_domain"],
467-
website_domain=config["auth"]["website_domain"],
466+
api_domain=config.auth.api_domain,
467+
website_domain=config.auth.website_domain,
468468
api_base_path="/auth",
469469
website_base_path="/auth",
470470
),
471471
supertokens_config=SupertokensConfig(
472472
# Force the first one for connection
473-
connection_uri=config["auth"]["connection_uri"][0],
474-
api_key=config["auth"]["api_key"],
473+
connection_uri=config.auth.connection_uri[0],
474+
api_key=config.auth.api_key,
475475
),
476476
framework="fastapi",
477477
recipe_list=[
@@ -484,13 +484,13 @@ def __init__(
484484
third_party_id="google",
485485
clients=[
486486
ProviderClientConfig(
487-
client_id=config["auth"]["providers"][
488-
"google"
489-
]["client_id"],
490-
client_secret=config["auth"]["providers"][
487+
client_id=config.auth.providers["google"][
488+
"client_id"
489+
],
490+
client_secret=config.auth.providers[
491491
"google"
492492
]["client_secret"],
493-
scope=config["auth"]["providers"]["google"][
493+
scope=config.auth.providers["google"][
494494
"scopes"
495495
],
496496
),
@@ -526,7 +526,7 @@ def __init__(
526526
self._logger = logging.getLogger("kanae.core")
527527

528528
self.config = config
529-
self.is_prometheus_enabled: bool = config["kanae"]["prometheus"]["enabled"]
529+
self.is_prometheus_enabled: bool = config.kanae.prometheus["enabled"]
530530

531531
_instrumentator_settings = InstrumentatorSettings(metric_namespace="kanae")
532532
self.instrumentator = PrometheusInstrumentator(
@@ -561,8 +561,8 @@ def __init__(
561561
)
562562

563563
if self.is_prometheus_enabled:
564-
_host = self.config["kanae"]["host"]
565-
_port = self.config["kanae"]["port"]
564+
_host = self.config.kanae.prometheus["host"]
565+
_port = self.config.kanae.prometheus["port"]
566566

567567
self.instrumentator.start()
568568

@@ -658,7 +658,7 @@ async def lifespan(self, app: Self):
658658
)
659659

660660
async with asyncpg.create_pool(
661-
dsn=self.config["postgres_uri"], init=init
661+
dsn=self.config.postgres_uri, init=init
662662
) as app.pool:
663663
yield
664664

server/launcher.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,22 @@
1-
from pathlib import Path
2-
31
from core import Kanae
42
from fastapi_pagination import add_pagination
53
from routes import router
64
from starlette.middleware.cors import CORSMiddleware
75
from supertokens_python import get_all_cors_headers
86
from supertokens_python.framework.fastapi import get_middleware
9-
from utils.config import KanaeConfig, KanaeUvicornConfig
7+
from utils.config import KanaeConfig, find_config
8+
from utils.uvicorn.config import KanaeUvicornConfig
109
from utils.uvicorn.server import KanaeUvicornServer
1110

12-
config_path = Path(__file__).parent / "config.yml"
13-
config = KanaeConfig(config_path)
11+
config = KanaeConfig.load_from_file(find_config())
12+
1413

1514
app = Kanae(config=config)
1615
app.add_middleware(get_middleware())
1716
app.include_router(router)
1817
app.add_middleware(
1918
CORSMiddleware,
20-
allow_origins=config["auth"]["allowed_origins"],
19+
allow_origins=config.auth.allowed_origins,
2120
allow_credentials=True,
2221
allow_methods=["GET", "PUT", "POST", "DELETE", "OPTIONS", "PATCH"],
2322
allow_headers=["Content-Type"] + get_all_cors_headers(),
@@ -32,8 +31,8 @@
3231
if __name__ == "__main__":
3332
config = KanaeUvicornConfig(
3433
"launcher:app",
35-
port=config["kanae"]["port"],
36-
host=config["kanae"]["host"],
34+
port=config.kanae.host,
35+
host=config.kanae.port,
3736
workers=2,
3837
access_log=True,
3938
)

server/tests/conftest.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from testcontainers.core.utils import raise_for_deprecated_parameter
2020
from testcontainers.core.waiting_utils import wait_container_is_ready, wait_for_logs
2121
from testcontainers.postgres import PostgresContainer
22-
from utils.config import KanaeConfig
22+
from utils.config import KanaeConfig, find_config
2323
from utils.limiter import get_remote_address
2424
from utils.limiter.extension import (
2525
KanaeLimiter,
@@ -40,9 +40,9 @@
4040

4141
ROOT = Path(__file__).parents[2]
4242
DOCKERFILE_PATH = ROOT / "docker" / "pg-test" / "Dockerfile"
43-
CONFIG_PATH = ROOT / "server" / "config.yml"
43+
CONFIG_PATH = find_config()
4444

45-
config = KanaeConfig(CONFIG_PATH)
45+
config = KanaeConfig.load_from_file(CONFIG_PATH)
4646

4747

4848
async def _async_rate_limit_exceeded_handler(request: Request, exc: RateLimitExceeded):
@@ -109,8 +109,8 @@ class KanaeServices(NamedTuple):
109109
class KanaeTestClient:
110110
def __init__(self, app: Kanae, *, base_url: Optional[str] = None):
111111
self._config = app.config
112-
self._host = self._config["kanae"]["host"]
113-
self._port = self._config["kanae"]["port"]
112+
self._host = self._config.kanae.host
113+
self._port = self._config.kanae.port
114114

115115
self._transport = httpx.ASGITransport(app=app)
116116

@@ -158,7 +158,7 @@ def valkey() -> Generator[ValkeyContainer, None, None]:
158158
async def app(
159159
get_app: Kanae, setup: KanaeServices
160160
) -> AsyncGenerator[KanaeTestClient, None]:
161-
get_app.config["postgres_uri"] = setup.postgres.get_connection_url(driver=None)
161+
get_app.config.postgres_uri = setup.postgres.get_connection_url(driver=None)
162162
async with (
163163
LifespanManager(app=get_app),
164164
KanaeTestClient(app=get_app) as client,
@@ -177,8 +177,8 @@ async def build_fastapi_app(request, valkey: ValkeyContainer):
177177
def _factory(**limiter_args):
178178
middleware, exception_handler = request.param
179179

180-
test_config = KanaeConfig(CONFIG_PATH)
181-
test_config["kanae"]["limiter"]["storage_uri"] = valkey.get_connection_url()
180+
test_config = KanaeConfig.load_from_file(CONFIG_PATH)
181+
test_config.kanae.limiter["storage_uri"] = valkey.get_connection_url()
182182

183183
limiter_args.setdefault("key_func", get_remote_address)
184184
limiter_args.setdefault("config", test_config)

0 commit comments

Comments
 (0)