11"""Configuration loading and validation."""
22
3+ import json
4+ import typing as t
35
46from loguru import logger
5- from pydantic import BaseModel , field_validator
6- from pydantic_settings import BaseSettings
7+ from pydantic import BaseModel , field_validator , fields
8+ from pydantic_settings import BaseSettings , PydanticBaseSettingsSource
9+
10+
11+ def custom_decode_complex_value (
12+ __ : str ,
13+ ___ : fields .FieldInfo ,
14+ value : t .Any ,
15+ ) -> t .Any :
16+ """Parse complex values as CSV if they cannot be parsed as JSON."""
17+ try :
18+ return json .loads (value )
19+ except ValueError :
20+ return value .split ("," )
721
822
923class EnvConfig (
@@ -15,6 +29,25 @@ class EnvConfig(
1529):
1630 """Our default configuration for models that should load from .env files."""
1731
32+ @classmethod
33+ def settings_customise_sources (
34+ cls ,
35+ settings_cls : type [BaseSettings ],
36+ init_settings : PydanticBaseSettingsSource ,
37+ env_settings : PydanticBaseSettingsSource ,
38+ dotenv_settings : PydanticBaseSettingsSource ,
39+ file_secret_settings : PydanticBaseSettingsSource ,
40+ ) -> tuple [PydanticBaseSettingsSource , ...]:
41+ """Monkey patch default sources to have the custom CSV parser fallback."""
42+ dotenv_settings .decode_complex_value = custom_decode_complex_value
43+ env_settings .decode_complex_value = custom_decode_complex_value
44+ return (
45+ init_settings ,
46+ env_settings ,
47+ dotenv_settings ,
48+ file_secret_settings ,
49+ )
50+
1851
1952class _LokiConfig (EnvConfig , env_prefix = "loki_" ):
2053 """Loki specific configuration."""
@@ -69,7 +102,7 @@ def warn_above_ten(cls, value: list[TokenConfig]) -> list[TokenConfig]:
69102 This is because we cannot handle more than 10 token triggers at once until we
70103 batch triggers into groups of 10 to distribute to the webhook.
71104 """
72- if len (value ) > 10 : # noqa: PLR2004
105+ if len (value ) > 10 :
73106 logger .warning ("More than 10 token triggers in one period cannot be handled, be careful." )
74107
75108 return value
0 commit comments