Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
b7c3859
refactor(config): add helper to fold deprecated flat settings into ne…
HosseinNejatiJavaremi Nov 21, 2026
809f26c
refactor(config): rely on pydantic deprecated warnings in fold helper
HosseinNejatiJavaremi Nov 21, 2026
bf2e4ee
refactor(config): group vault settings into nested models
HosseinNejatiJavaremi Nov 21, 2026
955f31b
refactor(config): group scylladb settings into nested models
HosseinNejatiJavaremi Nov 21, 2026
4819aa3
refactor(config): group temporal settings into nested models
HosseinNejatiJavaremi Nov 21, 2026
f932b04
refactor(config): group redis settings into nested models
HosseinNejatiJavaremi Nov 21, 2026
d950ee9
refactor(config): group elasticsearch settings into nested models
HosseinNejatiJavaremi Nov 21, 2026
94f4586
refactor(config): group sqlalchemy pool and count cache settings into…
HosseinNejatiJavaremi Nov 21, 2026
51e6f04
refactor(config): group auth settings into nested models
HosseinNejatiJavaremi Nov 21, 2026
9c0fa62
refactor(config): group keycloak settings into nested models
HosseinNejatiJavaremi Nov 21, 2026
bdae6d8
refactor(config): group email settings into nested models
HosseinNejatiJavaremi Nov 21, 2026
6676385
refactor(config): group grpc tls settings into nested models
HosseinNejatiJavaremi Nov 21, 2026
0ac1a9e
refactor(config): group kafka sasl and ssl settings into nested models
HosseinNejatiJavaremi Nov 21, 2026
9eb74b9
refactor(config): group fastapi middleware settings into nested models
HosseinNejatiJavaremi Nov 21, 2026
8139b84
refactor(config): name every group switch IS_ENABLED
HosseinNejatiJavaremi Nov 21, 2026
2f72381
docs(config): describe nested settings groups
HosseinNejatiJavaremi Nov 21, 2026
eb2abc7
refactor(config): group uvicorn tls, websocket and limit settings int…
HosseinNejatiJavaremi Nov 21, 2026
e8e336f
refactor(config): group otel pushgateway settings into a nested model
HosseinNejatiJavaremi Nov 21, 2026
81a2c5e
merge master into nested config groups
HosseinNejatiJavaremi Nov 21, 2026
c9e575e
docs(changelog): add 5.33.0 release notes
HosseinNejatiJavaremi Nov 21, 2026
92fd820
docs(changelog): add nested settings to the 5.32.0 release notes
HosseinNejatiJavaremi Nov 21, 2026
2c882b6
test(keycloak): set nested token expectations
HosseinNejatiJavaremi Nov 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions archipy/adapters/base/sqlalchemy/query_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,11 @@ async def _run_async_count_request(request: _CountRequest) -> int:

def _build_count_cache(config: SQLAlchemyConfig) -> Callable[[_CountRequest], int] | None:
"""Create the cached count runner when the config enables it (needs the ``cache`` extra)."""
if not config.COUNT_CACHE_ENABLED:
if not config.COUNT_CACHE.IS_ENABLED:
return None
from archipy.helpers.decorators.ttl_caching import ttl_cache # noqa: PLC0415 # optional "cache" extra

return ttl_cache(ttl_seconds=config.COUNT_CACHE_TTL_SECONDS, maxsize=config.COUNT_CACHE_MAX_SIZE)(
return ttl_cache(ttl_seconds=config.COUNT_CACHE.TTL_SECONDS, maxsize=config.COUNT_CACHE.MAX_SIZE)(
_run_count_request,
)

Expand All @@ -71,7 +71,7 @@ def _build_async_count_cache(config: SQLAlchemyConfig) -> Callable[[_CountReques
Raises:
ConfigurationError: If the count cache is enabled but ``async-lru`` is not installed.
"""
if not config.COUNT_CACHE_ENABLED:
if not config.COUNT_CACHE.IS_ENABLED:
return None
try:
from async_lru import alru_cache # noqa: PLC0415 # optional "cache" extra
Expand All @@ -81,7 +81,7 @@ def _build_async_count_cache(config: SQLAlchemyConfig) -> Callable[[_CountReques
reason="async-lru is not installed; install it with archipy[cache]",
) from exception

return alru_cache(ttl=config.COUNT_CACHE_TTL_SECONDS, maxsize=config.COUNT_CACHE_MAX_SIZE)(
return alru_cache(ttl=config.COUNT_CACHE.TTL_SECONDS, maxsize=config.COUNT_CACHE.MAX_SIZE)(
_run_async_count_request,
)

Expand Down
28 changes: 14 additions & 14 deletions archipy/adapters/base/sqlalchemy/session_managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,13 +201,13 @@ def _get_pool_kwargs(self, configs: ConfigT) -> dict[str, Any]:
A dictionary of pool-related keyword arguments for engine creation.
"""
return {
"pool_pre_ping": configs.POOL_PRE_PING,
"pool_size": configs.POOL_SIZE,
"pool_recycle": configs.POOL_RECYCLE_SECONDS,
"pool_reset_on_return": configs.POOL_RESET_ON_RETURN,
"pool_timeout": configs.POOL_TIMEOUT,
"pool_use_lifo": configs.POOL_USE_LIFO,
"max_overflow": configs.POOL_MAX_OVERFLOW,
"pool_pre_ping": configs.POOL.PRE_PING,
"pool_size": configs.POOL.SIZE,
"pool_recycle": configs.POOL.RECYCLE_SECONDS,
"pool_reset_on_return": configs.POOL.RESET_ON_RETURN,
"pool_timeout": configs.POOL.TIMEOUT,
"pool_use_lifo": configs.POOL.USE_LIFO,
"max_overflow": configs.POOL.MAX_OVERFLOW,
}

def _get_session_generator(self) -> scoped_session:
Expand Down Expand Up @@ -430,13 +430,13 @@ def _get_pool_kwargs(self, configs: ConfigT) -> dict[str, Any]:
A dictionary of pool-related keyword arguments for engine creation.
"""
return {
"pool_pre_ping": configs.POOL_PRE_PING,
"pool_size": configs.POOL_SIZE,
"pool_recycle": configs.POOL_RECYCLE_SECONDS,
"pool_reset_on_return": configs.POOL_RESET_ON_RETURN,
"pool_timeout": configs.POOL_TIMEOUT,
"pool_use_lifo": configs.POOL_USE_LIFO,
"max_overflow": configs.POOL_MAX_OVERFLOW,
"pool_pre_ping": configs.POOL.PRE_PING,
"pool_size": configs.POOL.SIZE,
"pool_recycle": configs.POOL.RECYCLE_SECONDS,
"pool_reset_on_return": configs.POOL.RESET_ON_RETURN,
"pool_timeout": configs.POOL.TIMEOUT,
"pool_use_lifo": configs.POOL.USE_LIFO,
"max_overflow": configs.POOL.MAX_OVERFLOW,
}

def _get_session_generator(self) -> async_scoped_session:
Expand Down
52 changes: 26 additions & 26 deletions archipy/adapters/email/adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def __init__(self, config: EmailConfig) -> None:
"""Initialize EmailConnectionManager.

Raises:
ConfigurationError: If only one of ``USERNAME`` and ``PASSWORD`` is set while ``TLS_MODE`` is not ``auto``.
ConfigurationError: If only one of ``USERNAME`` and ``PASSWORD`` is set while ``TLS.MODE`` is not ``auto``.
"""
self.config = config
self.smtp_connection: smtplib.SMTP | None = None
Expand All @@ -86,10 +86,10 @@ def __init__(self, config: EmailConfig) -> None:
def _validate_security(self) -> None:
"""Check the TLS and credential settings; the legacy ``auto`` mode only warns."""
half_set = bool(self.config.USERNAME) != bool(self.config.PASSWORD)
if self.config.TLS_MODE == "auto":
if self.config.TLS.MODE == "auto":
warnings.warn(
"EMAIL.TLS_MODE='auto' is deprecated: STARTTLS is opportunistic, the certificate is not verified "
"and a failed upgrade falls back to clear text. Set TLS_MODE to 'starttls' or 'implicit'.",
"EMAIL.TLS.MODE='auto' is deprecated: STARTTLS is opportunistic, the certificate is not verified "
"and a failed upgrade falls back to clear text. Set TLS.MODE to 'starttls' or 'implicit'.",
DeprecationWarning,
stacklevel=3,
)
Expand All @@ -105,37 +105,37 @@ def _validate_security(self) -> None:
operation="email_credentials",
reason="USERNAME and PASSWORD must be set together",
)
if self.config.TLS_MODE == "none" and self.config.USERNAME and self.config.PASSWORD:
if self.config.TLS.MODE == "none" and self.config.USERNAME and self.config.PASSWORD:
warnings.warn(
"EMAIL.TLS_MODE='none' sends USERNAME and PASSWORD in clear text. "
"Set TLS_MODE to 'starttls' or 'implicit'; clear-text login will be rejected in a future release.",
"EMAIL.TLS.MODE='none' sends USERNAME and PASSWORD in clear text. "
"Set TLS.MODE to 'starttls' or 'implicit'; clear-text login will be rejected in a future release.",
DeprecationWarning,
stacklevel=3,
)
if self.config.TLS_MODE in ("starttls", "implicit") and not self.config.TLS_VERIFY:
if self.config.TLS.MODE in ("starttls", "implicit") and not self.config.TLS.VERIFY:
warnings.warn(
"EMAIL.TLS_VERIFY=False disables certificate and host name verification, which exposes the "
"session and credentials to interception. Use TLS_CA_FILE for a private CA; "
"TLS_VERIFY=False will be rejected in a future release.",
"EMAIL.TLS.VERIFY=False disables certificate and host name verification, which exposes the "
"session and credentials to interception. Use TLS.CA_FILE for a private CA; "
"TLS.VERIFY=False will be rejected in a future release.",
DeprecationWarning,
stacklevel=3,
)

def _build_ssl_context(self) -> ssl.SSLContext:
"""Build the TLS context from ``TLS_CA_FILE`` and ``TLS_VERIFY``."""
context = ssl.create_default_context(cafile=self.config.TLS_CA_FILE)
if not self.config.TLS_VERIFY:
"""Build the TLS context from ``TLS.CA_FILE`` and ``TLS.VERIFY``."""
context = ssl.create_default_context(cafile=self.config.TLS.CA_FILE)
if not self.config.TLS.VERIFY:
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
return context

def _open_session(self) -> tuple[smtplib.SMTP, str]:
"""Open the SMTP session for ``TLS_MODE`` and return it with the TLS mode actually in use."""
mode = self.config.TLS_MODE
mode = self.config.TLS.MODE
source_address = (self.config.SOURCE_ADDRESS, self.config.SOURCE_PORT) if self.config.SOURCE_ADDRESS else None
common: dict[str, Any] = {
"local_hostname": self.config.LOCAL_HOSTNAME,
"timeout": self.config.CONNECTION_TIMEOUT,
"timeout": self.config.POOL.CONNECTION_TIMEOUT,
"source_address": source_address,
}
server = cast("str", self.config.SMTP_SERVER)
Expand All @@ -158,7 +158,7 @@ def _open_session(self) -> tuple[smtplib.SMTP, str]:

def _negotiate_tls(self, session: smtplib.SMTP) -> str:
"""Greet the server and upgrade with STARTTLS as ``TLS_MODE`` demands; return the TLS mode in use."""
mode = self.config.TLS_MODE
mode = self.config.TLS.MODE
session.ehlo()
offered = session.has_extn("starttls")
if mode == "starttls" and not offered:
Expand Down Expand Up @@ -220,7 +220,7 @@ def refresh_if_needed(self) -> None:
return

time_diff = (DatetimeUtils.get_datetime_now() - self.last_used).total_seconds()
if time_diff > self.config.CONNECTION_REFRESH_SECONDS:
if time_diff > self.config.POOL.CONNECTION_REFRESH_SECONDS:
self.disconnect()
self.connect()

Expand All @@ -231,11 +231,11 @@ class EmailConnectionPool:
def __init__(self, config: EmailConfig) -> None:
"""Initialize EmailConnectionPool."""
self.config = config
self.pool: Queue[EmailConnectionManager] = Queue(maxsize=config.POOL_SIZE)
self.pool: Queue[EmailConnectionManager] = Queue(maxsize=config.POOL.SIZE)
self._initialize_pool()

def _initialize_pool(self) -> None:
for _ in range(self.config.POOL_SIZE):
for _ in range(self.config.POOL.SIZE):
connection = EmailConnectionManager(self.config)
self.pool.put(connection)

Expand All @@ -249,7 +249,7 @@ def get_connection(self) -> EmailConnectionManager:
UnavailableError: If no slot becomes free within ``CONNECTION_TIMEOUT`` seconds.
"""
try:
connection = self.pool.get(timeout=self.config.CONNECTION_TIMEOUT)
connection = self.pool.get(timeout=self.config.POOL.CONNECTION_TIMEOUT)
except Empty as exception:
raise UnavailableError(resource_type="SMTP") from exception
try:
Expand Down Expand Up @@ -287,7 +287,7 @@ def create_attachment(
content_type: Optional MIME type of the attachment.
content_disposition: Whether the attachment is inline or a regular attachment.
content_id: Optional Content-ID for inline attachments.
max_size: Maximum size in bytes; defaults to the configured ``ATTACHMENT_MAX_SIZE``.
max_size: Maximum size in bytes; defaults to the configured ``ATTACHMENTS.MAX_SIZE``.

Returns:
EmailAttachmentDTO: The validated attachment.
Expand All @@ -297,7 +297,7 @@ def create_attachment(
(for example it exceeds the maximum size).
"""
if max_size is None:
max_size = BaseConfig.global_config().EMAIL.ATTACHMENT_MAX_SIZE
max_size = BaseConfig.global_config().EMAIL.ATTACHMENTS.MAX_SIZE
try:
processed_content = AttachmentHandler._process_source(source, attachment_type, max_size)

Expand Down Expand Up @@ -362,12 +362,12 @@ def _process_url_source(source: str | bytes | BinaryIO | HttpUrl, max_size: int
parsed = urlparse(url)
if parsed.scheme not in ("http", "https"):
raise InvalidArgumentError(argument_name="source", additional_data={"reason": "unsupported_url_scheme"})
allowed_hosts = config.ATTACHMENT_URL_ALLOWED_HOSTS
allowed_hosts = config.ATTACHMENTS.URL_ALLOWED_HOSTS
if allowed_hosts is not None and parsed.hostname not in allowed_hosts:
raise InvalidArgumentError(argument_name="source", additional_data={"reason": "url_host_not_allowed"})
limit = max_size if max_size is not None else config.ATTACHMENT_MAX_SIZE
limit = max_size if max_size is not None else config.ATTACHMENTS.MAX_SIZE
content = bytearray()
with httpx2.stream("GET", url, timeout=config.ATTACHMENT_URL_TIMEOUT) as response:
with httpx2.stream("GET", url, timeout=config.ATTACHMENTS.URL_TIMEOUT) as response:
response.raise_for_status()
for chunk in response.iter_bytes():
content.extend(chunk)
Expand Down
6 changes: 3 additions & 3 deletions archipy/configs/base_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ def customize(self) -> None:
It is called automatically by `set_global()`.

When ``APP_NAME`` is set, unset or placeholder nested identity fields are
filled: ``OTEL.SERVICE_NAME``, ``FASTAPI.PROJECT_NAME``, ``AUTH.JWT_ISSUER``,
filled: ``OTEL.SERVICE_NAME``, ``FASTAPI.PROJECT_NAME``, ``AUTH.JWT.ISSUER``,
and ``TEMPORAL.CLIENT_IDENTITY``. Explicit nested values always win.

An unset ``COUNT_THRESHOLD`` of the SQLAlchemy configs is filled with ``PAGINATION.MAX_ITEMS``.
Expand All @@ -257,8 +257,8 @@ def customize(self) -> None:
self.OTEL.SERVICE_NAME = self.APP_NAME
if self.FASTAPI.PROJECT_NAME == "project_name":
self.FASTAPI.PROJECT_NAME = self.APP_NAME
if self.AUTH.JWT_ISSUER == "your-app-name":
self.AUTH.JWT_ISSUER = self.APP_NAME
if self.AUTH.JWT.ISSUER == "your-app-name":
self.AUTH.JWT.ISSUER = self.APP_NAME
if self.TEMPORAL.CLIENT_IDENTITY is None:
self.TEMPORAL.CLIENT_IDENTITY = self.APP_NAME

Expand Down
51 changes: 51 additions & 0 deletions archipy/configs/sections/_common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""Helpers for config sections that move flat fields into nested groups."""

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
from collections.abc import Mapping

from pydantic import BaseModel


def deprecated_flat_message(section: str, flat_name: str, group: str, field: str) -> str:
"""Return the deprecation message of a flat setting that moved into a nested group.

Args:
section: Config section name, for example ``"VAULT"``.
flat_name: Old flat field name, for example ``"APPROLE_ROLE_ID"``.
group: New group name, for example ``"APPROLE"``.
field: Field name inside the group, for example ``"ROLE_ID"``.

Returns:
The message to pass to ``Field(deprecated=...)``.
"""
return f"Use {section}.{group}.{field} instead; {section}.{flat_name} will be removed in 6.0.0"


def fold_flat_fields(
owner: BaseModel,
group: str,
group_type: type[BaseModel],
flat_to_field: Mapping[str, str],
) -> None:
"""Copy deprecated flat settings into a nested group.

Only flat fields the user set explicitly are used. Declare them with ``Field(deprecated=...)``: reading them here
makes pydantic emit one ``DeprecationWarning`` per field. A value already set on the group wins. The group is
created when it is ``None``. Call this from a ``model_validator(mode="after")`` of the section.

Args:
owner: The section model that holds the flat fields and the group.
group: Attribute name of the group on ``owner``.
group_type: Model class of the group.
flat_to_field: Maps each flat field name to its field name inside the group.
"""
used = sorted(name for name in flat_to_field if name in owner.model_fields_set)
if not used:
return
current: BaseModel | None = getattr(owner, group)
values: dict[str, Any] = current.model_dump(exclude_unset=True) if current is not None else {}
for name in used:
values.setdefault(flat_to_field[name], getattr(owner, name))
object.__setattr__(owner, group, group_type(**values))
Loading
Loading