|
5 | 5 | and async context management for notification sources and outputs. |
6 | 6 | """ |
7 | 7 |
|
| 8 | +import os |
8 | 9 | from abc import ABC, abstractmethod |
9 | 10 | from collections.abc import AsyncIterator |
10 | 11 | from contextlib import asynccontextmanager |
11 | 12 | from dataclasses import dataclass, field |
12 | 13 | from typing import Any, Generic, Protocol, TypeVar, runtime_checkable |
13 | 14 |
|
14 | 15 | from loguru import logger |
15 | | -from pydantic import BaseModel, ConfigDict |
| 16 | +from pydantic import BaseModel, ConfigDict, model_validator |
16 | 17 |
|
17 | 18 | from .event import NotificationEvent |
18 | 19 |
|
@@ -60,10 +61,119 @@ class BasePluginConfig(BaseModel): |
60 | 61 | Base configuration class for plugins implementing the protocol. |
61 | 62 |
|
62 | 63 | Provides common configuration methods and Pydantic validation. |
| 64 | + Automatically applies environment variable overrides for all config fields. |
63 | 65 | """ |
64 | 66 |
|
65 | 67 | model_config = ConfigDict(extra="forbid") |
66 | 68 |
|
| 69 | + def _get_plugin_prefix(self) -> str: |
| 70 | + """ |
| 71 | + Extract plugin prefix from config class name. |
| 72 | +
|
| 73 | + Examples: |
| 74 | + - PgSTACSourceConfig -> PGSTAC |
| 75 | + - MQTTConfig -> MQTT |
| 76 | + - CloudEventsConfig -> CLOUDEVENTS |
| 77 | + """ |
| 78 | + class_name = self.__class__.__name__ |
| 79 | + |
| 80 | + # Remove common suffixes |
| 81 | + for suffix in ["SourceConfig", "Config", "Source", "Output"]: |
| 82 | + if class_name.endswith(suffix): |
| 83 | + class_name = class_name[: -len(suffix)] |
| 84 | + break |
| 85 | + |
| 86 | + # Convert to uppercase and handle special cases |
| 87 | + if class_name.lower() == "pgstac": |
| 88 | + return "PGSTAC" |
| 89 | + elif class_name.lower() == "cloudevents": |
| 90 | + return "CLOUDEVENTS" |
| 91 | + elif class_name.lower() == "mqtt": |
| 92 | + return "MQTT" |
| 93 | + else: |
| 94 | + return class_name.upper() |
| 95 | + |
| 96 | + @model_validator(mode="after") |
| 97 | + def apply_env_overrides(self) -> "BasePluginConfig": |
| 98 | + """ |
| 99 | + Apply environment variable overrides for all configuration fields. |
| 100 | +
|
| 101 | + Uses simple plugin-prefixed environment variables: |
| 102 | + - PGSTAC_HOST, PGSTAC_PORT, PGSTAC_PASSWORD, etc. |
| 103 | + - MQTT_BROKER_HOST, MQTT_TIMEOUT, MQTT_USE_TLS, etc. |
| 104 | + - CLOUDEVENTS_ENDPOINT, CLOUDEVENTS_TIMEOUT, etc. |
| 105 | + """ |
| 106 | + plugin_prefix = self._get_plugin_prefix() |
| 107 | + |
| 108 | + for field_name, field_info in self.model_fields.items(): |
| 109 | + # Check for plugin-prefixed environment variable |
| 110 | + env_var_name = f"{plugin_prefix}_{field_name.upper()}" |
| 111 | + env_value = os.getenv(env_var_name) |
| 112 | + |
| 113 | + if env_value is None: |
| 114 | + continue |
| 115 | + |
| 116 | + try: |
| 117 | + # Get the field's type annotation |
| 118 | + field_type = field_info.annotation |
| 119 | + |
| 120 | + # Handle Union types (like str | None) safely |
| 121 | + origin = getattr(field_type, "__origin__", None) |
| 122 | + if origin is not None: |
| 123 | + args = getattr(field_type, "__args__", ()) |
| 124 | + if len(args) > 0: |
| 125 | + # For Union types, use the first non-None type |
| 126 | + non_none_types = [arg for arg in args if arg is not type(None)] |
| 127 | + if non_none_types: |
| 128 | + field_type = non_none_types[0] |
| 129 | + elif origin is list: |
| 130 | + # Handle list types - split by comma |
| 131 | + list_value = [ |
| 132 | + item.strip() |
| 133 | + for item in env_value.split(",") |
| 134 | + if item.strip() |
| 135 | + ] |
| 136 | + setattr(self, field_name, list_value) |
| 137 | + logger.debug( |
| 138 | + f"Applied env override: {env_var_name}={env_value} -> " |
| 139 | + f"{field_name}={list_value}" |
| 140 | + ) |
| 141 | + continue |
| 142 | + |
| 143 | + # Convert environment variable value to appropriate type |
| 144 | + converted_value: Any |
| 145 | + if field_type is bool or ( |
| 146 | + isinstance(field_type, type) and issubclass(field_type, bool) |
| 147 | + ): |
| 148 | + # Handle boolean conversion |
| 149 | + converted_value = env_value.lower() in ("true", "1", "yes", "on") |
| 150 | + elif field_type is int or ( |
| 151 | + isinstance(field_type, type) and issubclass(field_type, int) |
| 152 | + ): |
| 153 | + converted_value = int(env_value) |
| 154 | + elif field_type is float or ( |
| 155 | + isinstance(field_type, type) and issubclass(field_type, float) |
| 156 | + ): |
| 157 | + converted_value = float(env_value) |
| 158 | + else: |
| 159 | + # Default to string |
| 160 | + converted_value = env_value |
| 161 | + |
| 162 | + # Apply the override |
| 163 | + setattr(self, field_name, converted_value) |
| 164 | + logger.debug( |
| 165 | + f"Applied env override: {env_var_name}={env_value} -> " |
| 166 | + f"{field_name}={converted_value}" |
| 167 | + ) |
| 168 | + |
| 169 | + except (ValueError, TypeError) as e: |
| 170 | + logger.warning( |
| 171 | + f"Failed to apply env override {env_var_name}={env_value} to " |
| 172 | + f"field {field_name}: {e}" |
| 173 | + ) |
| 174 | + |
| 175 | + return self |
| 176 | + |
67 | 177 | @classmethod |
68 | 178 | def get_sample_config(cls) -> dict[str, Any]: |
69 | 179 | """Default implementation - subclasses should override.""" |
|
0 commit comments