-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat: gapic centralization into api core #17628
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
Closed
Closed
Changes from 36 commits
Commits
Show all changes
53 commits
Select commit
Hold shift + click to select a range
aedbee9
feat: apply PEP 0810 lazy imports to google-cloud-compute
hebaalazzeh 4b3ba9d
fix: remove python version guard for PEP 810 lazy imports
hebaalazzeh c60e977
feat: centralize service-agnostic boilerplate into api_core for GAPIC…
hebaalazzeh 4463094
Update packages/google-api-core/google/api_core/gapic_v1/client_helpe…
hebaalazzeh 4d9bea2
refactor: optimize regex and update type hints in client_helpers
hebaalazzeh 54cf6a0
style: run black formatter on client_helpers.py
hebaalazzeh 69260e5
fix: address lint and mypy issues in api_core and kms
hebaalazzeh 46e0797
fix: address black formatting issue in client_helpers.py
hebaalazzeh a4513c4
fix: add underscore prefix to internal helpers in client_helpers.py
hebaalazzeh ad1c01f
test: add unit tests for gapic client_helpers
hebaalazzeh 1456ead
chore: revert experimental kms validation changes
hebaalazzeh 0ffcdd3
fix: resolve flake8 line length issues in tests
hebaalazzeh 2168bc0
chore: revert experimental PEP 0810 lazy loading in compute
hebaalazzeh 5abeb85
feat: centralize additional client helpers to api_core
hebaalazzeh 09243e9
test: mock missing google-auth mtls attributes
hebaalazzeh be2b472
style: remove manual 79-char line breaks to satisfy black
hebaalazzeh d386dfe
refactor: remove underscore prefix from gapic client helpers
hebaalazzeh 72d6561
fix: linting issues and add backward compatibility aliases for intern…
hebaalazzeh 6a44282
fix: skip test_client_helpers in non-grpc environments
hebaalazzeh 2353e82
fix: mock patch missing attribute in old google-auth versions
hebaalazzeh 7208833
feat: split client_helpers into domain-specific modules
hebaalazzeh 65861d9
chore: fix lint and formatting
hebaalazzeh 17acb05
chore: revert accidental formatting and generated files to fix dedupl…
hebaalazzeh 3e9393a
test: split test_client_helpers.py into domain-specific test files
hebaalazzeh 1888b2e
fix: address reviewer comments on api-core
hebaalazzeh 9a36216
test: restore grpc skip to test_method_helpers
hebaalazzeh f1ca030
fix: safely handle None in get_api_endpoint default_endpoint_template
hebaalazzeh 68f5263
chore: revert unrelated bigframes changes
hebaalazzeh 018d107
fix: make grpc-dependent imports conditional in gapic_v1/__init__.py …
hebaalazzeh f286631
chore: fix black formatting in gapic_v1/__init__.py
hebaalazzeh b830151
fix: add noqa flags to unused conditional imports and remove unused p…
hebaalazzeh a175e88
chore: trigger CI to retry flaky bigframes test
hebaalazzeh 575244e
chore: revert unrelated changes to bigframes, bigquery, and pandas-gbq
hebaalazzeh a1341f0
fix: isolate unit tests from workstation mTLS environments and fix co…
hebaalazzeh dcce1e7
test: resolve timing flake in test_bidi.py by adding tolerance to wai…
hebaalazzeh e0f3f85
merge: merge origin/main into feat/gapic-centralization-api-core
hebaalazzeh b8a3b32
Update packages/google-api-core/tests/unit/gapic/test_routing.py
hebaalazzeh 317c7ec
Update packages/google-api-core/google/api_core/gapic_v1/_method_help…
hebaalazzeh b4b9450
Update packages/google-api-core/google/api_core/gapic_v1/_routing.py
hebaalazzeh b4fe2d0
Update packages/google-api-core/tests/unit/gapic/test_client_cert.py
hebaalazzeh 5471865
Update packages/google-api-core/tests/unit/gapic/test_config_helpers.py
hebaalazzeh ed6438e
Update packages/google-api-core/google/api_core/gapic_v1/_routing.py
hebaalazzeh 393fd85
fix: address code review feedback for GAPIC centralization
hebaalazzeh 2fae23a
fix: add grpc check back to test modules to prevent ImportError on no…
hebaalazzeh 70445ef
style: run black formatter on gapic test files
hebaalazzeh 2cdabf9
Merge branch 'main' into feat/gapic-centralization-api-core
hebaalazzeh 6bf0e26
fix(gapic): resolve linting errors from redundant eager imports
hebaalazzeh 6844bd2
fix: remove unnecessary grpc check in test_client_cert.py
hebaalazzeh 94e51a1
chore: remove unused grpc import checks in test files
hebaalazzeh ac1c090
Merge branch 'main' into feat/gapic-centralization-api-core
hebaalazzeh 79c74a4
refactor(api-core): rename gapic internal helper modules and function…
hebaalazzeh 5889da8
style(api-core): run black formatter on gapic centralization files
hebaalazzeh 4eb40c0
merge: merge origin/main into feat/gapic-centralization-api-core
hebaalazzeh 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
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
78 changes: 78 additions & 0 deletions
78
packages/google-api-core/google/api_core/gapic_v1/_client_cert.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,78 @@ | ||
| # -*- 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. | ||
| # | ||
|
|
||
| """Helpers for client certificate handling and mTLS authentication.""" | ||
|
|
||
| import os | ||
| from typing import Any, Optional | ||
|
|
||
| from google.auth.transport import mtls # type: ignore | ||
|
|
||
|
|
||
| def use_client_cert_effective() -> bool: | ||
|
hebaalazzeh marked this conversation as resolved.
|
||
| """Returns whether client certificate should be used for mTLS if the | ||
| google-auth version supports should_use_client_cert automatic mTLS | ||
| enablement. | ||
|
|
||
| Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. | ||
|
|
||
| Returns: | ||
| bool: whether client certificate should be used for mTLS | ||
| Raises: | ||
| ValueError: (If using a version of google-auth without | ||
| should_use_client_cert and GOOGLE_API_USE_CLIENT_CERTIFICATE is | ||
| set to an unexpected value.) | ||
| """ | ||
| # check if google-auth version supports should_use_client_cert for | ||
| # automatic mTLS enablement | ||
| if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER | ||
| return mtls.should_use_client_cert() | ||
| else: # pragma: NO COVER | ||
| # if unsupported, fallback to reading from env var | ||
| use_client_cert_str = os.getenv( | ||
| "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" | ||
| ).lower() | ||
| if use_client_cert_str not in ("true", "false"): | ||
| raise ValueError( | ||
| "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` " | ||
| "must be either `true` or `false`" | ||
| ) | ||
| return use_client_cert_str == "true" | ||
|
|
||
|
|
||
| def get_client_cert_source( | ||
| provided_cert_source: Optional[Any], use_cert_flag: bool | ||
|
hebaalazzeh marked this conversation as resolved.
Outdated
|
||
| ) -> Optional[Any]: | ||
|
hebaalazzeh marked this conversation as resolved.
Outdated
|
||
| """Return the client cert source to be used by the client. | ||
|
|
||
| Args: | ||
| provided_cert_source (Callable[[], Tuple[bytes, bytes]]): The client certificate source provided. | ||
| use_cert_flag (bool): A flag indicating whether to use the | ||
| client certificate. | ||
|
|
||
| Returns: | ||
| Callable[[], Tuple[bytes, bytes]] or None: The client cert source to be used by the client. | ||
| """ | ||
| client_cert_source = None | ||
| if use_cert_flag: | ||
| if provided_cert_source: | ||
| client_cert_source = provided_cert_source | ||
| elif ( | ||
| hasattr(mtls, "has_default_client_cert_source") | ||
| and mtls.has_default_client_cert_source() | ||
| ): | ||
| client_cert_source = mtls.default_client_cert_source() | ||
| return client_cert_source | ||
49 changes: 49 additions & 0 deletions
49
packages/google-api-core/google/api_core/gapic_v1/_config_helpers.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,49 @@ | ||
| # -*- 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. | ||
| # | ||
|
|
||
| """Helpers for parsing environment variables.""" | ||
|
|
||
| import os | ||
| from typing import Optional, Tuple | ||
|
|
||
| from google.api_core.gapic_v1._client_cert import use_client_cert_effective | ||
| from google.auth.exceptions import MutualTLSChannelError # type: ignore | ||
|
|
||
|
|
||
| def read_environment_variables() -> Tuple[bool, str, Optional[str]]: | ||
| """Returns the environment variables used by the client. | ||
|
|
||
| Returns: | ||
| Tuple[bool, str, Optional[str]]: returns the | ||
| GOOGLE_API_USE_CLIENT_CERTIFICATE, GOOGLE_API_USE_MTLS_ENDPOINT, | ||
| and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. | ||
|
|
||
| Raises: | ||
| ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not | ||
| any of ["true", "false"]. | ||
| google.auth.exceptions.MutualTLSChannelError: If | ||
| GOOGLE_API_USE_MTLS_ENDPOINT is not any of | ||
| ["auto", "never", "always"]. | ||
| """ | ||
| use_client_cert = use_client_cert_effective() | ||
| use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() | ||
| universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") | ||
| if use_mtls_endpoint not in ("auto", "never", "always"): | ||
| raise MutualTLSChannelError( | ||
| "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` " | ||
| "must be `never`, `auto` or `always`" | ||
| ) | ||
| return use_client_cert, use_mtls_endpoint, universe_domain_env |
51 changes: 51 additions & 0 deletions
51
packages/google-api-core/google/api_core/gapic_v1/_method_helpers.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,51 @@ | ||
| # -*- 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. | ||
| # | ||
|
|
||
| """Helpers for method requests.""" | ||
|
|
||
| import uuid | ||
| from typing import Any | ||
|
|
||
|
|
||
| def setup_request_id(request: Any, field_name: str, is_proto3_optional: bool) -> None: | ||
| """Populate a UUID4 field in the request if it is not already set. | ||
|
|
||
| Args: | ||
| request (Union[google.protobuf.message.Message, dict]): The | ||
| request object. | ||
| field_name (str): The name of the field to populate. | ||
| is_proto3_optional (bool): Whether the field is proto3 optional. | ||
| """ | ||
| if isinstance(request, dict): | ||
| if is_proto3_optional: | ||
| if field_name not in request: | ||
| request[field_name] = str(uuid.uuid4()) | ||
| elif not request.get(field_name): | ||
| request[field_name] = str(uuid.uuid4()) | ||
| return | ||
|
|
||
| if is_proto3_optional: | ||
| try: | ||
| # Pure protobuf messages | ||
| if not request.HasField(field_name): | ||
| setattr(request, field_name, str(uuid.uuid4())) | ||
| except (AttributeError, ValueError): | ||
| # Proto-plus messages or other objects | ||
| if field_name not in request: | ||
|
hebaalazzeh marked this conversation as resolved.
Outdated
|
||
| setattr(request, field_name, str(uuid.uuid4())) | ||
| else: | ||
| if not getattr(request, field_name): | ||
| setattr(request, field_name, str(uuid.uuid4())) | ||
102 changes: 102 additions & 0 deletions
102
packages/google-api-core/google/api_core/gapic_v1/_routing.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,102 @@ | ||
| # -*- 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. | ||
| # | ||
|
|
||
| """Helpers for routing and endpoint resolution.""" | ||
|
|
||
| import re | ||
| from typing import Any, Optional | ||
|
|
||
| from google.auth.exceptions import MutualTLSChannelError # type: ignore | ||
|
|
||
| _MTLS_ENDPOINT_RE = re.compile( | ||
| r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?" | ||
| r"(?P<googledomain>\.googleapis\.com)?" | ||
| ) | ||
|
|
||
|
|
||
| def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: | ||
| """Converts api endpoint to mTLS endpoint. | ||
|
|
||
| Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to | ||
| "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. | ||
| Args: | ||
| api_endpoint (Optional[str]): the api endpoint to convert. | ||
| Returns: | ||
| Optional[str]: converted mTLS api endpoint. | ||
| """ | ||
| if not api_endpoint: | ||
| return api_endpoint | ||
|
|
||
| m = _MTLS_ENDPOINT_RE.match(api_endpoint) | ||
| if m is None: | ||
| # Could not parse api_endpoint; return as-is. | ||
| return api_endpoint | ||
|
|
||
| name, mtls_group, sandbox, googledomain = m.groups() | ||
| if mtls_group or not googledomain: | ||
| return api_endpoint | ||
|
|
||
| if sandbox: | ||
| return api_endpoint.replace( | ||
| "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" | ||
| ) | ||
|
|
||
| return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") | ||
|
|
||
|
|
||
| def get_api_endpoint( | ||
| api_override: Optional[str], | ||
| client_cert_source: Optional[Any], | ||
| universe_domain: str, | ||
| use_mtls_endpoint: str, | ||
| default_universe: str, | ||
| default_mtls_endpoint: Optional[str], | ||
| default_endpoint_template: Optional[str], | ||
| ) -> Optional[str]: | ||
| """Return the API endpoint used by the client.""" | ||
| if api_override is not None: | ||
| return api_override | ||
| elif use_mtls_endpoint == "always" or ( | ||
| use_mtls_endpoint == "auto" and client_cert_source | ||
| ): | ||
| if universe_domain != default_universe: | ||
|
hebaalazzeh marked this conversation as resolved.
Outdated
|
||
| raise MutualTLSChannelError( | ||
| f"mTLS is not supported in any universe other than " | ||
| f"{default_universe}." | ||
| ) | ||
| return default_mtls_endpoint | ||
| else: | ||
| return ( | ||
| default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) | ||
| if default_endpoint_template | ||
| else None | ||
| ) | ||
|
|
||
|
|
||
| def get_universe_domain( | ||
| client_universe_domain: Optional[str], | ||
| universe_domain_env: Optional[str], | ||
| default_universe: str, | ||
| ) -> str: | ||
| """Return the universe domain used by the client.""" | ||
| universe_domain = default_universe | ||
| if client_universe_domain is not None: | ||
| universe_domain = client_universe_domain | ||
| elif universe_domain_env is not None: | ||
| universe_domain = universe_domain_env | ||
| if len(universe_domain.strip()) == 0: | ||
|
hebaalazzeh marked this conversation as resolved.
Outdated
|
||
| raise ValueError("Universe Domain cannot be an empty string.") | ||
| return universe_domain | ||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| # -*- 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. | ||
|
|
||
| import os | ||
| from unittest import mock | ||
| import pytest | ||
|
|
||
|
|
||
| @pytest.fixture(scope="session", autouse=True) | ||
| def mock_mtls_env(): | ||
| """Autouse session-scoped fixture to isolate unit tests from workstation mTLS environments.""" | ||
| with mock.patch.dict( | ||
| os.environ, | ||
| { | ||
| "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", | ||
| "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false", | ||
| }, | ||
| ): | ||
| yield |
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.