-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat: Add Feature Gating configuration helpers. #17524
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
+363
−0
Merged
Changes from 19 commits
Commits
Show all changes
34 commits
Select commit
Hold shift + click to select a range
959e752
feat: Add OpenTelemetry environment variable and options configuratio…
chalmerlowe 071ae3c
feat(observability): add base OpenTelemetry span enricher interceptor
chalmerlowe 626ed58
test(observability): add test-only environment variable overrides and…
chalmerlowe c867011
feat(observability): simplify options resolver to tracing-only
chalmerlowe 3f6ba78
feat(observability): remove OtelSpanEnricher from current PR
chalmerlowe 35f0736
test(o11y): add coverage for environment overrides and fallback
chalmerlowe fa5d234
test(o11y): improve test isolation in environment overrides
chalmerlowe c19700e
test(o11y): eliminate 'traces' references and improve test readability
chalmerlowe 5aedd86
refactor(o11y): add license header, reorganize variables and improve …
chalmerlowe 4e49506
chore(o11y): apply black formatting fixes to tests
chalmerlowe 4e950c1
feat(otel): align resolve_feature_flags with strict LLD requirements
chalmerlowe c6fe8a6
test(o11y): add comprehensive tests for generic feature resolver
chalmerlowe 391fe4c
feat(o11y): refactor resolve_feature_flags to be generic and strictly…
chalmerlowe 0f92c35
style(o11y): apply black formatting to options.py and test_options.py
chalmerlowe 2fb0057
docs(o11y): revise terminology to remove 'gate' metaphor
chalmerlowe 57014ab
fix(o11y): add warning for malformed environment variables
chalmerlowe 1c17863
refactor(o11y): make _has_provider more robust by using getattr
chalmerlowe 8dd6175
test(o11y): add missing tests for experimental path without provider
chalmerlowe 9fc0088
style(o11y): apply black formatting to test_options.py
chalmerlowe 11313ec
feat: move observability resolver to general purpose feature_gating_h…
chalmerlowe 9b4df5c
refactor: remove custom test overrides and use monkeypatch
chalmerlowe 745cceb
chore: remove opentelemetry-api dependency from google-api-core
chalmerlowe d8d313b
style: apply black formatting to test_feature_gating_helpers.py
chalmerlowe 71330d9
refactor: rename parameters and enforce keyword-only in feature gating
chalmerlowe bd6d88f
feat: add dunder key guardrail to feature gating
chalmerlowe f667db5
refactor: update tests to use private module name
chalmerlowe c72bc30
refactor: modernize type hints in feature gating helpers
chalmerlowe bff8b6a
feat: use custom FeatureGatingError in feature gating helpers
chalmerlowe 526c0b8
refactor: rename _has_provider to _has_feature_key for better general…
chalmerlowe 050a857
docs: scrub remaining 'provider' terminology from helper module
chalmerlowe d9aff39
chore: apply ruff formatting to feature gating helpers
chalmerlowe 23b87c0
Update packages/google-api-core/testing/constraints-3.10.txt
chalmerlowe d8065b1
Update packages/google-api-core/testing/constraints-async-rest-3.10.txt
chalmerlowe 1e98bde
Apply suggestion from @chalmerlowe
chalmerlowe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
11 changes: 11 additions & 0 deletions
11
packages/google-api-core/google/api_core/observability/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| from .options import ( | ||
| clear_test_env_overrides, | ||
| resolve_feature_flags, | ||
| set_test_env_override, | ||
| ) | ||
|
|
||
| __all__ = [ | ||
| "resolve_feature_flags", | ||
| "set_test_env_override", | ||
| "clear_test_env_overrides", | ||
| ] | ||
149 changes: 149 additions & 0 deletions
149
packages/google-api-core/google/api_core/observability/options.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| # -*- coding: utf-8 -*- | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
|
|
||
| """Observability environment variable and client options resolution helpers.""" | ||
|
|
||
| import os | ||
| import warnings | ||
| from typing import Any, Dict, Optional, Union | ||
|
|
||
| # Allowed truthy and falsy patterns for environment variables | ||
| _TRUTHY_VALUES = ("y", "yes", "t", "true", "on", "1") | ||
| _FALSY_VALUES = ("n", "no", "f", "false", "off", "0") | ||
|
|
||
| # Test-only overrides for environment variables. | ||
| # This is intended ONLY for unit/integration testing to prevent mutating | ||
| # os.environ. | ||
| _TEST_ENV_OVERRIDES: Dict[str, bool] = {} | ||
|
|
||
|
|
||
| def _strtobool(val: str) -> Optional[bool]: | ||
| """Convert a string representation of truth to a boolean.""" | ||
| clean_val = val.lower().strip() | ||
| if not clean_val: | ||
| return None | ||
| if clean_val in _TRUTHY_VALUES: | ||
| return True | ||
| if clean_val in _FALSY_VALUES: | ||
| return False | ||
| raise ValueError(f"Invalid truth value: {val!r}") | ||
|
|
||
|
|
||
| def set_test_env_override(name: str, value: Optional[bool]) -> None: | ||
| """Sets a test-only override for a specific environment variable. | ||
|
|
||
| This is intended ONLY for unit/integration testing to prevent mutating | ||
| os.environ. | ||
|
daniel-sanche marked this conversation as resolved.
Outdated
|
||
| """ | ||
| if value is None: | ||
| _TEST_ENV_OVERRIDES.pop(name, None) | ||
| else: | ||
| _TEST_ENV_OVERRIDES[name] = value | ||
|
|
||
|
|
||
| def clear_test_env_overrides() -> None: | ||
| """Clears all test-only overrides.""" | ||
| _TEST_ENV_OVERRIDES.clear() | ||
|
|
||
|
|
||
| def _get_env_bool(name: str) -> Optional[bool]: | ||
| """Retrieve the boolean value of an environment variable.""" | ||
| if name in _TEST_ENV_OVERRIDES: | ||
| return _TEST_ENV_OVERRIDES[name] | ||
|
daniel-sanche marked this conversation as resolved.
Outdated
|
||
|
|
||
| val = os.getenv(name) | ||
| if val is None: | ||
| return None | ||
| try: | ||
| return _strtobool(val) | ||
| except ValueError as e: | ||
| warnings.warn(f"Ignored invalid value for {name}: {e}", RuntimeWarning) | ||
| return None | ||
|
|
||
|
|
||
| def _has_provider( | ||
| client_options: Optional[Union[Dict[str, Any], Any]], provider_key: str | ||
| ) -> bool: | ||
| """Checks if a specific provider key is present and not None in client_options.""" | ||
| if client_options is None: | ||
| return False | ||
|
|
||
| if isinstance(client_options, dict): | ||
| return client_options.get(provider_key) is not None | ||
|
|
||
| return getattr(client_options, provider_key, None) is not None | ||
|
|
||
|
|
||
| def resolve_feature_flags( | ||
| env_var: str, | ||
| provider_key: str, | ||
| client_options: Optional[Union[Dict[str, Any], Any]] = None, | ||
| ) -> bool: | ||
| """Determines if a feature is enabled based on environment variables and client options. | ||
|
|
||
| Behavior depends on whether the `env_var` name contains "EXPERIMENTAL": | ||
|
|
||
| - **Experimental Path** (env_var contains "EXPERIMENTAL"): | ||
| Strict control. Requires the environment variable to be explicitly 'true'. | ||
| If a programmatic provider is passed but the environment variable is not 'true', | ||
| raises ValueError (Fail Fast). | ||
|
|
||
| - **GA Path** (env_var does not contain "EXPERIMENTAL"): | ||
| Standard precedence. Enabled if a programmatic provider is passed, | ||
| otherwise falls back to the environment variable value. | ||
|
|
||
| Args: | ||
| env_var: The name of the environment variable controlling this feature. | ||
| provider_key: The key in client_options/attributes for the programmatic provider. | ||
| client_options: A dictionary or object containing client configuration. | ||
|
|
||
| Returns: | ||
| bool: True if the feature is resolved to enabled, False otherwise. | ||
|
|
||
| Raises: | ||
| ValueError: If a provider is provided for an experimental feature without enabling the experimental environment variable. | ||
| """ | ||
|
|
||
| # Check for programmatic feature provider | ||
| has_provider = _has_provider(client_options, provider_key) | ||
|
|
||
| # Read environment variable | ||
| env_var_setting = _get_env_bool(env_var) | ||
|
|
||
| # EXPERIMENTAL PATH: | ||
| # Resolution Hierarchy: | ||
| # 1. EXPERIMENTAL Environment Variable | ||
| # 2. Fail Fast if Provider present but EXPERIMENTAL Environment Variable is not enabled | ||
| if "EXPERIMENTAL" in env_var: | ||
| # Fail Fast if provider present but experimental environment variable is not enabled | ||
| if env_var_setting is not True and has_provider: | ||
| raise ValueError( | ||
| f"Experimental feature requires {env_var} to be set to 'true' to use programmatic providers." | ||
| ) | ||
|
|
||
| return bool(env_var_setting) | ||
|
|
||
| # GENERAL AVAILABILITY PATH: | ||
| # Resolution Hierarchy: | ||
| # 1. Programmatic Provider | ||
| # 2. Environment Variable | ||
|
|
||
| # Check Programmatic Provider | ||
| if has_provider: | ||
| return True | ||
|
|
||
| # Check Environment Variable | ||
| return bool(env_var_setting) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.