|
| 1 | +import logging |
| 2 | +from typing import Any, Dict, List, Optional |
| 3 | + |
| 4 | +from . import schema |
| 5 | +from .exceptions import ConfigurationException |
| 6 | +from .schema_fetcher import SchemaFetcher |
| 7 | + |
| 8 | +logger = logging.getLogger(__name__) |
| 9 | + |
| 10 | + |
| 11 | +class ConfigurationStore: |
| 12 | + def __init__(self, schema_fetcher: SchemaFetcher): |
| 13 | + """constructor |
| 14 | +
|
| 15 | + Args: |
| 16 | + schema_fetcher (SchemaFetcher): A schema JSON fetcher, can be AWS AppConfig, Hashicorp Consul etc. |
| 17 | + """ |
| 18 | + self._logger = logger |
| 19 | + self._schema_fetcher = schema_fetcher |
| 20 | + self._schema_validator = schema.SchemaValidator(self._logger) |
| 21 | + |
| 22 | + def _match_by_action(self, action: str, condition_value: Any, context_value: Any) -> bool: |
| 23 | + if not context_value: |
| 24 | + return False |
| 25 | + mapping_by_action = { |
| 26 | + schema.ACTION.EQUALS.value: lambda a, b: a == b, |
| 27 | + schema.ACTION.STARTSWITH.value: lambda a, b: a.startswith(b), |
| 28 | + schema.ACTION.ENDSWITH.value: lambda a, b: a.endswith(b), |
| 29 | + schema.ACTION.CONTAINS.value: lambda a, b: a in b, |
| 30 | + } |
| 31 | + |
| 32 | + try: |
| 33 | + func = mapping_by_action.get(action, lambda a, b: False) |
| 34 | + return func(context_value, condition_value) |
| 35 | + except Exception as exc: |
| 36 | + self._logger.error(f"caught exception while matching action, action={action}, exception={str(exc)}") |
| 37 | + return False |
| 38 | + |
| 39 | + def _is_rule_matched(self, feature_name: str, rule: Dict[str, Any], rules_context: Dict[str, Any]) -> bool: |
| 40 | + rule_name = rule.get(schema.RULE_NAME_KEY, "") |
| 41 | + rule_default_value = rule.get(schema.RULE_DEFAULT_VALUE) |
| 42 | + conditions: Dict[str, str] = rule.get(schema.CONDITIONS_KEY) |
| 43 | + |
| 44 | + for condition in conditions: |
| 45 | + context_value = rules_context.get(condition.get(schema.CONDITION_KEY)) |
| 46 | + if not self._match_by_action( |
| 47 | + condition.get(schema.CONDITION_ACTION), |
| 48 | + condition.get(schema.CONDITION_VALUE), |
| 49 | + context_value, |
| 50 | + ): |
| 51 | + logger.debug( |
| 52 | + f"rule did not match action, rule_name={rule_name}, rule_default_value={rule_default_value}, feature_name={feature_name}, context_value={str(context_value)}" # noqa: E501 |
| 53 | + ) |
| 54 | + # context doesn't match condition |
| 55 | + return False |
| 56 | + # if we got here, all conditions match |
| 57 | + logger.debug( |
| 58 | + f"rule matched, rule_name={rule_name}, rule_default_value={rule_default_value}, feature_name={feature_name}" # noqa: E501 |
| 59 | + ) |
| 60 | + return True |
| 61 | + |
| 62 | + def _handle_rules( |
| 63 | + self, |
| 64 | + *, |
| 65 | + feature_name: str, |
| 66 | + rules_context: Dict[str, Any], |
| 67 | + feature_default_value: bool, |
| 68 | + rules: List[Dict[str, Any]], |
| 69 | + ) -> bool: |
| 70 | + for rule in rules: |
| 71 | + rule_default_value = rule.get(schema.RULE_DEFAULT_VALUE) |
| 72 | + if self._is_rule_matched(feature_name, rule, rules_context): |
| 73 | + return rule_default_value |
| 74 | + # no rule matched, return default value of feature |
| 75 | + logger.debug( |
| 76 | + f"no rule matched, returning default value of feature, feature_default_value={feature_default_value}, feature_name={feature_name}" # noqa: E501 |
| 77 | + ) |
| 78 | + return feature_default_value |
| 79 | + |
| 80 | + def get_configuration(self) -> Dict[str, Any]: |
| 81 | + """Get configuration string from AWs AppConfig and returned the parsed JSON dictionary |
| 82 | +
|
| 83 | + Raises: |
| 84 | + ConfigurationException: Any validation error or appconfig error that can occur |
| 85 | +
|
| 86 | + Returns: |
| 87 | + Dict[str, Any]: parsed JSON dictionary |
| 88 | + """ |
| 89 | + schema: Dict[ |
| 90 | + str, Any |
| 91 | + ] = ( |
| 92 | + self._schema_fetcher.get_json_configuration() |
| 93 | + ) # parse result conf as JSON, keep in cache for self.max_age seconds |
| 94 | + # validate schema |
| 95 | + self._schema_validator.validate_json_schema(schema) |
| 96 | + return schema |
| 97 | + |
| 98 | + def get_feature_toggle( |
| 99 | + self, *, feature_name: str, rules_context: Optional[Dict[str, Any]] = None, value_if_missing: bool |
| 100 | + ) -> bool: |
| 101 | + """get a feature toggle boolean value. Value is calculated according to a set of rules and conditions. |
| 102 | + see below for explanation. |
| 103 | +
|
| 104 | + Args: |
| 105 | + feature_name (str): feature name that you wish to fetch |
| 106 | + rules_context (Optional[Dict[str, Any]]): dict of attributes that you would like to match the rules |
| 107 | + against, can be {'tenant_id: 'X', 'username':' 'Y', 'region': 'Z'} etc. |
| 108 | + value_if_missing (bool): this will be the returned value in case the feature toggle doesn't exist in |
| 109 | + the schema or there has been an error while fetching the |
| 110 | + configuration from appconfig |
| 111 | +
|
| 112 | + Returns: |
| 113 | + bool: calculated feature toggle value. several possibilities: |
| 114 | + 1. if the feature doesn't appear in the schema or there has been an error fetching the |
| 115 | + configuration -> error/warning log would appear and value_if_missing is returned |
| 116 | + 2. feature exists and has no rules or no rules have matched -> return feature_default_value of |
| 117 | + the defined feature |
| 118 | + 3. feature exists and a rule matches -> rule_default_value of rule is returned |
| 119 | + """ |
| 120 | + if rules_context is None: |
| 121 | + rules_context = {} |
| 122 | + |
| 123 | + try: |
| 124 | + toggles_dict: Dict[str, Any] = self.get_configuration() |
| 125 | + except ConfigurationException: |
| 126 | + logger.error("unable to get feature toggles JSON, returning provided value_if_missing value") # noqa: E501 |
| 127 | + return value_if_missing |
| 128 | + |
| 129 | + feature: Dict[str, Dict] = toggles_dict.get(schema.FEATURES_KEY, {}).get(feature_name, None) |
| 130 | + if feature is None: |
| 131 | + logger.warning( |
| 132 | + f"feature does not appear in configuration, using provided value_if_missing, feature_name={feature_name}, value_if_missing={value_if_missing}" # noqa: E501 |
| 133 | + ) |
| 134 | + return value_if_missing |
| 135 | + |
| 136 | + rules_list = feature.get(schema.RULES_KEY) |
| 137 | + feature_default_value = feature.get(schema.FEATURE_DEFAULT_VAL_KEY) |
| 138 | + if not rules_list: |
| 139 | + # not rules but has a value |
| 140 | + logger.debug( |
| 141 | + f"no rules found, returning feature default value, feature_name={feature_name}, default_value={feature_default_value}" # noqa: E501 |
| 142 | + ) |
| 143 | + return feature_default_value |
| 144 | + # look for first rule match |
| 145 | + logger.debug( |
| 146 | + f"looking for rule match, feature_name={feature_name}, feature_default_value={feature_default_value}" |
| 147 | + ) # noqa: E501 |
| 148 | + return self._handle_rules( |
| 149 | + feature_name=feature_name, |
| 150 | + rules_context=rules_context, |
| 151 | + feature_default_value=feature_default_value, |
| 152 | + rules=rules_list, |
| 153 | + ) |
| 154 | + |
| 155 | + def get_all_enabled_feature_toggles(self, *, rules_context: Optional[Dict[str, Any]] = None) -> List[str]: |
| 156 | + """Get all enabled feature toggles while also taking into account rule_context (when a feature has defined rules) |
| 157 | +
|
| 158 | + Args: |
| 159 | + rules_context (Optional[Dict[str, Any]]): dict of attributes that you would like to match the rules |
| 160 | + against, can be {'tenant_id: 'X', 'username':' 'Y', 'region': 'Z'} etc. |
| 161 | +
|
| 162 | + Returns: |
| 163 | + List[str]: a list of all features name that are enabled by also taking into account |
| 164 | + rule_context (when a feature has defined rules) |
| 165 | + """ |
| 166 | + if rules_context is None: |
| 167 | + rules_context = {} |
| 168 | + try: |
| 169 | + toggles_dict: Dict[str, Any] = self.get_configuration() |
| 170 | + except ConfigurationException: |
| 171 | + logger.error("unable to get feature toggles JSON") # noqa: E501 |
| 172 | + return [] |
| 173 | + ret_list = [] |
| 174 | + features: Dict[str, Any] = toggles_dict.get(schema.FEATURES_KEY, {}) |
| 175 | + for feature_name, feature_dict_def in features.items(): |
| 176 | + rules_list = feature_dict_def.get(schema.RULES_KEY, []) |
| 177 | + feature_default_value = feature_dict_def.get(schema.FEATURE_DEFAULT_VAL_KEY) |
| 178 | + if feature_default_value and not rules_list: |
| 179 | + self._logger.debug( |
| 180 | + f"feature is enabled by default and has no defined rules, feature_name={feature_name}" |
| 181 | + ) |
| 182 | + ret_list.append(feature_name) |
| 183 | + elif self._handle_rules( |
| 184 | + feature_name=feature_name, |
| 185 | + rules_context=rules_context, |
| 186 | + feature_default_value=feature_default_value, |
| 187 | + rules=rules_list, |
| 188 | + ): |
| 189 | + self._logger.debug(f"feature's calculated value is True, feature_name={feature_name}") |
| 190 | + ret_list.append(feature_name) |
| 191 | + return ret_list |
0 commit comments