Skip to content

feat(feature_flags): support beyond boolean values (JSON values) #804

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Dec 31, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
Prev Previous commit
Next Next commit
fix: mypy, JSONType annotation, GA notice
  • Loading branch information
heitorlessa committed Dec 31, 2021
commit 0a44cf8ed0f0a41de76dbba9326d2684854a6178
4 changes: 3 additions & 1 deletion aws_lambda_powertools/shared/types.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Any, Callable, TypeVar
from typing import Any, Callable, Dict, List, TypeVar, Union

AnyCallableT = TypeVar("AnyCallableT", bound=Callable[..., Any]) # noqa: VNE001
# JSON primitives only, mypy doesn't support recursive tho
JSONType = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
26 changes: 17 additions & 9 deletions aws_lambda_powertools/utilities/feature_flags/feature_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import Any, Dict, List, Optional, Union, cast

from ... import Logger
from ...shared.types import JSONType
from . import schema
from .base import StoreProvider
from .exceptions import ConfigurationStoreError
Expand Down Expand Up @@ -111,14 +112,15 @@ def _evaluate_rules(

# Context might contain PII data; do not log its value
self.logger.debug(
f"Evaluating rule matching, rule={rule_name}, feature={feature_name}, default={str(feat_default)}, boolean_feature={boolean_feature}" # type: ignore # noqa: E501
f"Evaluating rule matching, rule={rule_name}, feature={feature_name}, default={str(feat_default)}, boolean_feature={boolean_feature}" # noqa: E501
)
if self._evaluate_conditions(rule_name=rule_name, feature_name=feature_name, rule=rule, context=context):
# Maintenance: Revisit before going GA.
return bool(rule_match_value) if boolean_feature else rule_match_value

# no rule matched, return default value of feature
self.logger.debug(
f"no rule matched, returning feature default, default={str(feat_default)}, name={feature_name}, boolean_feature={boolean_feature}" # type: ignore # noqa: E501
f"no rule matched, returning feature default, default={str(feat_default)}, name={feature_name}, boolean_feature={boolean_feature}" # noqa: E501
)
return feat_default

Expand Down Expand Up @@ -172,7 +174,7 @@ def get_configuration(self) -> Dict:

return config

def evaluate(self, *, name: str, context: Optional[Dict[str, Any]] = None, default: Any) -> Any:
def evaluate(self, *, name: str, context: Optional[Dict[str, Any]] = None, default: JSONType) -> JSONType:
"""Evaluate whether a feature flag should be enabled according to stored schema and input context

**Logic when evaluating a feature flag**
Expand All @@ -189,15 +191,15 @@ def evaluate(self, *, name: str, context: Optional[Dict[str, Any]] = None, defau
Attributes that should be evaluated against the stored schema.

for example: `{"tenant_id": "X", "username": "Y", "region": "Z"}`
default: Any
default: JSONType
default value if feature flag doesn't exist in the schema,
or there has been an error when fetching the configuration from the store
Can be boolean (the default for feature flags) or any JSON values for advanced features
Can be boolean or any JSON values for non-boolean features.

Returns
------
bool
whether feature should be enabled or not for boolean feature flag or any other JSON type
JSONType
whether feature should be enabled (bool flags) or JSON value when non-bool feature matches

Raises
------
Expand All @@ -220,17 +222,23 @@ def evaluate(self, *, name: str, context: Optional[Dict[str, Any]] = None, defau

rules = feature.get(schema.RULES_KEY)
feat_default = feature.get(schema.FEATURE_DEFAULT_VAL_KEY)
# Maintenance: Revisit before going GA. We might to simplify customers on-boarding by not requiring it
# for non-boolean flags. It'll need minor implementation changes, docs changes, and maybe refactor
# get_enabled_features. We can minimize breaking change, despite Beta label, by having a new
# method `get_matching_features` returning Dict[feature_name, feature_value]
boolean_feature = feature.get(
schema.FEATURE_DEFAULT_VAL_TYPE_KEY, True
) # backwards compatability ,assume feature flag
if not rules:
self.logger.debug(
f"no rules found, returning feature default, name={name}, default={str(feat_default)}, boolean_feature={boolean_feature}" # type: ignore # noqa: E501
f"no rules found, returning feature default, name={name}, default={str(feat_default)}, boolean_feature={boolean_feature}" # noqa: E501
)
# Maintenance: Revisit before going GA. We might to simplify customers on-boarding by not requiring it
# for non-boolean flags.
return bool(feat_default) if boolean_feature else feat_default

self.logger.debug(
f"looking for rule match, name={name}, default={str(feat_default)}, boolean_feature={boolean_feature}" # type: ignore # noqa: E501
f"looking for rule match, name={name}, default={str(feat_default)}, boolean_feature={boolean_feature}" # noqa: E501
)
return self._evaluate_rules(
feature_name=name, context=context, feat_default=feat_default, rules=rules, boolean_feature=boolean_feature
Expand Down
4 changes: 3 additions & 1 deletion aws_lambda_powertools/utilities/feature_flags/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@ def validate_feature(name, feature) -> bool:
boolean_feature: bool = feature.get(FEATURE_DEFAULT_VAL_TYPE_KEY, True)
# if feature is boolean_feature, default_value must be a boolean type.
# default_value must exist
# Maintenance: Revisit before going GA. We might to simplify customers on-boarding by not requiring it
# for non-boolean flags.
if default_value is None or (not isinstance(default_value, bool) and boolean_feature):
raise SchemaValidationError(f"feature 'default' boolean key must be present, feature={name}")
return boolean_feature
Expand Down Expand Up @@ -187,7 +189,7 @@ def validate(self):
conditions.validate()

@staticmethod
def validate_rule(rule: Dict, rule_name: str, feature_name: str, boolean_feature: Optional[bool] = True):
def validate_rule(rule: Dict, rule_name: str, feature_name: str, boolean_feature: bool = True):
if not rule or not isinstance(rule, dict):
raise SchemaValidationError(f"Feature rule must be a dictionary, feature={feature_name}")

Expand Down