wenjin272 commented on code in PR #1486:
URL: https://github.com/apache/flink-agents/pull/1486#discussion_r4768346188
##########
api/src/main/java/org/apache/flink/agents/api/configuration/ConfigOption.java:
##########
@@ -17,13 +17,30 @@
*/
package org.apache.flink.agents.api.configuration;
+import javax.annotation.Nullable;
+
+import java.util.Map;
import java.util.Objects;
/** A {@code ConfigOption} describes a configuration parameter. */
public class ConfigOption<T> {
+ private static final Map<Class<?>, Class<?>> PRIMITIVE_WRAPPERS =
Review Comment:
Could we reuse `ClassUtils.primitiveToWrapper(type)` instead of maintaining
`PRIMITIVE_WRAPPERS`? The API module already uses Commons Lang’s `ClassUtils`,
and this method handles the conversion while leaving reference types unchanged.
##########
python/flink_agents/api/configuration.py:
##########
@@ -15,42 +15,266 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#################################################################################
+import math
+import re
from abc import ABC, abstractmethod
from copy import deepcopy
-from typing import Any, Type
-
-
-class ConfigOption:
+from dataclasses import dataclass
+from enum import Enum
+from typing import Any, ClassVar, Generic, Iterable, Type, TypeGuard, TypeVar,
final
+
+T = TypeVar("T")
+
+
+def _matches_type(value: Any, config_type: type[T]) -> TypeGuard[T]:
+ return isinstance(value, config_type) and not (
+ config_type in {int, float} and isinstance(value, bool)
+ )
+
+
+@dataclass(frozen=True)
+class AllowedValues(Generic[T]):
+ """Restrict an option to strings, integers, or members of its declared
enum."""
+
+ _SUPPORTED_SCALAR_TYPES: ClassVar[tuple[type, ...]] = (str, int)
+
+ _values: tuple[T, ...]
+
+ def __init__(self, values: Iterable[T]) -> None:
+ """Copy choices so changes to the input do not alter the rule."""
+ choices = tuple(values)
+ if not choices:
+ msg = "Allowed values must be nonempty"
+ raise ValueError(msg)
+ first = choices[0]
+ if type(first) not in self._SUPPORTED_SCALAR_TYPES and not isinstance(
+ first, Enum
+ ):
+ msg = "Expected a string, integer, or enum member"
+ raise ValueError(msg)
+ if any(type(choice) is not type(first) for choice in choices):
+ msg = "Allowed values must have the same type"
+ raise ValueError(msg)
+ # Enum membership is defined by identity, even for enums with custom
equality.
+ unique = {
+ id(choice) if isinstance(choice, Enum) else choice: choice
+ for choice in choices
+ }
+ object.__setattr__(self, "_values", tuple(unique.values()))
+
+ @property
+ def values(self) -> tuple[T, ...]:
+ """Return the allowed values for schema inspection."""
+ return self._values
+
+ def _check_type(self, key: str, config_type: type) -> None:
+ if type(self._values[0]) is not config_type:
+ msg = f"{key}: expected allowed values of type
{config_type.__name__}"
+ raise ValueError(msg)
+
+ def _validate(self, key: str, value: T) -> None:
+ if isinstance(value, Enum):
+ permitted = any(value is choice for choice in self._values)
+ else:
+ permitted = type(value) is type(self._values[0]) and value in
self._values
+ if not permitted:
+ msg = f"{key}: value is not in allowed values"
+ raise ValueError(msg)
+
+
+@dataclass(frozen=True)
+class NumericRange(Generic[T]):
+ """Inclusive range for int or float options with at least one endpoint."""
+
+ _SUPPORTED_BOUND_TYPES: ClassVar[tuple[type, ...]] = (int, float)
+
+ minimum: T | None = None
+ maximum: T | None = None
+
+ def __post_init__(self) -> None:
+ bounds = [v for v in (self.minimum, self.maximum) if v is not None]
+ if not bounds or any(
+ type(v) not in self._SUPPORTED_BOUND_TYPES for v in bounds
+ ):
+ msg = "Numeric ranges require at least one int or float bound"
+ raise ValueError(msg)
+ for bound in bounds:
+ self._check_finite("bound", bound)
+ if self.minimum is not None and self.maximum is not None:
+ if type(self.minimum) is not type(self.maximum):
+ msg = "Bounds must have the same type"
+ raise ValueError(msg)
+ if self.minimum > self.maximum:
+ msg = "minimum exceeds maximum"
+ raise ValueError(msg)
+
+ def _check_type(self, key: str, config_type: type) -> None:
+ for bound in (self.minimum, self.maximum):
+ if bound is not None and type(bound) is not config_type:
+ msg = f"{key}: expected {config_type.__name__} bound"
+ raise ValueError(msg)
+
+ @staticmethod
+ def _check_finite(key: str, value: T) -> None:
+ if isinstance(value, float) and not math.isfinite(value):
+ msg = f"{key}: bounded values must be finite"
+ raise ValueError(msg)
+
+ def _validate(self, key: str, value: T) -> None:
+ self._check_finite(key, value)
+ if self.minimum is not None and value < self.minimum:
+ msg = f"{key}: value is below minimum {self.minimum}"
+ raise ValueError(msg)
+ if self.maximum is not None and value > self.maximum:
+ msg = f"{key}: value is above maximum {self.maximum}"
+ raise ValueError(msg)
+
+
+class ConfigOption(Generic[T]):
"""A configuration option defines a configuration key with its type and
default
value.
Args:
key: The configuration key name
- config_type: The expected type of the configuration value (int, float,
str,
- or bool)
+ config_type: The expected Python type after conversion.
default: The default value for this configuration option
+ required: Require an explicit non-null value; incompatible with a
default.
+ description: Meaning, units and usage notes for reference
documentation.
+ constraint: One allowed-values or inclusive-range rule. It is checked
for
+ non-null defaults at declaration and for converted values on
option reads.
+ stability: Classification declared on this option. None leaves it
unspecified.
+ since: First release in the current classification, not first
introduction.
+ in_progress: Experimental functionality not yet complete; omit since.
+ deprecated_since: First deprecated release; independent of stable
since.
+ replacement: Nonblank replacement key, when a deprecated option has
one.
"""
def __init__(
- self, key: str, config_type: Type[Any], default: Any | None = None
+ self,
+ key: str,
+ config_type: Type[T],
+ default: T | None = None,
+ *,
+ required: bool = False,
+ description: str = "",
+ constraint: AllowedValues[T] | NumericRange[T] | None = None,
+ stability: str | None = None,
+ since: str | None = None,
+ in_progress: bool = False,
+ deprecated_since: str | None = None,
+ replacement: str | None = None,
Review Comment:
Could we use `Annotated` with the metadata types from #1491 for Python
configuration options as well? For example:
```python
TIMEOUT: Annotated[
ConfigOption[int],
Experimental(since="1.1.0"),
] = ConfigOption("timeout", int, default=30)
```
This would align with Java’s field annotations and reuse the existing
lifecycle markers and classification inheritance rules, keeping `ConfigOption`
focused on configuration properties and value validation. This revises the
approach originally proposed in #1460, but I think it would simplify the design.
We could then remove the lifecycle parameters, getters, and constructor-time
lifecycle validation from `ConfigOption`. As with #1491, lifecycle rules can be
checked by the shared compatibility tooling. Configuration value validation
should remain unchanged.
The tooling would read lifecycle metadata from field declarations rather
than option instances.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]