From bfb40b0151ea38c806ecb8f5d41f8269065e4abe Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Thu, 3 Sep 2026 06:30:13 -0400 Subject: [PATCH 01/43] feat(core): add request hook to inject GCP resource and project attributes --- .../google/api_core/_observability.py | 55 ++++++++++++++++++- .../tests/unit/test_observability.py | 47 +++++++++++++++- 2 files changed, 98 insertions(+), 4 deletions(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index f101cec28f5c..262b9beda34d 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -64,6 +64,55 @@ def is_otel_capabilities_enabled( return False +def _extract_t4_attributes(request: Any) -> dict[str, Any]: + """Extracts Google Cloud semantic and resource attributes from a gRPC request object. + + Args: + request: The gRPC request object. + + Returns: + dict[str, Any]: A dictionary of semantic attributes. + """ + attrs: dict[str, Any] = {} + if request is None: + return attrs + + name = getattr(request, "name", None) + if name and isinstance(name, str): + attrs["gcp.resource.name"] = name + if "projects/" in name: + parts = name.split("/") + try: + idx = parts.index("projects") + if idx + 1 < len(parts): + attrs["gcp.project_id"] = parts[idx + 1] + except ValueError: + pass + + parent = getattr(request, "parent", None) + if parent and isinstance(parent, str): + attrs["gcp.resource.parent"] = parent + if "gcp.project_id" not in attrs and "projects/" in parent: + parts = parent.split("/") + try: + idx = parts.index("projects") + if idx + 1 < len(parts): + attrs["gcp.project_id"] = parts[idx + 1] + except ValueError: + pass + + return attrs + + +def _client_request_hook(span: Any, request: Any) -> None: + """OpenTelemetry client request hook to inject GCP resource attributes into the span.""" + if span is None or not getattr(span, "is_recording", lambda: True)(): + return + attrs = _extract_t4_attributes(request) + for key, value in attrs.items(): + span.set_attribute(key, value) + + def _get_tracer_provider( client_options: ClientOptions | dict[str, Any] | None = None, ) -> opentelemetry.trace.TracerProvider | None: @@ -102,7 +151,8 @@ def get_otel_interceptor( import opentelemetry.instrumentation.grpc as otel_grpc # type: ignore[import-not-found] interceptor: ClientInterceptor = otel_grpc.client_interceptor( - tracer_provider=_get_tracer_provider(client_options) + tracer_provider=_get_tracer_provider(client_options), + request_hook=_client_request_hook, ) def otel_interceptor(channel: grpc.Channel) -> grpc.Channel: @@ -131,5 +181,6 @@ def get_otel_async_interceptor( import opentelemetry.instrumentation.grpc as otel_grpc # type: ignore[import-not-found] return otel_grpc.aio_client_interceptors( - tracer_provider=_get_tracer_provider(client_options) + tracer_provider=_get_tracer_provider(client_options), + request_hook=_client_request_hook, ) diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 8e8964e66264..a512ea068981 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -162,7 +162,8 @@ def test_get_otel_interceptor_enabled(monkeypatch): assert callable(interceptor) mock_otel_grpc.client_interceptor.assert_called_once_with( - tracer_provider=mock_tracer_provider + tracer_provider=mock_tracer_provider, + request_hook=_observability._client_request_hook, ) result = interceptor(mock_raw_channel) @@ -251,5 +252,47 @@ def test_get_otel_async_interceptor_enabled(monkeypatch): result = _observability.get_otel_async_interceptor(client_options=options) assert result is mock_async_interceptors mock_otel_grpc.aio_client_interceptors.assert_called_once_with( - tracer_provider=mock_tracer_provider + tracer_provider=mock_tracer_provider, + request_hook=_observability._client_request_hook, ) + + +def test_extract_t4_attributes(): + """Proves that _extract_t4_attributes correctly extracts GCP resource name, + parent, and project ID from gRPC request objects. + """ + assert _observability._extract_t4_attributes(None) == {} + + # With name + req_name = mock.Mock(spec=["name"], name="req_name") + req_name.name = "projects/my-project/secrets/my-secret" + attrs = _observability._extract_t4_attributes(req_name) + assert attrs["gcp.resource.name"] == "projects/my-project/secrets/my-secret" + assert attrs["gcp.project_id"] == "my-project" + + # With parent + req_parent = mock.Mock(spec=["parent"], name="req_parent") + req_parent.parent = "projects/parent-project" + attrs = _observability._extract_t4_attributes(req_parent) + assert attrs["gcp.resource.parent"] == "projects/parent-project" + assert attrs["gcp.project_id"] == "parent-project" + + +def test_client_request_hook(): + """Proves that _client_request_hook attaches extracted T4 attributes to recording spans.""" + # Non-recording span should not set attributes + mock_span_non_rec = mock.Mock() + mock_span_non_rec.is_recording.return_value = False + _observability._client_request_hook(mock_span_non_rec, mock.Mock()) + mock_span_non_rec.set_attribute.assert_not_called() + + # Recording span should set attributes + mock_span_rec = mock.Mock() + mock_span_rec.is_recording.return_value = True + req = mock.Mock(name="req") + req.name = "projects/my-proj/secrets/s1" + _observability._client_request_hook(mock_span_rec, req) + mock_span_rec.set_attribute.assert_any_call( + "gcp.resource.name", "projects/my-proj/secrets/s1" + ) + mock_span_rec.set_attribute.assert_any_call("gcp.project_id", "my-proj") From 87ca9b865fd794952bf5936e669332a59f36465e Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 9 Sep 2026 08:42:46 -0400 Subject: [PATCH 02/43] feat(core): implement complete T4 gRPC telemetry capture and response hook - Add rpc.system.name: 'grpc' - Extract server.address and server.port from client options endpoint - Extract gcp.grpc.resend_count from request resend count - Extract gcp.resource.destination.id from request name or parent - Add _client_response_hook for status code, error.type, and status.message - Plumb response_hook into get_otel_interceptor and get_otel_async_interceptor --- .../google/api_core/_observability.py | 158 ++++++++++++++---- 1 file changed, 126 insertions(+), 32 deletions(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index 262b9beda34d..b3309bae8a63 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -25,7 +25,7 @@ if TYPE_CHECKING: # flake8: grpc, trace, and ClientInterceptor are imported only for static analysis and type annotations - # The `# noqa: F401` comment avoids flake8 "imported but not used" errors. + # The 'noqa: F401' comment avoids flake8 "imported but not used" errors. import grpc # noqa: F401 import opentelemetry.trace # noqa: F401 @@ -64,8 +64,56 @@ def is_otel_capabilities_enabled( return False +_STATUS_CODE_NAMES = { + 0: "OK", + 1: "CANCELLED", + 2: "UNKNOWN", + 3: "INVALID_ARGUMENT", + 4: "DEADLINE_EXCEEDED", + 5: "NOT_FOUND", + 6: "ALREADY_EXISTS", + 7: "PERMISSION_DENIED", + 8: "RESOURCE_EXHAUSTED", + 9: "FAILED_PRECONDITION", + 10: "ABORTED", + 11: "OUT_OF_RANGE", + 12: "UNIMPLEMENTED", + 13: "INTERNAL", + 14: "UNAVAILABLE", + 15: "DATA_LOSS", + 16: "UNAUTHENTICATED", +} + + +def _extract_endpoint_attributes( + client_options: ClientOptions | dict[str, Any] | None = None, +) -> dict[str, Any]: + """Extracts server.address and server.port from client options if present.""" + attrs: dict[str, Any] = {} + endpoint = None + if isinstance(client_options, dict): + endpoint = client_options.get("api_endpoint") + elif client_options is not None: + endpoint = getattr(client_options, "api_endpoint", None) + + if endpoint and isinstance(endpoint, str): + clean = endpoint.replace("http://", "").replace("https://", "").strip("/") + if clean: + if ":" in clean: + host, port_str = clean.split(":", 1) + attrs["server.address"] = host + try: + attrs["server.port"] = int(port_str) + except ValueError: + attrs["server.port"] = 443 + else: + attrs["server.address"] = clean + attrs["server.port"] = 443 + return attrs + + def _extract_t4_attributes(request: Any) -> dict[str, Any]: - """Extracts Google Cloud semantic and resource attributes from a gRPC request object. + """Extracts Google Cloud T4 semantic and resource attributes from a gRPC request object. Args: request: The gRPC request object. @@ -73,44 +121,74 @@ def _extract_t4_attributes(request: Any) -> dict[str, Any]: Returns: dict[str, Any]: A dictionary of semantic attributes. """ - attrs: dict[str, Any] = {} + attrs: dict[str, Any] = { + "rpc.system.name": "grpc", + } if request is None: return attrs - name = getattr(request, "name", None) - if name and isinstance(name, str): - attrs["gcp.resource.name"] = name - if "projects/" in name: - parts = name.split("/") - try: - idx = parts.index("projects") - if idx + 1 < len(parts): - attrs["gcp.project_id"] = parts[idx + 1] - except ValueError: - pass + resend_count = getattr(request, "resend_count", None) + if isinstance(resend_count, int) and resend_count > 0: + attrs["gcp.grpc.resend_count"] = resend_count - parent = getattr(request, "parent", None) - if parent and isinstance(parent, str): - attrs["gcp.resource.parent"] = parent - if "gcp.project_id" not in attrs and "projects/" in parent: - parts = parent.split("/") - try: - idx = parts.index("projects") - if idx + 1 < len(parts): - attrs["gcp.project_id"] = parts[idx + 1] - except ValueError: - pass + name = getattr(request, "name", None) + if isinstance(name, str) and name: + attrs["gcp.resource.destination.id"] = name + else: + parent = getattr(request, "parent", None) + if isinstance(parent, str) and parent: + attrs["gcp.resource.destination.id"] = parent return attrs -def _client_request_hook(span: Any, request: Any) -> None: - """OpenTelemetry client request hook to inject GCP resource attributes into the span.""" +def _make_client_request_hook( + endpoint_attrs: dict[str, Any] | None = None, +) -> Callable[[Any, Any], None]: + """Creates an OpenTelemetry client request hook with optional endpoint attributes.""" + + def client_request_hook(span: Any, request: Any) -> None: + if span is None or not getattr(span, "is_recording", lambda: True)(): + return + attrs = _extract_t4_attributes(request) + if endpoint_attrs: + attrs.update(endpoint_attrs) + for key, value in attrs.items(): + span.set_attribute(key, value) + + return client_request_hook + + +_client_request_hook = _make_client_request_hook() + + +def _client_response_hook(span: Any, response: Any) -> None: + """OpenTelemetry client response hook to inject gRPC response status attributes into the span.""" if span is None or not getattr(span, "is_recording", lambda: True)(): return - attrs = _extract_t4_attributes(request) - for key, value in attrs.items(): - span.set_attribute(key, value) + + status_str = "OK" + code_fn = getattr(response, "code", None) + if callable(code_fn): + try: + code_val = code_fn() + status_str = getattr(code_val, "name", None) or _STATUS_CODE_NAMES.get( + code_val, str(code_val) + ) + except Exception: + pass + + span.set_attribute("rpc.response.status_code", status_str) + if status_str != "OK": + span.set_attribute("error.type", status_str) + details_fn = getattr(response, "details", None) + if callable(details_fn): + try: + details = details_fn() + if details: + span.set_attribute("status.message", str(details)) + except Exception: + pass def _get_tracer_provider( @@ -150,9 +228,17 @@ def get_otel_interceptor( import opentelemetry.instrumentation.grpc as otel_grpc # type: ignore[import-not-found] + endpoint_attrs = _extract_endpoint_attributes(client_options) + request_hook = ( + _make_client_request_hook(endpoint_attrs) + if endpoint_attrs + else _client_request_hook + ) + interceptor: ClientInterceptor = otel_grpc.client_interceptor( tracer_provider=_get_tracer_provider(client_options), - request_hook=_client_request_hook, + request_hook=request_hook, + response_hook=_client_response_hook, ) def otel_interceptor(channel: grpc.Channel) -> grpc.Channel: @@ -180,7 +266,15 @@ def get_otel_async_interceptor( # Ignored by mypy: Optional dependency only loaded if early-return is skipped import opentelemetry.instrumentation.grpc as otel_grpc # type: ignore[import-not-found] + endpoint_attrs = _extract_endpoint_attributes(client_options) + request_hook = ( + _make_client_request_hook(endpoint_attrs) + if endpoint_attrs + else _client_request_hook + ) + return otel_grpc.aio_client_interceptors( tracer_provider=_get_tracer_provider(client_options), - request_hook=_client_request_hook, + request_hook=request_hook, + response_hook=_client_response_hook, ) From 451e17bacfe278674f334c7968107de6f0b5206f Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 9 Sep 2026 08:42:52 -0400 Subject: [PATCH 03/43] test(core): add comprehensive unit tests for T4 gRPC telemetry and hooks - Test endpoint attribute parsing across host/port variations - Test destination id and resend count extraction - Test client request and response hooks covering all status and error cases - Test interceptor creation and custom endpoint attribute propagation - Achieve 100% statement and branch coverage on _observability.py --- .../tests/unit/test_observability.py | 279 ++++++++++++++++-- 1 file changed, 256 insertions(+), 23 deletions(-) diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index a512ea068981..5bfa72df64cd 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -13,6 +13,7 @@ # limitations under the License. import sys +import types from unittest import mock import pytest @@ -164,6 +165,7 @@ def test_get_otel_interceptor_enabled(monkeypatch): mock_otel_grpc.client_interceptor.assert_called_once_with( tracer_provider=mock_tracer_provider, request_hook=_observability._client_request_hook, + response_hook=_observability._client_response_hook, ) result = interceptor(mock_raw_channel) @@ -254,28 +256,84 @@ def test_get_otel_async_interceptor_enabled(monkeypatch): mock_otel_grpc.aio_client_interceptors.assert_called_once_with( tracer_provider=mock_tracer_provider, request_hook=_observability._client_request_hook, + response_hook=_observability._client_response_hook, ) -def test_extract_t4_attributes(): - """Proves that _extract_t4_attributes correctly extracts GCP resource name, - parent, and project ID from gRPC request objects. - """ - assert _observability._extract_t4_attributes(None) == {} - - # With name - req_name = mock.Mock(spec=["name"], name="req_name") - req_name.name = "projects/my-project/secrets/my-secret" - attrs = _observability._extract_t4_attributes(req_name) - assert attrs["gcp.resource.name"] == "projects/my-project/secrets/my-secret" - assert attrs["gcp.project_id"] == "my-project" +def test_extract_endpoint_attributes(): + """Proves that _extract_endpoint_attributes correctly parses server.address and server.port.""" + # None or empty options + assert _observability._extract_endpoint_attributes(None) == {} + assert _observability._extract_endpoint_attributes({}) == {} + assert ( + _observability._extract_endpoint_attributes(ClientOptions(api_endpoint=None)) + == {} + ) - # With parent - req_parent = mock.Mock(spec=["parent"], name="req_parent") - req_parent.parent = "projects/parent-project" - attrs = _observability._extract_t4_attributes(req_parent) - assert attrs["gcp.resource.parent"] == "projects/parent-project" - assert attrs["gcp.project_id"] == "parent-project" + # Dict options with standard endpoint + dict_opts = {"api_endpoint": "secretmanager.googleapis.com"} + attrs = _observability._extract_endpoint_attributes(dict_opts) + assert attrs["server.address"] == "secretmanager.googleapis.com" + assert attrs["server.port"] == 443 + + # ClientOptions with custom port + custom_opts = ClientOptions(api_endpoint="https://my-custom-host.com:8443/") + attrs = _observability._extract_endpoint_attributes(custom_opts) + assert attrs["server.address"] == "my-custom-host.com" + assert attrs["server.port"] == 8443 + + # Invalid port string falls back to 443 + invalid_port_opts = ClientOptions(api_endpoint="my-custom-host.com:invalid_port") + attrs = _observability._extract_endpoint_attributes(invalid_port_opts) + assert attrs["server.address"] == "my-custom-host.com" + assert attrs["server.port"] == 443 + + +@pytest.mark.parametrize( + "req,expected_attrs", + [ + (None, {"rpc.system.name": "grpc"}), + (types.SimpleNamespace(), {"rpc.system.name": "grpc"}), + ( + types.SimpleNamespace(name="projects/p1/secrets/s1"), + { + "rpc.system.name": "grpc", + "gcp.resource.destination.id": "projects/p1/secrets/s1", + }, + ), + ( + types.SimpleNamespace(parent="projects/parent-p1"), + { + "rpc.system.name": "grpc", + "gcp.resource.destination.id": "projects/parent-p1", + }, + ), + ( + types.SimpleNamespace( + name="projects/p1/secrets/s1", parent="projects/parent-p1" + ), + { + "rpc.system.name": "grpc", + "gcp.resource.destination.id": "projects/p1/secrets/s1", + }, + ), + ( + types.SimpleNamespace(name="projects/p1/secrets/s1", resend_count=2), + { + "rpc.system.name": "grpc", + "gcp.resource.destination.id": "projects/p1/secrets/s1", + "gcp.grpc.resend_count": 2, + }, + ), + ( + types.SimpleNamespace(resend_count=0), + {"rpc.system.name": "grpc"}, + ), + ], +) +def test_extract_t4_attributes(req, expected_attrs): + """Proves that _extract_t4_attributes extracts all T4 gRPC attributes.""" + assert _observability._extract_t4_attributes(req) == expected_attrs def test_client_request_hook(): @@ -286,13 +344,188 @@ def test_client_request_hook(): _observability._client_request_hook(mock_span_non_rec, mock.Mock()) mock_span_non_rec.set_attribute.assert_not_called() - # Recording span should set attributes + # None span should safely return + _observability._client_request_hook(None, mock.Mock()) + + # Recording span with default hook mock_span_rec = mock.Mock() mock_span_rec.is_recording.return_value = True - req = mock.Mock(name="req") - req.name = "projects/my-proj/secrets/s1" + req = types.SimpleNamespace(name="projects/my-proj/secrets/s1", resend_count=1) _observability._client_request_hook(mock_span_rec, req) + mock_span_rec.set_attribute.assert_any_call("rpc.system.name", "grpc") mock_span_rec.set_attribute.assert_any_call( - "gcp.resource.name", "projects/my-proj/secrets/s1" + "gcp.resource.destination.id", "projects/my-proj/secrets/s1" + ) + mock_span_rec.set_attribute.assert_any_call("gcp.grpc.resend_count", 1) + + # Custom hook with endpoint attributes + endpoint_hook = _observability._make_client_request_hook( + {"server.address": "custom.api.com", "server.port": 443} + ) + mock_span_custom = mock.Mock() + mock_span_custom.is_recording.return_value = True + endpoint_hook(mock_span_custom, req) + mock_span_custom.set_attribute.assert_any_call("server.address", "custom.api.com") + mock_span_custom.set_attribute.assert_any_call("server.port", 443) + + +def test_client_response_hook(): + """Proves that _client_response_hook sets rpc.response.status_code, error.type, and status.message.""" + # Non-recording span should not set attributes + mock_span_non_rec = mock.Mock() + mock_span_non_rec.is_recording.return_value = False + _observability._client_response_hook(mock_span_non_rec, mock.Mock()) + mock_span_non_rec.set_attribute.assert_not_called() + + # None span should safely return + _observability._client_response_hook(None, mock.Mock()) + + # Response with no code method defaults to OK + mock_span_ok = mock.Mock() + mock_span_ok.is_recording.return_value = True + _observability._client_response_hook(mock_span_ok, mock.Mock(spec=[])) + mock_span_ok.set_attribute.assert_called_once_with("rpc.response.status_code", "OK") + + # Response with StatusCode object having name (e.g. OK) + mock_span_code_obj = mock.Mock() + mock_span_code_obj.is_recording.return_value = True + mock_resp_ok = mock.Mock() + mock_code_ok = mock.Mock() + mock_code_ok.name = "OK" + mock_resp_ok.code.return_value = mock_code_ok + _observability._client_response_hook(mock_span_code_obj, mock_resp_ok) + mock_span_code_obj.set_attribute.assert_called_once_with( + "rpc.response.status_code", "OK" + ) + + # Response with error status (e.g. integer 14 -> UNAVAILABLE) and details + mock_span_err = mock.Mock() + mock_span_err.is_recording.return_value = True + mock_resp_err = mock.Mock() + mock_resp_err.code.return_value = 14 + mock_resp_err.details.return_value = "Service temporarily unavailable" + _observability._client_response_hook(mock_span_err, mock_resp_err) + mock_span_err.set_attribute.assert_any_call( + "rpc.response.status_code", "UNAVAILABLE" + ) + mock_span_err.set_attribute.assert_any_call("error.type", "UNAVAILABLE") + mock_span_err.set_attribute.assert_any_call( + "status.message", "Service temporarily unavailable" + ) + + # Response where code() raises an exception is handled gracefully + mock_span_exc = mock.Mock() + mock_span_exc.is_recording.return_value = True + mock_resp_exc = mock.Mock() + mock_resp_exc.code.side_effect = RuntimeError("Broken call") + _observability._client_response_hook(mock_span_exc, mock_resp_exc) + mock_span_exc.set_attribute.assert_called_once_with( + "rpc.response.status_code", "OK" + ) + + # Response with error status but no details method + mock_span_no_det = mock.Mock() + mock_span_no_det.is_recording.return_value = True + mock_resp_no_det = mock.Mock(spec=["code"]) + mock_resp_no_det.code.return_value = 14 + _observability._client_response_hook(mock_span_no_det, mock_resp_no_det) + mock_span_no_det.set_attribute.assert_any_call( + "rpc.response.status_code", "UNAVAILABLE" + ) + mock_span_no_det.set_attribute.assert_any_call("error.type", "UNAVAILABLE") + + # Response with error status where details() returns empty/None + mock_span_empty_det = mock.Mock() + mock_span_empty_det.is_recording.return_value = True + mock_resp_empty_det = mock.Mock() + mock_resp_empty_det.code.return_value = 14 + mock_resp_empty_det.details.return_value = "" + _observability._client_response_hook(mock_span_empty_det, mock_resp_empty_det) + mock_span_empty_det.set_attribute.assert_any_call( + "rpc.response.status_code", "UNAVAILABLE" + ) + + # Response with error status where details() raises an exception + mock_span_exc_det = mock.Mock() + mock_span_exc_det.is_recording.return_value = True + mock_resp_exc_det = mock.Mock() + mock_resp_exc_det.code.return_value = 14 + mock_resp_exc_det.details.side_effect = RuntimeError("Details broken") + _observability._client_response_hook(mock_span_exc_det, mock_resp_exc_det) + mock_span_exc_det.set_attribute.assert_any_call( + "rpc.response.status_code", "UNAVAILABLE" + ) + + +def test_extract_endpoint_attributes_empty_clean(): + """Proves that endpoint consisting only of slashes/protocol results in empty attrs.""" + assert ( + _observability._extract_endpoint_attributes( + ClientOptions(api_endpoint="http:///") + ) + == {} + ) + + +def test_get_otel_interceptor_with_api_endpoint(monkeypatch): + """Proves that get_otel_interceptor injects server.address and server.port when api_endpoint is set.""" + monkeypatch.setenv("GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED", "true") + options = ClientOptions(api_endpoint="secretmanager.googleapis.com:443") + + mock_otel = mock.Mock() + mock_otel_grpc = mock_otel.instrumentation.grpc + monkeypatch.setitem(sys.modules, "opentelemetry", mock_otel) + monkeypatch.setitem( + sys.modules, "opentelemetry.instrumentation", mock_otel.instrumentation + ) + monkeypatch.setitem( + sys.modules, "opentelemetry.instrumentation.grpc", mock_otel_grpc + ) + + interceptor = _observability.get_otel_interceptor(client_options=options) + assert callable(interceptor) + + # Verify custom request hook was passed + args, kwargs = mock_otel_grpc.client_interceptor.call_args + req_hook = kwargs["request_hook"] + assert req_hook is not _observability._client_request_hook + + # Test invoking the custom hook + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + req_hook(mock_span, None) + mock_span.set_attribute.assert_any_call( + "server.address", "secretmanager.googleapis.com" + ) + mock_span.set_attribute.assert_any_call("server.port", 443) + + +def test_get_otel_async_interceptor_with_api_endpoint(monkeypatch): + """Proves that get_otel_async_interceptor injects server.address and server.port when api_endpoint is set.""" + monkeypatch.setenv("GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED", "true") + options = ClientOptions(api_endpoint="secretmanager.googleapis.com:8443") + + mock_otel = mock.Mock() + mock_otel_grpc = mock_otel.instrumentation.grpc + monkeypatch.setitem(sys.modules, "opentelemetry", mock_otel) + monkeypatch.setitem( + sys.modules, "opentelemetry.instrumentation", mock_otel.instrumentation + ) + monkeypatch.setitem( + sys.modules, "opentelemetry.instrumentation.grpc", mock_otel_grpc + ) + + result = _observability.get_otel_async_interceptor(client_options=options) + assert result is not None + + args, kwargs = mock_otel_grpc.aio_client_interceptors.call_args + req_hook = kwargs["request_hook"] + assert req_hook is not _observability._client_request_hook + + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + req_hook(mock_span, None) + mock_span.set_attribute.assert_any_call( + "server.address", "secretmanager.googleapis.com" ) - mock_span_rec.set_attribute.assert_any_call("gcp.project_id", "my-proj") + mock_span.set_attribute.assert_any_call("server.port", 8443) From 29de72e9bbc246d60f045ba2d008984500e66ba6 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 9 Sep 2026 09:50:04 -0400 Subject: [PATCH 04/43] refactor(core): adopt explicit _grpc_* naming for request extraction and hooks - Rename _extract_t4_attributes to _extract_grpc_request_attributes - Rename _make_client_request_hook to _make_grpc_client_request_hook - Rename _client_request_hook to _grpc_client_request_hook - Rename _client_response_hook to _grpc_client_response_hook - Preserve generic _extract_endpoint_attributes for shared transport usage --- .../google/api_core/_observability.py | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index b3309bae8a63..a537c2756207 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -112,7 +112,7 @@ def _extract_endpoint_attributes( return attrs -def _extract_t4_attributes(request: Any) -> dict[str, Any]: +def _extract_grpc_request_attributes(request: Any) -> dict[str, Any]: """Extracts Google Cloud T4 semantic and resource attributes from a gRPC request object. Args: @@ -142,15 +142,15 @@ def _extract_t4_attributes(request: Any) -> dict[str, Any]: return attrs -def _make_client_request_hook( +def _make_grpc_client_request_hook( endpoint_attrs: dict[str, Any] | None = None, ) -> Callable[[Any, Any], None]: - """Creates an OpenTelemetry client request hook with optional endpoint attributes.""" + """Creates an OpenTelemetry gRPC client request hook with optional endpoint attributes.""" def client_request_hook(span: Any, request: Any) -> None: if span is None or not getattr(span, "is_recording", lambda: True)(): return - attrs = _extract_t4_attributes(request) + attrs = _extract_grpc_request_attributes(request) if endpoint_attrs: attrs.update(endpoint_attrs) for key, value in attrs.items(): @@ -159,11 +159,11 @@ def client_request_hook(span: Any, request: Any) -> None: return client_request_hook -_client_request_hook = _make_client_request_hook() +_grpc_client_request_hook = _make_grpc_client_request_hook() -def _client_response_hook(span: Any, response: Any) -> None: - """OpenTelemetry client response hook to inject gRPC response status attributes into the span.""" +def _grpc_client_response_hook(span: Any, response: Any) -> None: + """OpenTelemetry gRPC client response hook to inject response status attributes into the span.""" if span is None or not getattr(span, "is_recording", lambda: True)(): return @@ -230,15 +230,15 @@ def get_otel_interceptor( endpoint_attrs = _extract_endpoint_attributes(client_options) request_hook = ( - _make_client_request_hook(endpoint_attrs) + _make_grpc_client_request_hook(endpoint_attrs) if endpoint_attrs - else _client_request_hook + else _grpc_client_request_hook ) interceptor: ClientInterceptor = otel_grpc.client_interceptor( tracer_provider=_get_tracer_provider(client_options), request_hook=request_hook, - response_hook=_client_response_hook, + response_hook=_grpc_client_response_hook, ) def otel_interceptor(channel: grpc.Channel) -> grpc.Channel: @@ -268,13 +268,13 @@ def get_otel_async_interceptor( endpoint_attrs = _extract_endpoint_attributes(client_options) request_hook = ( - _make_client_request_hook(endpoint_attrs) + _make_grpc_client_request_hook(endpoint_attrs) if endpoint_attrs - else _client_request_hook + else _grpc_client_request_hook ) return otel_grpc.aio_client_interceptors( tracer_provider=_get_tracer_provider(client_options), request_hook=request_hook, - response_hook=_client_response_hook, + response_hook=_grpc_client_response_hook, ) From 7f6519f760832efbb3975eb08609471dd205aac0 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 9 Sep 2026 09:50:10 -0400 Subject: [PATCH 05/43] test(core): align test names and assertions with _grpc_* naming convention - Rename test_extract_t4_attributes to test_extract_grpc_request_attributes - Rename test_client_request_hook to test_grpc_client_request_hook - Rename test_client_response_hook to test_grpc_client_response_hook - Update interceptor hook references to _grpc_client_* hooks --- .../tests/unit/test_observability.py | 52 +++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 5bfa72df64cd..82dd5daa76f8 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -164,8 +164,8 @@ def test_get_otel_interceptor_enabled(monkeypatch): mock_otel_grpc.client_interceptor.assert_called_once_with( tracer_provider=mock_tracer_provider, - request_hook=_observability._client_request_hook, - response_hook=_observability._client_response_hook, + request_hook=_observability._grpc_client_request_hook, + response_hook=_observability._grpc_client_response_hook, ) result = interceptor(mock_raw_channel) @@ -255,8 +255,8 @@ def test_get_otel_async_interceptor_enabled(monkeypatch): assert result is mock_async_interceptors mock_otel_grpc.aio_client_interceptors.assert_called_once_with( tracer_provider=mock_tracer_provider, - request_hook=_observability._client_request_hook, - response_hook=_observability._client_response_hook, + request_hook=_observability._grpc_client_request_hook, + response_hook=_observability._grpc_client_response_hook, ) @@ -331,27 +331,27 @@ def test_extract_endpoint_attributes(): ), ], ) -def test_extract_t4_attributes(req, expected_attrs): - """Proves that _extract_t4_attributes extracts all T4 gRPC attributes.""" - assert _observability._extract_t4_attributes(req) == expected_attrs +def test_extract_grpc_request_attributes(req, expected_attrs): + """Proves that _extract_grpc_request_attributes extracts all T4 gRPC attributes.""" + assert _observability._extract_grpc_request_attributes(req) == expected_attrs -def test_client_request_hook(): - """Proves that _client_request_hook attaches extracted T4 attributes to recording spans.""" +def test_grpc_client_request_hook(): + """Proves that _grpc_client_request_hook attaches extracted T4 attributes to recording spans.""" # Non-recording span should not set attributes mock_span_non_rec = mock.Mock() mock_span_non_rec.is_recording.return_value = False - _observability._client_request_hook(mock_span_non_rec, mock.Mock()) + _observability._grpc_client_request_hook(mock_span_non_rec, mock.Mock()) mock_span_non_rec.set_attribute.assert_not_called() # None span should safely return - _observability._client_request_hook(None, mock.Mock()) + _observability._grpc_client_request_hook(None, mock.Mock()) # Recording span with default hook mock_span_rec = mock.Mock() mock_span_rec.is_recording.return_value = True req = types.SimpleNamespace(name="projects/my-proj/secrets/s1", resend_count=1) - _observability._client_request_hook(mock_span_rec, req) + _observability._grpc_client_request_hook(mock_span_rec, req) mock_span_rec.set_attribute.assert_any_call("rpc.system.name", "grpc") mock_span_rec.set_attribute.assert_any_call( "gcp.resource.destination.id", "projects/my-proj/secrets/s1" @@ -359,7 +359,7 @@ def test_client_request_hook(): mock_span_rec.set_attribute.assert_any_call("gcp.grpc.resend_count", 1) # Custom hook with endpoint attributes - endpoint_hook = _observability._make_client_request_hook( + endpoint_hook = _observability._make_grpc_client_request_hook( {"server.address": "custom.api.com", "server.port": 443} ) mock_span_custom = mock.Mock() @@ -369,21 +369,21 @@ def test_client_request_hook(): mock_span_custom.set_attribute.assert_any_call("server.port", 443) -def test_client_response_hook(): - """Proves that _client_response_hook sets rpc.response.status_code, error.type, and status.message.""" +def test_grpc_client_response_hook(): + """Proves that _grpc_client_response_hook sets rpc.response.status_code, error.type, and status.message.""" # Non-recording span should not set attributes mock_span_non_rec = mock.Mock() mock_span_non_rec.is_recording.return_value = False - _observability._client_response_hook(mock_span_non_rec, mock.Mock()) + _observability._grpc_client_response_hook(mock_span_non_rec, mock.Mock()) mock_span_non_rec.set_attribute.assert_not_called() # None span should safely return - _observability._client_response_hook(None, mock.Mock()) + _observability._grpc_client_response_hook(None, mock.Mock()) # Response with no code method defaults to OK mock_span_ok = mock.Mock() mock_span_ok.is_recording.return_value = True - _observability._client_response_hook(mock_span_ok, mock.Mock(spec=[])) + _observability._grpc_client_response_hook(mock_span_ok, mock.Mock(spec=[])) mock_span_ok.set_attribute.assert_called_once_with("rpc.response.status_code", "OK") # Response with StatusCode object having name (e.g. OK) @@ -393,7 +393,7 @@ def test_client_response_hook(): mock_code_ok = mock.Mock() mock_code_ok.name = "OK" mock_resp_ok.code.return_value = mock_code_ok - _observability._client_response_hook(mock_span_code_obj, mock_resp_ok) + _observability._grpc_client_response_hook(mock_span_code_obj, mock_resp_ok) mock_span_code_obj.set_attribute.assert_called_once_with( "rpc.response.status_code", "OK" ) @@ -404,7 +404,7 @@ def test_client_response_hook(): mock_resp_err = mock.Mock() mock_resp_err.code.return_value = 14 mock_resp_err.details.return_value = "Service temporarily unavailable" - _observability._client_response_hook(mock_span_err, mock_resp_err) + _observability._grpc_client_response_hook(mock_span_err, mock_resp_err) mock_span_err.set_attribute.assert_any_call( "rpc.response.status_code", "UNAVAILABLE" ) @@ -418,7 +418,7 @@ def test_client_response_hook(): mock_span_exc.is_recording.return_value = True mock_resp_exc = mock.Mock() mock_resp_exc.code.side_effect = RuntimeError("Broken call") - _observability._client_response_hook(mock_span_exc, mock_resp_exc) + _observability._grpc_client_response_hook(mock_span_exc, mock_resp_exc) mock_span_exc.set_attribute.assert_called_once_with( "rpc.response.status_code", "OK" ) @@ -428,7 +428,7 @@ def test_client_response_hook(): mock_span_no_det.is_recording.return_value = True mock_resp_no_det = mock.Mock(spec=["code"]) mock_resp_no_det.code.return_value = 14 - _observability._client_response_hook(mock_span_no_det, mock_resp_no_det) + _observability._grpc_client_response_hook(mock_span_no_det, mock_resp_no_det) mock_span_no_det.set_attribute.assert_any_call( "rpc.response.status_code", "UNAVAILABLE" ) @@ -440,7 +440,7 @@ def test_client_response_hook(): mock_resp_empty_det = mock.Mock() mock_resp_empty_det.code.return_value = 14 mock_resp_empty_det.details.return_value = "" - _observability._client_response_hook(mock_span_empty_det, mock_resp_empty_det) + _observability._grpc_client_response_hook(mock_span_empty_det, mock_resp_empty_det) mock_span_empty_det.set_attribute.assert_any_call( "rpc.response.status_code", "UNAVAILABLE" ) @@ -451,7 +451,7 @@ def test_client_response_hook(): mock_resp_exc_det = mock.Mock() mock_resp_exc_det.code.return_value = 14 mock_resp_exc_det.details.side_effect = RuntimeError("Details broken") - _observability._client_response_hook(mock_span_exc_det, mock_resp_exc_det) + _observability._grpc_client_response_hook(mock_span_exc_det, mock_resp_exc_det) mock_span_exc_det.set_attribute.assert_any_call( "rpc.response.status_code", "UNAVAILABLE" ) @@ -488,7 +488,7 @@ def test_get_otel_interceptor_with_api_endpoint(monkeypatch): # Verify custom request hook was passed args, kwargs = mock_otel_grpc.client_interceptor.call_args req_hook = kwargs["request_hook"] - assert req_hook is not _observability._client_request_hook + assert req_hook is not _observability._grpc_client_request_hook # Test invoking the custom hook mock_span = mock.Mock() @@ -520,7 +520,7 @@ def test_get_otel_async_interceptor_with_api_endpoint(monkeypatch): args, kwargs = mock_otel_grpc.aio_client_interceptors.call_args req_hook = kwargs["request_hook"] - assert req_hook is not _observability._client_request_hook + assert req_hook is not _observability._grpc_client_request_hook mock_span = mock.Mock() mock_span.is_recording.return_value = True From b0de0a4ad72da5c02e6d5c5df0efe948442bb3b6 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 9 Sep 2026 20:24:40 -0400 Subject: [PATCH 06/43] feat(core): add url.domain, error attributes, and streamline T4 hooks - Add url.domain extraction from universe_domain or default to googleapis.com - Add _extract_error_attributes helper to extract gcp.errors.domain and gcp.errors.metadata. - Omit server.port when port matches scheme defaults (443 for https/grpc, 80 for http) - Remove redundant _grpc_client_response_hook and _STATUS_CODE_NAMES - Deduplicate name and parent resource lookup for gcp.resource.destination.id - Add comprehensive parametrized unit tests and update interceptor test suites --- .../google/api_core/_observability.py | 165 ++++++----- .../tests/unit/test_observability.py | 269 ++++++++++-------- 2 files changed, 229 insertions(+), 205 deletions(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index a537c2756207..33838cf19f01 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -18,6 +18,7 @@ from __future__ import annotations +import urllib.parse from typing import TYPE_CHECKING, Any, Callable, Sequence from google.api_core import _feature_gating_helpers @@ -64,51 +65,43 @@ def is_otel_capabilities_enabled( return False -_STATUS_CODE_NAMES = { - 0: "OK", - 1: "CANCELLED", - 2: "UNKNOWN", - 3: "INVALID_ARGUMENT", - 4: "DEADLINE_EXCEEDED", - 5: "NOT_FOUND", - 6: "ALREADY_EXISTS", - 7: "PERMISSION_DENIED", - 8: "RESOURCE_EXHAUSTED", - 9: "FAILED_PRECONDITION", - 10: "ABORTED", - 11: "OUT_OF_RANGE", - 12: "UNIMPLEMENTED", - 13: "INTERNAL", - 14: "UNAVAILABLE", - 15: "DATA_LOSS", - 16: "UNAUTHENTICATED", -} - - def _extract_endpoint_attributes( client_options: ClientOptions | dict[str, Any] | None = None, ) -> dict[str, Any]: - """Extracts server.address and server.port from client options if present.""" + """Extracts server.address, server.port (if non-default), and url.domain from client options if present. + + Args: + client_options: The client options object or dictionary. + + Returns: + dict[str, Any]: A dictionary containing url.domain and, if an api_endpoint is configured, + server.address and non-default server.port. + """ attrs: dict[str, Any] = {} endpoint = None + universe_domain = None + if isinstance(client_options, dict): endpoint = client_options.get("api_endpoint") + universe_domain = client_options.get("universe_domain") elif client_options is not None: endpoint = getattr(client_options, "api_endpoint", None) + universe_domain = getattr(client_options, "universe_domain", None) + + attrs["url.domain"] = universe_domain or "googleapis.com" if endpoint and isinstance(endpoint, str): - clean = endpoint.replace("http://", "").replace("https://", "").strip("/") - if clean: - if ":" in clean: - host, port_str = clean.split(":", 1) - attrs["server.address"] = host - try: - attrs["server.port"] = int(port_str) - except ValueError: - attrs["server.port"] = 443 - else: - attrs["server.address"] = clean - attrs["server.port"] = 443 + target = endpoint if "//" in endpoint else f"//{endpoint}" + parsed = urllib.parse.urlsplit(target) + if parsed.hostname: + attrs["server.address"] = parsed.hostname + if parsed.port: + scheme = parsed.scheme.lower() + is_default_port = (parsed.port == 443 and scheme in ("https", "")) or ( + parsed.port == 80 and scheme == "http" + ) + if not is_default_port: + attrs["server.port"] = parsed.port return attrs @@ -131,13 +124,46 @@ def _extract_grpc_request_attributes(request: Any) -> dict[str, Any]: if isinstance(resend_count, int) and resend_count > 0: attrs["gcp.grpc.resend_count"] = resend_count - name = getattr(request, "name", None) - if isinstance(name, str) and name: - attrs["gcp.resource.destination.id"] = name - else: - parent = getattr(request, "parent", None) - if isinstance(parent, str) and parent: - attrs["gcp.resource.destination.id"] = parent + resource_id = getattr(request, "name", None) or getattr(request, "parent", None) + if isinstance(resource_id, str) and resource_id: + attrs["gcp.resource.destination.id"] = resource_id + + return attrs + + +def _extract_error_attributes(exc: Any) -> dict[str, Any]: + """Extracts gcp.errors.domain, gcp.errors.metadata.*, and error.type from an exception or ErrorInfo. + + Args: + exc: An exception (such as GoogleAPICallError or grpc.RpcError) or ErrorInfo object. + + Returns: + dict[str, Any]: Extracted error attributes. + """ + attrs: dict[str, Any] = {} + if exc is None: + return attrs + + error_info = getattr(exc, "error_info", None) + if error_info is None and hasattr(exc, "trailing_metadata"): + try: + from google.api_core import exceptions + + _, error_info = exceptions._parse_grpc_error_details(exc) + except Exception: + pass + + if error_info is not None: + domain = getattr(error_info, "domain", None) + if domain and isinstance(domain, str): + attrs["gcp.errors.domain"] = domain + reason = getattr(error_info, "reason", None) + if reason and isinstance(reason, str): + attrs["error.type"] = reason + metadata = getattr(error_info, "metadata", None) + if metadata and hasattr(metadata, "items"): + for k, v in metadata.items(): + attrs[f"gcp.errors.metadata.{k}"] = str(v) return attrs @@ -145,14 +171,22 @@ def _extract_grpc_request_attributes(request: Any) -> dict[str, Any]: def _make_grpc_client_request_hook( endpoint_attrs: dict[str, Any] | None = None, ) -> Callable[[Any, Any], None]: - """Creates an OpenTelemetry gRPC client request hook with optional endpoint attributes.""" + """Creates an OpenTelemetry gRPC client request hook with optional endpoint attributes. + + Args: + endpoint_attrs: Optional static endpoint attributes to attach to every span. + + Returns: + Callable[[Any, Any], None]: The request hook callback. + """ + static_attrs = dict(endpoint_attrs) if endpoint_attrs else {} def client_request_hook(span: Any, request: Any) -> None: if span is None or not getattr(span, "is_recording", lambda: True)(): return attrs = _extract_grpc_request_attributes(request) - if endpoint_attrs: - attrs.update(endpoint_attrs) + if static_attrs: + attrs.update(static_attrs) for key, value in attrs.items(): span.set_attribute(key, value) @@ -162,35 +196,6 @@ def client_request_hook(span: Any, request: Any) -> None: _grpc_client_request_hook = _make_grpc_client_request_hook() -def _grpc_client_response_hook(span: Any, response: Any) -> None: - """OpenTelemetry gRPC client response hook to inject response status attributes into the span.""" - if span is None or not getattr(span, "is_recording", lambda: True)(): - return - - status_str = "OK" - code_fn = getattr(response, "code", None) - if callable(code_fn): - try: - code_val = code_fn() - status_str = getattr(code_val, "name", None) or _STATUS_CODE_NAMES.get( - code_val, str(code_val) - ) - except Exception: - pass - - span.set_attribute("rpc.response.status_code", status_str) - if status_str != "OK": - span.set_attribute("error.type", status_str) - details_fn = getattr(response, "details", None) - if callable(details_fn): - try: - details = details_fn() - if details: - span.set_attribute("status.message", str(details)) - except Exception: - pass - - def _get_tracer_provider( client_options: ClientOptions | dict[str, Any] | None = None, ) -> opentelemetry.trace.TracerProvider | None: @@ -229,16 +234,11 @@ def get_otel_interceptor( import opentelemetry.instrumentation.grpc as otel_grpc # type: ignore[import-not-found] endpoint_attrs = _extract_endpoint_attributes(client_options) - request_hook = ( - _make_grpc_client_request_hook(endpoint_attrs) - if endpoint_attrs - else _grpc_client_request_hook - ) + request_hook = _make_grpc_client_request_hook(endpoint_attrs) interceptor: ClientInterceptor = otel_grpc.client_interceptor( tracer_provider=_get_tracer_provider(client_options), request_hook=request_hook, - response_hook=_grpc_client_response_hook, ) def otel_interceptor(channel: grpc.Channel) -> grpc.Channel: @@ -267,14 +267,9 @@ def get_otel_async_interceptor( import opentelemetry.instrumentation.grpc as otel_grpc # type: ignore[import-not-found] endpoint_attrs = _extract_endpoint_attributes(client_options) - request_hook = ( - _make_grpc_client_request_hook(endpoint_attrs) - if endpoint_attrs - else _grpc_client_request_hook - ) + request_hook = _make_grpc_client_request_hook(endpoint_attrs) return otel_grpc.aio_client_interceptors( tracer_provider=_get_tracer_provider(client_options), request_hook=request_hook, - response_hook=_grpc_client_response_hook, ) diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 82dd5daa76f8..4ae31e9c163e 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -164,9 +164,13 @@ def test_get_otel_interceptor_enabled(monkeypatch): mock_otel_grpc.client_interceptor.assert_called_once_with( tracer_provider=mock_tracer_provider, - request_hook=_observability._grpc_client_request_hook, - response_hook=_observability._grpc_client_response_hook, + request_hook=mock.ANY, ) + req_hook = mock_otel_grpc.client_interceptor.call_args[1]["request_hook"] + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + req_hook(mock_span, None) + mock_span.set_attribute.assert_any_call("url.domain", "googleapis.com") result = interceptor(mock_raw_channel) assert result is mock_wrapped_channel @@ -255,38 +259,76 @@ def test_get_otel_async_interceptor_enabled(monkeypatch): assert result is mock_async_interceptors mock_otel_grpc.aio_client_interceptors.assert_called_once_with( tracer_provider=mock_tracer_provider, - request_hook=_observability._grpc_client_request_hook, - response_hook=_observability._grpc_client_response_hook, - ) - - -def test_extract_endpoint_attributes(): - """Proves that _extract_endpoint_attributes correctly parses server.address and server.port.""" - # None or empty options - assert _observability._extract_endpoint_attributes(None) == {} - assert _observability._extract_endpoint_attributes({}) == {} - assert ( - _observability._extract_endpoint_attributes(ClientOptions(api_endpoint=None)) - == {} + request_hook=mock.ANY, ) + req_hook = mock_otel_grpc.aio_client_interceptors.call_args[1]["request_hook"] + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + req_hook(mock_span, None) + mock_span.set_attribute.assert_any_call("url.domain", "googleapis.com") - # Dict options with standard endpoint - dict_opts = {"api_endpoint": "secretmanager.googleapis.com"} - attrs = _observability._extract_endpoint_attributes(dict_opts) - assert attrs["server.address"] == "secretmanager.googleapis.com" - assert attrs["server.port"] == 443 - - # ClientOptions with custom port - custom_opts = ClientOptions(api_endpoint="https://my-custom-host.com:8443/") - attrs = _observability._extract_endpoint_attributes(custom_opts) - assert attrs["server.address"] == "my-custom-host.com" - assert attrs["server.port"] == 8443 - # Invalid port string falls back to 443 - invalid_port_opts = ClientOptions(api_endpoint="my-custom-host.com:invalid_port") - attrs = _observability._extract_endpoint_attributes(invalid_port_opts) - assert attrs["server.address"] == "my-custom-host.com" - assert attrs["server.port"] == 443 +@pytest.mark.parametrize( + "client_options,expected_attrs", + [ + (None, {"url.domain": "googleapis.com"}), + ({}, {"url.domain": "googleapis.com"}), + (ClientOptions(api_endpoint=None), {"url.domain": "googleapis.com"}), + ({"universe_domain": "myuniverse.com"}, {"url.domain": "myuniverse.com"}), + ( + ClientOptions(universe_domain="custom.domain"), + {"url.domain": "custom.domain"}, + ), + ( + {"api_endpoint": "secretmanager.googleapis.com"}, + { + "server.address": "secretmanager.googleapis.com", + "url.domain": "googleapis.com", + }, + ), + ( + {"api_endpoint": "secretmanager.googleapis.com:443"}, + { + "server.address": "secretmanager.googleapis.com", + "url.domain": "googleapis.com", + }, + ), + ( + {"api_endpoint": "https://secretmanager.googleapis.com:443"}, + { + "server.address": "secretmanager.googleapis.com", + "url.domain": "googleapis.com", + }, + ), + ( + {"api_endpoint": "http://localhost:80"}, + {"server.address": "localhost", "url.domain": "googleapis.com"}, + ), + ( + ClientOptions(api_endpoint="https://my-custom-host.com:8443/"), + { + "server.address": "my-custom-host.com", + "server.port": 8443, + "url.domain": "googleapis.com", + }, + ), + ( + ClientOptions(api_endpoint="http://[::1]:8080"), + { + "server.address": "::1", + "server.port": 8080, + "url.domain": "googleapis.com", + }, + ), + ( + ClientOptions(api_endpoint="http:///"), + {"url.domain": "googleapis.com"}, + ), + ], +) +def test_extract_endpoint_attributes(client_options, expected_attrs): + """Proves that _extract_endpoint_attributes correctly parses server.address, non-default server.port, and url.domain.""" + assert _observability._extract_endpoint_attributes(client_options) == expected_attrs @pytest.mark.parametrize( @@ -369,108 +411,90 @@ def test_grpc_client_request_hook(): mock_span_custom.set_attribute.assert_any_call("server.port", 443) -def test_grpc_client_response_hook(): - """Proves that _grpc_client_response_hook sets rpc.response.status_code, error.type, and status.message.""" - # Non-recording span should not set attributes - mock_span_non_rec = mock.Mock() - mock_span_non_rec.is_recording.return_value = False - _observability._grpc_client_response_hook(mock_span_non_rec, mock.Mock()) - mock_span_non_rec.set_attribute.assert_not_called() +def test_extract_error_attributes_none(): + """Proves that _extract_error_attributes returns an empty dict when exception is None.""" + assert _observability._extract_error_attributes(None) == {} - # None span should safely return - _observability._grpc_client_response_hook(None, mock.Mock()) - - # Response with no code method defaults to OK - mock_span_ok = mock.Mock() - mock_span_ok.is_recording.return_value = True - _observability._grpc_client_response_hook(mock_span_ok, mock.Mock(spec=[])) - mock_span_ok.set_attribute.assert_called_once_with("rpc.response.status_code", "OK") - - # Response with StatusCode object having name (e.g. OK) - mock_span_code_obj = mock.Mock() - mock_span_code_obj.is_recording.return_value = True - mock_resp_ok = mock.Mock() - mock_code_ok = mock.Mock() - mock_code_ok.name = "OK" - mock_resp_ok.code.return_value = mock_code_ok - _observability._grpc_client_response_hook(mock_span_code_obj, mock_resp_ok) - mock_span_code_obj.set_attribute.assert_called_once_with( - "rpc.response.status_code", "OK" - ) - # Response with error status (e.g. integer 14 -> UNAVAILABLE) and details - mock_span_err = mock.Mock() - mock_span_err.is_recording.return_value = True - mock_resp_err = mock.Mock() - mock_resp_err.code.return_value = 14 - mock_resp_err.details.return_value = "Service temporarily unavailable" - _observability._grpc_client_response_hook(mock_span_err, mock_resp_err) - mock_span_err.set_attribute.assert_any_call( - "rpc.response.status_code", "UNAVAILABLE" - ) - mock_span_err.set_attribute.assert_any_call("error.type", "UNAVAILABLE") - mock_span_err.set_attribute.assert_any_call( - "status.message", "Service temporarily unavailable" +def test_extract_error_attributes_standard_exception(): + """Proves that _extract_error_attributes returns an empty dict for standard exceptions without ErrorInfo.""" + assert ( + _observability._extract_error_attributes(ValueError("unexpected error")) == {} ) - # Response where code() raises an exception is handled gracefully - mock_span_exc = mock.Mock() - mock_span_exc.is_recording.return_value = True - mock_resp_exc = mock.Mock() - mock_resp_exc.code.side_effect = RuntimeError("Broken call") - _observability._grpc_client_response_hook(mock_span_exc, mock_resp_exc) - mock_span_exc.set_attribute.assert_called_once_with( - "rpc.response.status_code", "OK" - ) - # Response with error status but no details method - mock_span_no_det = mock.Mock() - mock_span_no_det.is_recording.return_value = True - mock_resp_no_det = mock.Mock(spec=["code"]) - mock_resp_no_det.code.return_value = 14 - _observability._grpc_client_response_hook(mock_span_no_det, mock_resp_no_det) - mock_span_no_det.set_attribute.assert_any_call( - "rpc.response.status_code", "UNAVAILABLE" +def test_extract_error_attributes_with_error_info(): + """Proves that _extract_error_attributes extracts domain, error.type, and metadata from ErrorInfo.""" + error_info = types.SimpleNamespace( + domain="googleapis.com", + reason="SERVICE_DISABLED", + metadata={ + "service": "secretmanager.googleapis.com", + "consumer": "projects/123", + }, ) - mock_span_no_det.set_attribute.assert_any_call("error.type", "UNAVAILABLE") - - # Response with error status where details() returns empty/None - mock_span_empty_det = mock.Mock() - mock_span_empty_det.is_recording.return_value = True - mock_resp_empty_det = mock.Mock() - mock_resp_empty_det.code.return_value = 14 - mock_resp_empty_det.details.return_value = "" - _observability._grpc_client_response_hook(mock_span_empty_det, mock_resp_empty_det) - mock_span_empty_det.set_attribute.assert_any_call( - "rpc.response.status_code", "UNAVAILABLE" + exc = types.SimpleNamespace(error_info=error_info) + attrs = _observability._extract_error_attributes(exc) + assert attrs == { + "gcp.errors.domain": "googleapis.com", + "error.type": "SERVICE_DISABLED", + "gcp.errors.metadata.service": "secretmanager.googleapis.com", + "gcp.errors.metadata.consumer": "projects/123", + } + + +def test_extract_error_attributes_from_grpc_trailing_metadata(monkeypatch): + """Proves that _extract_error_attributes parses error_info from gRPC trailing metadata.""" + from google.api_core import exceptions + + mock_exc = mock.Mock() + mock_exc.error_info = None + mock_exc.trailing_metadata = mock.Mock() + + parsed_error_info = types.SimpleNamespace( + domain="googleapis.com", + reason="RESOURCE_EXHAUSTED", + metadata={"quota_limit": "100"}, ) - # Response with error status where details() raises an exception - mock_span_exc_det = mock.Mock() - mock_span_exc_det.is_recording.return_value = True - mock_resp_exc_det = mock.Mock() - mock_resp_exc_det.code.return_value = 14 - mock_resp_exc_det.details.side_effect = RuntimeError("Details broken") - _observability._grpc_client_response_hook(mock_span_exc_det, mock_resp_exc_det) - mock_span_exc_det.set_attribute.assert_any_call( - "rpc.response.status_code", "UNAVAILABLE" + monkeypatch.setattr( + exceptions, + "_parse_grpc_error_details", + mock.Mock(return_value=(None, parsed_error_info)), ) + attrs = _observability._extract_error_attributes(mock_exc) + assert attrs == { + "gcp.errors.domain": "googleapis.com", + "error.type": "RESOURCE_EXHAUSTED", + "gcp.errors.metadata.quota_limit": "100", + } -def test_extract_endpoint_attributes_empty_clean(): - """Proves that endpoint consisting only of slashes/protocol results in empty attrs.""" - assert ( - _observability._extract_endpoint_attributes( - ClientOptions(api_endpoint="http:///") - ) - == {} + +def test_extract_error_attributes_trailing_metadata_failure(monkeypatch): + """Proves that _extract_error_attributes safely handles exceptions during trailing metadata parsing.""" + from google.api_core import exceptions + + mock_exc = mock.Mock() + mock_exc.error_info = None + mock_exc.trailing_metadata = mock.Mock() + + monkeypatch.setattr( + exceptions, + "_parse_grpc_error_details", + mock.Mock(side_effect=RuntimeError("Parse failed")), ) + assert _observability._extract_error_attributes(mock_exc) == {} + def test_get_otel_interceptor_with_api_endpoint(monkeypatch): - """Proves that get_otel_interceptor injects server.address and server.port when api_endpoint is set.""" + """Proves that get_otel_interceptor injects server.address, server.port, and url.domain when api_endpoint is set.""" monkeypatch.setenv("GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED", "true") - options = ClientOptions(api_endpoint="secretmanager.googleapis.com:443") + options = ClientOptions( + api_endpoint="secretmanager.googleapis.com:8443", + universe_domain="custom-domain.com", + ) mock_otel = mock.Mock() mock_otel_grpc = mock_otel.instrumentation.grpc @@ -497,13 +521,17 @@ def test_get_otel_interceptor_with_api_endpoint(monkeypatch): mock_span.set_attribute.assert_any_call( "server.address", "secretmanager.googleapis.com" ) - mock_span.set_attribute.assert_any_call("server.port", 443) + mock_span.set_attribute.assert_any_call("server.port", 8443) + mock_span.set_attribute.assert_any_call("url.domain", "custom-domain.com") def test_get_otel_async_interceptor_with_api_endpoint(monkeypatch): - """Proves that get_otel_async_interceptor injects server.address and server.port when api_endpoint is set.""" + """Proves that get_otel_async_interceptor injects server.address, server.port, and url.domain when api_endpoint is set.""" monkeypatch.setenv("GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED", "true") - options = ClientOptions(api_endpoint="secretmanager.googleapis.com:8443") + options = ClientOptions( + api_endpoint="secretmanager.googleapis.com:8443", + universe_domain="custom-domain.com", + ) mock_otel = mock.Mock() mock_otel_grpc = mock_otel.instrumentation.grpc @@ -529,3 +557,4 @@ def test_get_otel_async_interceptor_with_api_endpoint(monkeypatch): "server.address", "secretmanager.googleapis.com" ) mock_span.set_attribute.assert_any_call("server.port", 8443) + mock_span.set_attribute.assert_any_call("url.domain", "custom-domain.com") From ac095c5103c0dd8da262b7a351fed50cfcee80b7 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Thu, 10 Sep 2026 05:42:47 -0400 Subject: [PATCH 07/43] feat(core): normalize gRPC span names and eliminate duplicate rpc.system attribute - Strip leading slash from gRPC attempt span names via span.update_name - Set rpc.method to the fully qualified method name per PRD specification - Retain rpc.system.name: 'grpc' and remove legacy rpc.system attribute to avoid duplication - Update unit tests to verify span name normalization and attribute deduplication --- .../google/api_core/_observability.py | 19 +++++++++++++ .../tests/unit/test_observability.py | 27 ++++++++++++++++--- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index 33838cf19f01..5e8f574ba06f 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -184,7 +184,26 @@ def _make_grpc_client_request_hook( def client_request_hook(span: Any, request: Any) -> None: if span is None or not getattr(span, "is_recording", lambda: True)(): return + + # Upstream opentelemetry-instrumentation-grpc names spans with a leading slash + # (e.g. "/package.Service/Method") and sets only the short name on rpc.method. + # Normalize span.name and rpc.method to the fully-qualified name without leading slash. + span_name = getattr(span, "name", None) + clean_method_name = None + if isinstance(span_name, str) and span_name.startswith("/"): + clean_method_name = span_name.lstrip("/") + if hasattr(span, "update_name"): + span.update_name(clean_method_name) + + # Remove duplicate legacy rpc.system attribute set by stock instrumentation + # in favor of modern rpc.system.name ("grpc") per PRD changelog. + span_attributes = getattr(span, "_attributes", None) + if hasattr(span_attributes, "pop"): + span_attributes.pop("rpc.system", None) + attrs = _extract_grpc_request_attributes(request) + if clean_method_name: + attrs["rpc.method"] = clean_method_name if static_attrs: attrs.update(static_attrs) for key, value in attrs.items(): diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 4ae31e9c163e..982797aed4ef 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -379,7 +379,9 @@ def test_extract_grpc_request_attributes(req, expected_attrs): def test_grpc_client_request_hook(): - """Proves that _grpc_client_request_hook attaches extracted T4 attributes to recording spans.""" + """Proves that _grpc_client_request_hook attaches extracted T4 attributes to recording spans, + normalizes span names, sets fully qualified rpc.method, and removes legacy rpc.system. + """ # Non-recording span should not set attributes mock_span_non_rec = mock.Mock() mock_span_non_rec.is_recording.return_value = False @@ -389,26 +391,45 @@ def test_grpc_client_request_hook(): # None span should safely return _observability._grpc_client_request_hook(None, mock.Mock()) - # Recording span with default hook + # Recording span with default hook, leading slash in span.name, and legacy rpc.system mock_span_rec = mock.Mock() mock_span_rec.is_recording.return_value = True + mock_span_rec.name = ( + "/google.cloud.secretmanager.v1.SecretManagerService/ListSecrets" + ) + mock_span_rec._attributes = {"rpc.system": "grpc"} req = types.SimpleNamespace(name="projects/my-proj/secrets/s1", resend_count=1) + _observability._grpc_client_request_hook(mock_span_rec, req) + + # Verify span name normalized and rpc.method set to fully qualified name + mock_span_rec.update_name.assert_called_once_with( + "google.cloud.secretmanager.v1.SecretManagerService/ListSecrets" + ) + mock_span_rec.set_attribute.assert_any_call( + "rpc.method", "google.cloud.secretmanager.v1.SecretManagerService/ListSecrets" + ) + + # Verify rpc.system.name set and legacy rpc.system popped mock_span_rec.set_attribute.assert_any_call("rpc.system.name", "grpc") + assert "rpc.system" not in mock_span_rec._attributes + mock_span_rec.set_attribute.assert_any_call( "gcp.resource.destination.id", "projects/my-proj/secrets/s1" ) mock_span_rec.set_attribute.assert_any_call("gcp.grpc.resend_count", 1) - # Custom hook with endpoint attributes + # Custom hook with endpoint attributes and already-clean span name endpoint_hook = _observability._make_grpc_client_request_hook( {"server.address": "custom.api.com", "server.port": 443} ) mock_span_custom = mock.Mock() mock_span_custom.is_recording.return_value = True + mock_span_custom.name = "already_clean_name" endpoint_hook(mock_span_custom, req) mock_span_custom.set_attribute.assert_any_call("server.address", "custom.api.com") mock_span_custom.set_attribute.assert_any_call("server.port", 443) + mock_span_custom.update_name.assert_not_called() def test_extract_error_attributes_none(): From ef7d77d03313d1c159bdb41cde3abf0744708ba9 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Thu, 10 Sep 2026 05:49:18 -0400 Subject: [PATCH 08/43] refactor(core): remove deferred gcp.resource.destination.id attribute - Remove gcp.resource.destination.id extraction from _extract_grpc_request_attributes - Update unit tests to reflect attribute removal per July Strategy Update --- .../google/api_core/_observability.py | 4 ---- .../tests/unit/test_observability.py | 23 ++----------------- 2 files changed, 2 insertions(+), 25 deletions(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index 5e8f574ba06f..b8daf298111e 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -124,10 +124,6 @@ def _extract_grpc_request_attributes(request: Any) -> dict[str, Any]: if isinstance(resend_count, int) and resend_count > 0: attrs["gcp.grpc.resend_count"] = resend_count - resource_id = getattr(request, "name", None) or getattr(request, "parent", None) - if isinstance(resource_id, str) and resource_id: - attrs["gcp.resource.destination.id"] = resource_id - return attrs diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 982797aed4ef..7adc333fa8e5 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -338,32 +338,16 @@ def test_extract_endpoint_attributes(client_options, expected_attrs): (types.SimpleNamespace(), {"rpc.system.name": "grpc"}), ( types.SimpleNamespace(name="projects/p1/secrets/s1"), - { - "rpc.system.name": "grpc", - "gcp.resource.destination.id": "projects/p1/secrets/s1", - }, + {"rpc.system.name": "grpc"}, ), ( types.SimpleNamespace(parent="projects/parent-p1"), - { - "rpc.system.name": "grpc", - "gcp.resource.destination.id": "projects/parent-p1", - }, - ), - ( - types.SimpleNamespace( - name="projects/p1/secrets/s1", parent="projects/parent-p1" - ), - { - "rpc.system.name": "grpc", - "gcp.resource.destination.id": "projects/p1/secrets/s1", - }, + {"rpc.system.name": "grpc"}, ), ( types.SimpleNamespace(name="projects/p1/secrets/s1", resend_count=2), { "rpc.system.name": "grpc", - "gcp.resource.destination.id": "projects/p1/secrets/s1", "gcp.grpc.resend_count": 2, }, ), @@ -414,9 +398,6 @@ def test_grpc_client_request_hook(): mock_span_rec.set_attribute.assert_any_call("rpc.system.name", "grpc") assert "rpc.system" not in mock_span_rec._attributes - mock_span_rec.set_attribute.assert_any_call( - "gcp.resource.destination.id", "projects/my-proj/secrets/s1" - ) mock_span_rec.set_attribute.assert_any_call("gcp.grpc.resend_count", 1) # Custom hook with endpoint attributes and already-clean span name From aa2beadada6701847a1e5e30615d2116bb0262dd Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Thu, 10 Sep 2026 06:33:05 -0400 Subject: [PATCH 09/43] feat(core): record rpc.response.status_code on wire attempt spans --- .../google/api_core/_observability.py | 39 +++++++++++++++++++ .../tests/unit/test_observability.py | 32 +++++++++++++++ 2 files changed, 71 insertions(+) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index b8daf298111e..98ca898c4e7b 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -211,6 +211,43 @@ def client_request_hook(span: Any, request: Any) -> None: _grpc_client_request_hook = _make_grpc_client_request_hook() +def _grpc_client_response_hook(span: Any, response: Any) -> None: + """OpenTelemetry gRPC client response hook to record response status code. + + Args: + span: The OpenTelemetry span. + response: The gRPC response object or details. + """ + if span is None or not hasattr(span, "set_attribute"): + return + + status = getattr(span, "status", None) + status_code = getattr(status, "status_code", None) + try: + from opentelemetry.trace.status import StatusCode + + if status_code == StatusCode.ERROR: + span_attrs = ( + getattr(span, "attributes", None) + or getattr(span, "_attributes", None) + or {} + ) + grpc_code = span_attrs.get("rpc.grpc.status_code") + if grpc_code is not None: + from google.api_core import exceptions + + if grpc_code in exceptions._INT_TO_GRPC_CODE: + span.set_attribute( + "rpc.response.status_code", + exceptions._INT_TO_GRPC_CODE[grpc_code].name, + ) + return + except Exception: + pass + + span.set_attribute("rpc.response.status_code", "OK") + + def _get_tracer_provider( client_options: ClientOptions | dict[str, Any] | None = None, ) -> opentelemetry.trace.TracerProvider | None: @@ -254,6 +291,7 @@ def get_otel_interceptor( interceptor: ClientInterceptor = otel_grpc.client_interceptor( tracer_provider=_get_tracer_provider(client_options), request_hook=request_hook, + response_hook=_grpc_client_response_hook, ) def otel_interceptor(channel: grpc.Channel) -> grpc.Channel: @@ -287,4 +325,5 @@ def get_otel_async_interceptor( return otel_grpc.aio_client_interceptors( tracer_provider=_get_tracer_provider(client_options), request_hook=request_hook, + response_hook=_grpc_client_response_hook, ) diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 7adc333fa8e5..e25139ce0a39 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -165,6 +165,7 @@ def test_get_otel_interceptor_enabled(monkeypatch): mock_otel_grpc.client_interceptor.assert_called_once_with( tracer_provider=mock_tracer_provider, request_hook=mock.ANY, + response_hook=_observability._grpc_client_response_hook, ) req_hook = mock_otel_grpc.client_interceptor.call_args[1]["request_hook"] mock_span = mock.Mock() @@ -260,7 +261,9 @@ def test_get_otel_async_interceptor_enabled(monkeypatch): mock_otel_grpc.aio_client_interceptors.assert_called_once_with( tracer_provider=mock_tracer_provider, request_hook=mock.ANY, + response_hook=_observability._grpc_client_response_hook, ) + req_hook = mock_otel_grpc.aio_client_interceptors.call_args[1]["request_hook"] mock_span = mock.Mock() mock_span.is_recording.return_value = True @@ -515,6 +518,7 @@ def test_get_otel_interceptor_with_api_endpoint(monkeypatch): args, kwargs = mock_otel_grpc.client_interceptor.call_args req_hook = kwargs["request_hook"] assert req_hook is not _observability._grpc_client_request_hook + assert kwargs["response_hook"] is _observability._grpc_client_response_hook # Test invoking the custom hook mock_span = mock.Mock() @@ -551,6 +555,7 @@ def test_get_otel_async_interceptor_with_api_endpoint(monkeypatch): args, kwargs = mock_otel_grpc.aio_client_interceptors.call_args req_hook = kwargs["request_hook"] assert req_hook is not _observability._grpc_client_request_hook + assert kwargs["response_hook"] is _observability._grpc_client_response_hook mock_span = mock.Mock() mock_span.is_recording.return_value = True @@ -560,3 +565,30 @@ def test_get_otel_async_interceptor_with_api_endpoint(monkeypatch): ) mock_span.set_attribute.assert_any_call("server.port", 8443) mock_span.set_attribute.assert_any_call("url.domain", "custom-domain.com") + + +def test_grpc_client_response_hook_success(): + """Proves that _grpc_client_response_hook sets rpc.response.status_code to 'OK' on success.""" + mock_span = mock.Mock() + _observability._grpc_client_response_hook(mock_span, mock.Mock()) + mock_span.set_attribute.assert_called_once_with("rpc.response.status_code", "OK") + + +def test_grpc_client_response_hook_error_mapped(): + """Proves that _grpc_client_response_hook maps status code when span has error status.""" + from opentelemetry.trace.status import StatusCode + + mock_span = mock.Mock() + mock_span.status.status_code = StatusCode.ERROR + mock_span.attributes = {"rpc.grpc.status_code": 5} + + _observability._grpc_client_response_hook(mock_span, None) + mock_span.set_attribute.assert_called_once_with( + "rpc.response.status_code", "NOT_FOUND" + ) + + +def test_grpc_client_response_hook_none_or_missing_set_attribute(): + """Proves that _grpc_client_response_hook handles None or invalid span gracefully.""" + _observability._grpc_client_response_hook(None, mock.Mock()) + _observability._grpc_client_response_hook(object(), mock.Mock()) From 894b3808548c2c7314eaf40e0bf7d2db30d78b0b Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Thu, 10 Sep 2026 07:48:11 -0400 Subject: [PATCH 10/43] refactor(core): remove duplicate error attribute extraction in favor of method spans --- .../google/api_core/_observability.py | 37 --------- .../tests/unit/test_observability.py | 77 ------------------- 2 files changed, 114 deletions(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index 98ca898c4e7b..4ad2b60b6e1e 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -127,43 +127,6 @@ def _extract_grpc_request_attributes(request: Any) -> dict[str, Any]: return attrs -def _extract_error_attributes(exc: Any) -> dict[str, Any]: - """Extracts gcp.errors.domain, gcp.errors.metadata.*, and error.type from an exception or ErrorInfo. - - Args: - exc: An exception (such as GoogleAPICallError or grpc.RpcError) or ErrorInfo object. - - Returns: - dict[str, Any]: Extracted error attributes. - """ - attrs: dict[str, Any] = {} - if exc is None: - return attrs - - error_info = getattr(exc, "error_info", None) - if error_info is None and hasattr(exc, "trailing_metadata"): - try: - from google.api_core import exceptions - - _, error_info = exceptions._parse_grpc_error_details(exc) - except Exception: - pass - - if error_info is not None: - domain = getattr(error_info, "domain", None) - if domain and isinstance(domain, str): - attrs["gcp.errors.domain"] = domain - reason = getattr(error_info, "reason", None) - if reason and isinstance(reason, str): - attrs["error.type"] = reason - metadata = getattr(error_info, "metadata", None) - if metadata and hasattr(metadata, "items"): - for k, v in metadata.items(): - attrs[f"gcp.errors.metadata.{k}"] = str(v) - - return attrs - - def _make_grpc_client_request_hook( endpoint_attrs: dict[str, Any] | None = None, ) -> Callable[[Any, Any], None]: diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index e25139ce0a39..3e720535f4bd 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -416,83 +416,6 @@ def test_grpc_client_request_hook(): mock_span_custom.update_name.assert_not_called() -def test_extract_error_attributes_none(): - """Proves that _extract_error_attributes returns an empty dict when exception is None.""" - assert _observability._extract_error_attributes(None) == {} - - -def test_extract_error_attributes_standard_exception(): - """Proves that _extract_error_attributes returns an empty dict for standard exceptions without ErrorInfo.""" - assert ( - _observability._extract_error_attributes(ValueError("unexpected error")) == {} - ) - - -def test_extract_error_attributes_with_error_info(): - """Proves that _extract_error_attributes extracts domain, error.type, and metadata from ErrorInfo.""" - error_info = types.SimpleNamespace( - domain="googleapis.com", - reason="SERVICE_DISABLED", - metadata={ - "service": "secretmanager.googleapis.com", - "consumer": "projects/123", - }, - ) - exc = types.SimpleNamespace(error_info=error_info) - attrs = _observability._extract_error_attributes(exc) - assert attrs == { - "gcp.errors.domain": "googleapis.com", - "error.type": "SERVICE_DISABLED", - "gcp.errors.metadata.service": "secretmanager.googleapis.com", - "gcp.errors.metadata.consumer": "projects/123", - } - - -def test_extract_error_attributes_from_grpc_trailing_metadata(monkeypatch): - """Proves that _extract_error_attributes parses error_info from gRPC trailing metadata.""" - from google.api_core import exceptions - - mock_exc = mock.Mock() - mock_exc.error_info = None - mock_exc.trailing_metadata = mock.Mock() - - parsed_error_info = types.SimpleNamespace( - domain="googleapis.com", - reason="RESOURCE_EXHAUSTED", - metadata={"quota_limit": "100"}, - ) - - monkeypatch.setattr( - exceptions, - "_parse_grpc_error_details", - mock.Mock(return_value=(None, parsed_error_info)), - ) - - attrs = _observability._extract_error_attributes(mock_exc) - assert attrs == { - "gcp.errors.domain": "googleapis.com", - "error.type": "RESOURCE_EXHAUSTED", - "gcp.errors.metadata.quota_limit": "100", - } - - -def test_extract_error_attributes_trailing_metadata_failure(monkeypatch): - """Proves that _extract_error_attributes safely handles exceptions during trailing metadata parsing.""" - from google.api_core import exceptions - - mock_exc = mock.Mock() - mock_exc.error_info = None - mock_exc.trailing_metadata = mock.Mock() - - monkeypatch.setattr( - exceptions, - "_parse_grpc_error_details", - mock.Mock(side_effect=RuntimeError("Parse failed")), - ) - - assert _observability._extract_error_attributes(mock_exc) == {} - - def test_get_otel_interceptor_with_api_endpoint(monkeypatch): """Proves that get_otel_interceptor injects server.address, server.port, and url.domain when api_endpoint is set.""" monkeypatch.setenv("GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED", "true") From 1c1b9afcd515a565a71dc6d227c01fc03b5d98e1 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Thu, 10 Sep 2026 10:29:31 -0400 Subject: [PATCH 11/43] fix(observability): resolve mypy union-attr error and support environments without grpc --- .../google/api_core/_observability.py | 41 ++++++++++++++++--- 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index 4ad2b60b6e1e..a14e2f43ddc7 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -157,8 +157,10 @@ def client_request_hook(span: Any, request: Any) -> None: # Remove duplicate legacy rpc.system attribute set by stock instrumentation # in favor of modern rpc.system.name ("grpc") per PRD changelog. span_attributes = getattr(span, "_attributes", None) - if hasattr(span_attributes, "pop"): - span_attributes.pop("rpc.system", None) + if span_attributes is not None: + pop_fn = getattr(span_attributes, "pop", None) + if callable(pop_fn): + pop_fn("rpc.system", None) attrs = _extract_grpc_request_attributes(request) if clean_method_name: @@ -173,6 +175,29 @@ def client_request_hook(span: Any, request: Any) -> None: _grpc_client_request_hook = _make_grpc_client_request_hook() +# Mapping of standard gRPC integer status codes to their canonical status name strings. +# Used when stock gRPC wire spans encounter errors, guaranteeing mapping even in environments +# where the optional `grpc` package is not installed (e.g. REST-only environments). +_GRPC_INT_STATUS_CODE_TO_NAME = { + 0: "OK", + 1: "CANCELLED", + 2: "UNKNOWN", + 3: "INVALID_ARGUMENT", + 4: "DEADLINE_EXCEEDED", + 5: "NOT_FOUND", + 6: "ALREADY_EXISTS", + 7: "PERMISSION_DENIED", + 8: "RESOURCE_EXHAUSTED", + 9: "FAILED_PRECONDITION", + 10: "ABORTED", + 11: "OUT_OF_RANGE", + 12: "UNIMPLEMENTED", + 13: "INTERNAL", + 14: "UNAVAILABLE", + 15: "DATA_LOSS", + 16: "UNAUTHENTICATED", +} + def _grpc_client_response_hook(span: Any, response: Any) -> None: """OpenTelemetry gRPC client response hook to record response status code. @@ -199,12 +224,16 @@ def _grpc_client_response_hook(span: Any, response: Any) -> None: if grpc_code is not None: from google.api_core import exceptions + name = None if grpc_code in exceptions._INT_TO_GRPC_CODE: - span.set_attribute( - "rpc.response.status_code", - exceptions._INT_TO_GRPC_CODE[grpc_code].name, - ) + name = exceptions._INT_TO_GRPC_CODE[grpc_code].name + elif grpc_code in _GRPC_INT_STATUS_CODE_TO_NAME: + name = _GRPC_INT_STATUS_CODE_TO_NAME[grpc_code] + if name: + span.set_attribute("rpc.response.status_code", name) return + span.set_attribute("rpc.response.status_code", "ERROR") + return except Exception: pass From 81b686ce1ab86c4fa7783618e107ba9e471e849f Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Thu, 10 Sep 2026 10:50:35 -0400 Subject: [PATCH 12/43] refactor(observability): simplify response hook to record OK on successful RPCs --- .../google/api_core/_observability.py | 60 ++----------------- .../tests/unit/test_observability.py | 14 ----- 2 files changed, 5 insertions(+), 69 deletions(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index a14e2f43ddc7..07cc352cd31c 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -175,69 +175,19 @@ def client_request_hook(span: Any, request: Any) -> None: _grpc_client_request_hook = _make_grpc_client_request_hook() -# Mapping of standard gRPC integer status codes to their canonical status name strings. -# Used when stock gRPC wire spans encounter errors, guaranteeing mapping even in environments -# where the optional `grpc` package is not installed (e.g. REST-only environments). -_GRPC_INT_STATUS_CODE_TO_NAME = { - 0: "OK", - 1: "CANCELLED", - 2: "UNKNOWN", - 3: "INVALID_ARGUMENT", - 4: "DEADLINE_EXCEEDED", - 5: "NOT_FOUND", - 6: "ALREADY_EXISTS", - 7: "PERMISSION_DENIED", - 8: "RESOURCE_EXHAUSTED", - 9: "FAILED_PRECONDITION", - 10: "ABORTED", - 11: "OUT_OF_RANGE", - 12: "UNIMPLEMENTED", - 13: "INTERNAL", - 14: "UNAVAILABLE", - 15: "DATA_LOSS", - 16: "UNAUTHENTICATED", -} - def _grpc_client_response_hook(span: Any, response: Any) -> None: """OpenTelemetry gRPC client response hook to record response status code. + Note: Upstream OpenTelemetry gRPC instrumentation only invokes this response_hook + on successful RPC invocations. Failed RPCs raise an exception before this hook is reached. + Args: span: The OpenTelemetry span. response: The gRPC response object or details. """ - if span is None or not hasattr(span, "set_attribute"): - return - - status = getattr(span, "status", None) - status_code = getattr(status, "status_code", None) - try: - from opentelemetry.trace.status import StatusCode - - if status_code == StatusCode.ERROR: - span_attrs = ( - getattr(span, "attributes", None) - or getattr(span, "_attributes", None) - or {} - ) - grpc_code = span_attrs.get("rpc.grpc.status_code") - if grpc_code is not None: - from google.api_core import exceptions - - name = None - if grpc_code in exceptions._INT_TO_GRPC_CODE: - name = exceptions._INT_TO_GRPC_CODE[grpc_code].name - elif grpc_code in _GRPC_INT_STATUS_CODE_TO_NAME: - name = _GRPC_INT_STATUS_CODE_TO_NAME[grpc_code] - if name: - span.set_attribute("rpc.response.status_code", name) - return - span.set_attribute("rpc.response.status_code", "ERROR") - return - except Exception: - pass - - span.set_attribute("rpc.response.status_code", "OK") + if span is not None and hasattr(span, "set_attribute"): + span.set_attribute("rpc.response.status_code", "OK") def _get_tracer_provider( diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 3e720535f4bd..635505dea8c3 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -497,20 +497,6 @@ def test_grpc_client_response_hook_success(): mock_span.set_attribute.assert_called_once_with("rpc.response.status_code", "OK") -def test_grpc_client_response_hook_error_mapped(): - """Proves that _grpc_client_response_hook maps status code when span has error status.""" - from opentelemetry.trace.status import StatusCode - - mock_span = mock.Mock() - mock_span.status.status_code = StatusCode.ERROR - mock_span.attributes = {"rpc.grpc.status_code": 5} - - _observability._grpc_client_response_hook(mock_span, None) - mock_span.set_attribute.assert_called_once_with( - "rpc.response.status_code", "NOT_FOUND" - ) - - def test_grpc_client_response_hook_none_or_missing_set_attribute(): """Proves that _grpc_client_response_hook handles None or invalid span gracefully.""" _observability._grpc_client_response_hook(None, mock.Mock()) From 324b866237447f429520f984de401ca69d06695f Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Thu, 10 Sep 2026 13:40:39 -0400 Subject: [PATCH 13/43] test(observability): cover request hook span edge cases for 100% branch coverage --- .../tests/unit/test_observability.py | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 635505dea8c3..52554beba345 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -416,6 +416,40 @@ def test_grpc_client_request_hook(): mock_span_custom.update_name.assert_not_called() +def test_grpc_client_request_hook_span_edge_cases(): + """Proves that _grpc_client_request_hook handles spans lacking update_name, + spans with None _attributes, and spans with un-poppable _attributes gracefully. + """ + # 1. Leading slash in span.name but span lacks update_name (exercises 154->159) + mock_span_no_update = mock.Mock( + spec=["is_recording", "name", "_attributes", "set_attribute"] + ) + mock_span_no_update.is_recording.return_value = True + mock_span_no_update.name = "/package.Service/Method" + mock_span_no_update._attributes = {"rpc.system": "grpc"} + _observability._grpc_client_request_hook(mock_span_no_update, None) + mock_span_no_update.set_attribute.assert_any_call( + "rpc.method", "package.Service/Method" + ) + + # 2. Span with None _attributes (exercises 160->165) + mock_span_no_attrs = mock.Mock(spec=["is_recording", "name", "set_attribute"]) + mock_span_no_attrs.is_recording.return_value = True + mock_span_no_attrs.name = "clean_name" + _observability._grpc_client_request_hook(mock_span_no_attrs, None) + mock_span_no_attrs.set_attribute.assert_any_call("rpc.system.name", "grpc") + + # 3. Span with non-dict / un-poppable _attributes (exercises 162->165) + mock_span_unpoppable = mock.Mock( + spec=["is_recording", "name", "_attributes", "set_attribute"] + ) + mock_span_unpoppable.is_recording.return_value = True + mock_span_unpoppable.name = "clean_name" + mock_span_unpoppable._attributes = object() + _observability._grpc_client_request_hook(mock_span_unpoppable, None) + mock_span_unpoppable.set_attribute.assert_any_call("rpc.system.name", "grpc") + + def test_get_otel_interceptor_with_api_endpoint(monkeypatch): """Proves that get_otel_interceptor injects server.address, server.port, and url.domain when api_endpoint is set.""" monkeypatch.setenv("GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED", "true") From abeaf048020eb5ac728521e9803d47b7ae122c4d Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 11 Sep 2026 08:07:42 -0400 Subject: [PATCH 14/43] fix(observability): safely handle invalid port in endpoint attributes --- .../google/api_core/_observability.py | 17 +++++++++++------ .../tests/unit/test_observability.py | 4 ++++ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index 07cc352cd31c..5bd28af8cb49 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -93,15 +93,20 @@ def _extract_endpoint_attributes( if endpoint and isinstance(endpoint, str): target = endpoint if "//" in endpoint else f"//{endpoint}" parsed = urllib.parse.urlsplit(target) - if parsed.hostname: - attrs["server.address"] = parsed.hostname - if parsed.port: + port = None + try: + if parsed.hostname: + attrs["server.address"] = parsed.hostname + port = parsed.port + except ValueError: + pass + if port: scheme = parsed.scheme.lower() - is_default_port = (parsed.port == 443 and scheme in ("https", "")) or ( - parsed.port == 80 and scheme == "http" + is_default_port = (port == 443 and scheme in ("https", "")) or ( + port == 80 and scheme == "http" ) if not is_default_port: - attrs["server.port"] = parsed.port + attrs["server.port"] = port return attrs diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 52554beba345..96efabf3611f 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -327,6 +327,10 @@ def test_get_otel_async_interceptor_enabled(monkeypatch): ClientOptions(api_endpoint="http:///"), {"url.domain": "googleapis.com"}, ), + ( + ClientOptions(api_endpoint="example.com:not_a_port"), + {"server.address": "example.com", "url.domain": "googleapis.com"}, + ), ], ) def test_extract_endpoint_attributes(client_options, expected_attrs): From 99a4d3d874258997880112098838e1b7687353c7 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 11 Sep 2026 10:18:39 -0400 Subject: [PATCH 15/43] fix(observability): ensure response hook only records OK on successful calls --- .../google/api_core/_observability.py | 20 +++++++++---- .../tests/unit/test_observability.py | 30 ++++++++++++++++--- 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index 5bd28af8cb49..f614822eed10 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -184,15 +184,25 @@ def client_request_hook(span: Any, request: Any) -> None: def _grpc_client_response_hook(span: Any, response: Any) -> None: """OpenTelemetry gRPC client response hook to record response status code. - Note: Upstream OpenTelemetry gRPC instrumentation only invokes this response_hook - on successful RPC invocations. Failed RPCs raise an exception before this hook is reached. - Args: span: The OpenTelemetry span. response: The gRPC response object or details. """ - if span is not None and hasattr(span, "set_attribute"): - span.set_attribute("rpc.response.status_code", "OK") + if not span.is_recording(): + return + + # Verify the RPC succeeded before recording the OK response status. + # Upstream async instrumentation invokes this hook on both successes + # and failures, so check whether an error status was already recorded. + status = getattr(span, "status", None) + status_code = getattr(status, "status_code", None) + if ( + getattr(status_code, "name", None) == "ERROR" + or getattr(status_code, "value", None) == 2 + ): + return + + span.set_attribute("rpc.response.status_code", "OK") def _get_tracer_provider( diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 96efabf3611f..4b82cb43fce9 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -531,11 +531,33 @@ def test_get_otel_async_interceptor_with_api_endpoint(monkeypatch): def test_grpc_client_response_hook_success(): """Proves that _grpc_client_response_hook sets rpc.response.status_code to 'OK' on success.""" mock_span = mock.Mock() + mock_span.is_recording.return_value = True _observability._grpc_client_response_hook(mock_span, mock.Mock()) mock_span.set_attribute.assert_called_once_with("rpc.response.status_code", "OK") -def test_grpc_client_response_hook_none_or_missing_set_attribute(): - """Proves that _grpc_client_response_hook handles None or invalid span gracefully.""" - _observability._grpc_client_response_hook(None, mock.Mock()) - _observability._grpc_client_response_hook(object(), mock.Mock()) +def test_grpc_client_response_hook_not_recording(): + """Proves that _grpc_client_response_hook skips non-recording spans.""" + mock_span = mock.Mock() + mock_span.is_recording.return_value = False + _observability._grpc_client_response_hook(mock_span, mock.Mock()) + mock_span.set_attribute.assert_not_called() + + +def test_grpc_client_response_hook_error_status(): + """Proves that _grpc_client_response_hook skips spans marked with ERROR status.""" + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + mock_span.status.status_code.name = "ERROR" + _observability._grpc_client_response_hook(mock_span, mock.Mock()) + mock_span.set_attribute.assert_not_called() + + +def test_grpc_client_response_hook_error_status_value(): + """Proves that _grpc_client_response_hook skips spans with StatusCode.ERROR value (2).""" + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + mock_span.status.status_code.name = "UNKNOWN" + mock_span.status.status_code.value = 2 + _observability._grpc_client_response_hook(mock_span, mock.Mock()) + mock_span.set_attribute.assert_not_called() From 4b82c9c37db55c10d9ad0e4f9c00487ec9c01b62 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 11 Sep 2026 19:54:11 -0400 Subject: [PATCH 16/43] refactor(observability): address review feedback on method name, url parsing, and attribute handling --- .../google/api_core/_observability.py | 74 +++++------- .../tests/unit/test_observability.py | 105 +++++++----------- 2 files changed, 73 insertions(+), 106 deletions(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index f614822eed10..5e70c95d85b6 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -92,15 +92,19 @@ def _extract_endpoint_attributes( if endpoint and isinstance(endpoint, str): target = endpoint if "//" in endpoint else f"//{endpoint}" - parsed = urllib.parse.urlsplit(target) + parsed = None + hostname = None port = None try: - if parsed.hostname: - attrs["server.address"] = parsed.hostname + parsed = urllib.parse.urlsplit(target) + hostname = parsed.hostname port = parsed.port except ValueError: pass - if port: + + if hostname: + attrs["server.address"] = hostname + if port and parsed: scheme = parsed.scheme.lower() is_default_port = (port == 443 and scheme in ("https", "")) or ( port == 80 and scheme == "http" @@ -110,28 +114,6 @@ def _extract_endpoint_attributes( return attrs -def _extract_grpc_request_attributes(request: Any) -> dict[str, Any]: - """Extracts Google Cloud T4 semantic and resource attributes from a gRPC request object. - - Args: - request: The gRPC request object. - - Returns: - dict[str, Any]: A dictionary of semantic attributes. - """ - attrs: dict[str, Any] = { - "rpc.system.name": "grpc", - } - if request is None: - return attrs - - resend_count = getattr(request, "resend_count", None) - if isinstance(resend_count, int) and resend_count > 0: - attrs["gcp.grpc.resend_count"] = resend_count - - return attrs - - def _make_grpc_client_request_hook( endpoint_attrs: dict[str, Any] | None = None, ) -> Callable[[Any, Any], None]: @@ -149,27 +131,19 @@ def client_request_hook(span: Any, request: Any) -> None: if span is None or not getattr(span, "is_recording", lambda: True)(): return - # Upstream opentelemetry-instrumentation-grpc names spans with a leading slash - # (e.g. "/package.Service/Method") and sets only the short name on rpc.method. - # Normalize span.name and rpc.method to the fully-qualified name without leading slash. + # Upstream opentelemetry-instrumentation-grpc may format span names with a + # leading slash (e.g. "/package.Service/Method"). Normalize the span name + # and ensure rpc.method is always captured as the clean, fully-qualified name. span_name = getattr(span, "name", None) - clean_method_name = None - if isinstance(span_name, str) and span_name.startswith("/"): + if isinstance(span_name, str) and span_name: clean_method_name = span_name.lstrip("/") - if hasattr(span, "update_name"): + if span_name.startswith("/") and hasattr(span, "update_name"): span.update_name(clean_method_name) + span.set_attribute("rpc.method", clean_method_name) - # Remove duplicate legacy rpc.system attribute set by stock instrumentation - # in favor of modern rpc.system.name ("grpc") per PRD changelog. - span_attributes = getattr(span, "_attributes", None) - if span_attributes is not None: - pop_fn = getattr(span_attributes, "pop", None) - if callable(pop_fn): - pop_fn("rpc.system", None) - - attrs = _extract_grpc_request_attributes(request) - if clean_method_name: - attrs["rpc.method"] = clean_method_name + attrs: dict[str, Any] = { + "rpc.system.name": "grpc", + } if static_attrs: attrs.update(static_attrs) for key, value in attrs.items(): @@ -182,7 +156,19 @@ def client_request_hook(span: Any, request: Any) -> None: def _grpc_client_response_hook(span: Any, response: Any) -> None: - """OpenTelemetry gRPC client response hook to record response status code. + """OpenTelemetry gRPC client response hook to record successful response status. + + Upstream ``opentelemetry-instrumentation-grpc`` sets the integer status code + ``rpc.grpc.status_code`` (e.g. 0), but does not record the modern string status + ``rpc.response.status_code`` (e.g. "OK") required by Cloud Trace and current + OpenTelemetry semantic conventions. + + This hook enriches successful RPC attempt spans with ``rpc.response.status_code = "OK"``. + Errors and non-OK statuses are handled at the Tier 3 method span layer or upstream. + + Note: + If upstream ``opentelemetry-instrumentation-grpc`` adds native support for + modern ``rpc.response.status_code`` in future releases, this hook can be retired. Args: span: The OpenTelemetry span. diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 4b82cb43fce9..4d7a0d283fd1 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -13,7 +13,6 @@ # limitations under the License. import sys -import types from unittest import mock import pytest @@ -331,47 +330,24 @@ def test_get_otel_async_interceptor_enabled(monkeypatch): ClientOptions(api_endpoint="example.com:not_a_port"), {"server.address": "example.com", "url.domain": "googleapis.com"}, ), - ], -) -def test_extract_endpoint_attributes(client_options, expected_attrs): - """Proves that _extract_endpoint_attributes correctly parses server.address, non-default server.port, and url.domain.""" - assert _observability._extract_endpoint_attributes(client_options) == expected_attrs - - -@pytest.mark.parametrize( - "req,expected_attrs", - [ - (None, {"rpc.system.name": "grpc"}), - (types.SimpleNamespace(), {"rpc.system.name": "grpc"}), - ( - types.SimpleNamespace(name="projects/p1/secrets/s1"), - {"rpc.system.name": "grpc"}, - ), ( - types.SimpleNamespace(parent="projects/parent-p1"), - {"rpc.system.name": "grpc"}, - ), - ( - types.SimpleNamespace(name="projects/p1/secrets/s1", resend_count=2), - { - "rpc.system.name": "grpc", - "gcp.grpc.resend_count": 2, - }, + ClientOptions(api_endpoint="http://[invalid:ipv6:80/"), + {"url.domain": "googleapis.com"}, ), ( - types.SimpleNamespace(resend_count=0), - {"rpc.system.name": "grpc"}, + ClientOptions(api_endpoint="example.com:99999"), + {"server.address": "example.com", "url.domain": "googleapis.com"}, ), ], ) -def test_extract_grpc_request_attributes(req, expected_attrs): - """Proves that _extract_grpc_request_attributes extracts all T4 gRPC attributes.""" - assert _observability._extract_grpc_request_attributes(req) == expected_attrs +def test_extract_endpoint_attributes(client_options, expected_attrs): + """Proves that _extract_endpoint_attributes correctly parses server.address, non-default server.port, and url.domain.""" + assert _observability._extract_endpoint_attributes(client_options) == expected_attrs def test_grpc_client_request_hook(): """Proves that _grpc_client_request_hook attaches extracted T4 attributes to recording spans, - normalizes span names, sets fully qualified rpc.method, and removes legacy rpc.system. + normalizes span names, sets fully qualified rpc.method, and allows legacy rpc.system to coexist. """ # Non-recording span should not set attributes mock_span_non_rec = mock.Mock() @@ -389,9 +365,8 @@ def test_grpc_client_request_hook(): "/google.cloud.secretmanager.v1.SecretManagerService/ListSecrets" ) mock_span_rec._attributes = {"rpc.system": "grpc"} - req = types.SimpleNamespace(name="projects/my-proj/secrets/s1", resend_count=1) - _observability._grpc_client_request_hook(mock_span_rec, req) + _observability._grpc_client_request_hook(mock_span_rec, mock.Mock()) # Verify span name normalized and rpc.method set to fully qualified name mock_span_rec.update_name.assert_called_once_with( @@ -401,57 +376,63 @@ def test_grpc_client_request_hook(): "rpc.method", "google.cloud.secretmanager.v1.SecretManagerService/ListSecrets" ) - # Verify rpc.system.name set and legacy rpc.system popped + # Verify rpc.system.name set and legacy rpc.system left intact mock_span_rec.set_attribute.assert_any_call("rpc.system.name", "grpc") - assert "rpc.system" not in mock_span_rec._attributes - - mock_span_rec.set_attribute.assert_any_call("gcp.grpc.resend_count", 1) + assert mock_span_rec._attributes["rpc.system"] == "grpc" - # Custom hook with endpoint attributes and already-clean span name + # Custom hook with endpoint attributes and already-clean span name (no leading slash) endpoint_hook = _observability._make_grpc_client_request_hook( {"server.address": "custom.api.com", "server.port": 443} ) mock_span_custom = mock.Mock() mock_span_custom.is_recording.return_value = True - mock_span_custom.name = "already_clean_name" - endpoint_hook(mock_span_custom, req) + mock_span_custom.name = ( + "google.cloud.secretmanager.v1.SecretManagerService/ListSecrets" + ) + endpoint_hook(mock_span_custom, None) mock_span_custom.set_attribute.assert_any_call("server.address", "custom.api.com") mock_span_custom.set_attribute.assert_any_call("server.port", 443) + mock_span_custom.set_attribute.assert_any_call( + "rpc.method", "google.cloud.secretmanager.v1.SecretManagerService/ListSecrets" + ) mock_span_custom.update_name.assert_not_called() def test_grpc_client_request_hook_span_edge_cases(): """Proves that _grpc_client_request_hook handles spans lacking update_name, - spans with None _attributes, and spans with un-poppable _attributes gracefully. + spans with None or non-string names, and empty string names gracefully. """ - # 1. Leading slash in span.name but span lacks update_name (exercises 154->159) - mock_span_no_update = mock.Mock( - spec=["is_recording", "name", "_attributes", "set_attribute"] - ) + # 1. Leading slash in span.name but span lacks update_name + mock_span_no_update = mock.Mock(spec=["is_recording", "name", "set_attribute"]) mock_span_no_update.is_recording.return_value = True mock_span_no_update.name = "/package.Service/Method" - mock_span_no_update._attributes = {"rpc.system": "grpc"} _observability._grpc_client_request_hook(mock_span_no_update, None) mock_span_no_update.set_attribute.assert_any_call( "rpc.method", "package.Service/Method" ) + mock_span_no_update.set_attribute.assert_any_call("rpc.system.name", "grpc") + + # 2. Span with None name + mock_span_none_name = mock.Mock(spec=["is_recording", "name", "set_attribute"]) + mock_span_none_name.is_recording.return_value = True + mock_span_none_name.name = None + _observability._grpc_client_request_hook(mock_span_none_name, None) + mock_span_none_name.set_attribute.assert_any_call("rpc.system.name", "grpc") + assert not any( + call.args[0] == "rpc.method" + for call in mock_span_none_name.set_attribute.call_args_list + ) - # 2. Span with None _attributes (exercises 160->165) - mock_span_no_attrs = mock.Mock(spec=["is_recording", "name", "set_attribute"]) - mock_span_no_attrs.is_recording.return_value = True - mock_span_no_attrs.name = "clean_name" - _observability._grpc_client_request_hook(mock_span_no_attrs, None) - mock_span_no_attrs.set_attribute.assert_any_call("rpc.system.name", "grpc") - - # 3. Span with non-dict / un-poppable _attributes (exercises 162->165) - mock_span_unpoppable = mock.Mock( - spec=["is_recording", "name", "_attributes", "set_attribute"] + # 3. Span with empty string name + mock_span_empty_name = mock.Mock(spec=["is_recording", "name", "set_attribute"]) + mock_span_empty_name.is_recording.return_value = True + mock_span_empty_name.name = "" + _observability._grpc_client_request_hook(mock_span_empty_name, None) + mock_span_empty_name.set_attribute.assert_any_call("rpc.system.name", "grpc") + assert not any( + call.args[0] == "rpc.method" + for call in mock_span_empty_name.set_attribute.call_args_list ) - mock_span_unpoppable.is_recording.return_value = True - mock_span_unpoppable.name = "clean_name" - mock_span_unpoppable._attributes = object() - _observability._grpc_client_request_hook(mock_span_unpoppable, None) - mock_span_unpoppable.set_attribute.assert_any_call("rpc.system.name", "grpc") def test_get_otel_interceptor_with_api_endpoint(monkeypatch): From 0fb354a1db91c5e140b900ef93a52257c804ee0f Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 14 Sep 2026 04:57:49 -0400 Subject: [PATCH 17/43] docs(observability): clarify sync vs async behavior and specify semconv version in response hook --- .../google/api_core/_observability.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index 5e70c95d85b6..2d8c50acbfa9 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -161,11 +161,22 @@ def _grpc_client_response_hook(span: Any, response: Any) -> None: Upstream ``opentelemetry-instrumentation-grpc`` sets the integer status code ``rpc.grpc.status_code`` (e.g. 0), but does not record the modern string status ``rpc.response.status_code`` (e.g. "OK") required by Cloud Trace and current - OpenTelemetry semantic conventions. + OpenTelemetry semantic conventions (v1.27.0+). This hook enriches successful RPC attempt spans with ``rpc.response.status_code = "OK"``. Errors and non-OK statuses are handled at the Tier 3 method span layer or upstream. + Upstream handles synchronous and asynchronous invocations differently: + - **Synchronous gRPC**: Upstream only invokes the response hook when an RPC call + succeeds. On failure, the hook is bypassed entirely. + - **Asynchronous gRPC**: Upstream invokes the response hook unconditionally for + both successes and failures (passing exception details on error). However, it + always marks ``span.status`` with an error status before calling the hook. + + Because of this disparity, this hook checks ``span.status`` to guard against + async failure callbacks while allowing synchronous and successful asynchronous + calls to be marked "OK". + Note: If upstream ``opentelemetry-instrumentation-grpc`` adds native support for modern ``rpc.response.status_code`` in future releases, this hook can be retired. @@ -177,9 +188,7 @@ def _grpc_client_response_hook(span: Any, response: Any) -> None: if not span.is_recording(): return - # Verify the RPC succeeded before recording the OK response status. - # Upstream async instrumentation invokes this hook on both successes - # and failures, so check whether an error status was already recorded. + # Guard against upstream async calls that invoke this hook on failures. status = getattr(span, "status", None) status_code = getattr(status, "status_code", None) if ( From acce308b77bbe62c68cab2e229483f8ea517a2fd Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 11 Sep 2026 07:12:21 -0400 Subject: [PATCH 18/43] feat(gapic): add OpenTelemetry channel tracing to generator templates --- .../%sub/services/%service/client.py.j2 | 74 ++++++++++------ .../services/%service/transports/grpc.py.j2 | 20 ++++- .../%name_%version/%sub/test_%service.py.j2 | 85 +++++++++++++++++++ 3 files changed, 153 insertions(+), 26 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 index 01407a160d99..37d55e659097 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 @@ -53,6 +53,13 @@ try: except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# mypy: _observability was added in google-api-core 2.35.0; guard for older versions +try: + from google.api_core import _observability # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + _observability = None # type: ignore[assignment] + _LOGGER = std_logging.getLogger(__name__) {% filter sort_lines %} @@ -314,17 +321,17 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): client_cert_source = mtls.default_client_cert_source() return client_cert_source - + def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. - + Returns: bool: True iff the configured universe domain is valid. Raises: ValueError: If the configured universe domain is not valid. """ - + # NOTE (b/349488459): universe validation is disabled until further notice. return True @@ -355,21 +362,21 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): @property def api_endpoint(self) -> str: """Return the API endpoint used by the client instance. - + Returns: str: The API endpoint used by the client instance. """ return self._api_endpoint - + @property def universe_domain(self) -> str: """Return the universe domain used by the client instance. - + Returns: str: The universe domain used by the client instance. """ return self._universe_domain - + def __init__(self, *, credentials: Optional[ga_credentials.Credentials] = None, transport: Optional[Union[str, {{ service.name }}Transport, Callable[..., {{ service.name }}Transport]]] = None, @@ -397,8 +404,8 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): {% endif %} client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the + + 1. The ``api_endpoint`` property can be used to override the default endpoint provided by the client when ``transport`` is not explicitly provided. Only if this property is not set and ``transport`` was not explicitly provided, the endpoint is @@ -415,7 +422,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. - + 3. The ``universe_domain`` property can be used to override the default "googleapis.com" universe. Note that the ``api_endpoint`` property still takes precedence; and ``universe_domain`` is @@ -473,7 +480,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): self._transport = cast({{ service.name }}Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or + self._api_endpoint = (self._api_endpoint or get_api_endpoint( api_override=self._client_options.api_endpoint, universe_domain=self._universe_domain, @@ -531,19 +538,38 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): else cast(Callable[..., {{ service.name }}Transport], transport) ) {% endif %} + # When OpenTelemetry tracing is enabled, obtain the channel interceptor + # and pass it to the transport. + interceptors = [] + {% if 'grpc' in opts.transport %} + if ( + transport_init is {{ service.grpc_transport_name }} + and _observability is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None + ): + interceptors.append(otel_interceptor) + {% endif %} + # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - + transport_kwargs = { + "credentials": credentials, + "credentials_file": self._client_options.credentials_file, + "host": self._api_endpoint, + "scopes": self._client_options.scopes, + "client_cert_source_for_mtls": self._client_cert_source, + "quota_project_id": self._client_options.quota_project_id, + "client_info": client_info, + "always_use_jwt_access": True, + "api_audience": self._client_options.api_audience, + **({"interceptors": interceptors} if interceptors else {}), + } + self._transport = transport_init(**transport_kwargs) + if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( @@ -827,7 +853,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): gapic_v1.routing_header.to_grpc_metadata( (("resource", request_pb.resource),)), ) - + # Validate the universe domain. self._validate_universe_domain() diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 index e906c9d9ea71..b644db807432 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 @@ -11,6 +11,7 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers +from google.api_core.grpc_helpers import ClientInterceptor {% if service.has_lro %} from google.api_core import operations_v1 {% endif %} @@ -80,7 +81,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO grpc_response = { "payload": response_payload, "metadata": metadata, - "status": "OK", + "status": "OK", } _LOGGER.debug( f"Received response for {client_call_details.method}.", @@ -123,6 +124,14 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport): client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + ClientInterceptor, + Callable[[grpc.Channel], grpc.Channel], + ] + ] + ] = None, ) -> None: """Instantiate the transport. @@ -143,7 +152,7 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport): ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` + that constructs and returns one. If set to None, ``self.create_channel`` is used to create the channel. If a Callable is given, it will be called with the same arguments as used in ``self.create_channel``. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. @@ -173,6 +182,9 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport): to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): + Additional interceptors (or callables that apply interceptors) to apply to the + gRPC channel. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -252,6 +264,10 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport): ], ) + self._grpc_channel = grpc_helpers.apply_channel_interceptors( + self._grpc_channel, interceptors + ) + self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 index 68e754caf287..832d735656c9 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 @@ -904,6 +904,91 @@ def test_{{ service.client_name|snake_case }}_client_options_from_dict(): ) +def test_{{ service.client_name|snake_case }}_otel_channel_injection_enabled(): + mock_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_interceptor + with ( + mock.patch( + "{{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join('.') }}.services.{{ service.name|snake_case }}.client._observability", + mock_obs, + ), + mock.patch.object( + transports.{{ service.grpc_transport_name }}, "__init__", return_value=None + ) as patched_transport_init, + ): + client = {{ service.client_name }}(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert called_kwargs.get("interceptors") == [mock_interceptor] + + +def test_{{ service.client_name|snake_case }}_otel_channel_injection_disabled(): + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = None + with ( + mock.patch( + "{{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join('.') }}.services.{{ service.name|snake_case }}.client._observability", + mock_obs, + ), + mock.patch.object( + transports.{{ service.grpc_transport_name }}, "__init__", return_value=None + ) as patched_transport_init, + ): + client = {{ service.client_name }}(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert not called_kwargs.get("interceptors", []) + + +def test_{{ service.name|snake_case }}_grpc_transport_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_channel = mock.Mock() + + with ( + mock.patch.object( + transports.{{ service.grpc_transport_name }}, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + ) as mock_apply_interceptors, + ): + transport = transports.{{ service.grpc_transport_name }}( + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_channel + + +def test_{{ service.name|snake_case }}_grpc_transport_custom_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_custom_channel = mock.Mock(spec=grpc.Channel) + + with mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_custom_channel, + ) as mock_apply_interceptors: + transport = transports.{{ service.grpc_transport_name }}( + channel=mock_custom_channel, + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_custom_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_custom_channel + + @pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ ({{ service.client_name }}, transports.{{ service.grpc_transport_name }}, "grpc", grpc_helpers), ({{ service.async_client_name }}, transports.{{ service.grpc_asyncio_transport_name }}, "grpc_asyncio", grpc_helpers_async), From d337933a4dd5098954195333cf962f5e97150451 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 11 Sep 2026 07:36:34 -0400 Subject: [PATCH 19/43] fix(gapic): resolve CI import errors on unreleased ClientInterceptor and fix mypy comment --- .../%sub/services/%service/client.py.j2 | 2 +- .../services/%service/transports/grpc.py.j2 | 22 +++++++++++++++---- .../%name_%version/%sub/test_%service.py.j2 | 2 ++ 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 index 37d55e659097..5156805f1e38 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 @@ -54,7 +54,7 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# mypy: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.35.0; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 index b644db807432..75b6304c0316 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 @@ -10,8 +10,20 @@ import pickle import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import grpc # type: ignore from google.api_core import grpc_helpers -from google.api_core.grpc_helpers import ClientInterceptor + +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +try: + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + ClientInterceptor = Union[ # type: ignore[misc,assignment] + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, + ] {% if service.has_lro %} from google.api_core import operations_v1 {% endif %} @@ -22,7 +34,6 @@ from google.auth.transport.grpc import SslCredentials # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore import proto # type: ignore {% filter sort_lines %} @@ -264,9 +275,12 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport): ], ) - self._grpc_channel = grpc_helpers.apply_channel_interceptors( - self._grpc_channel, interceptors + apply_interceptors = getattr( + grpc_helpers, + "apply_channel_interceptors", + lambda channel, interceptors: channel, ) + self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 index 832d735656c9..a0fe129f98d9 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 @@ -957,6 +957,7 @@ def test_{{ service.name|snake_case }}_grpc_transport_channel_interceptors(): grpc_helpers, "apply_channel_interceptors", return_value=mock_channel, + create=True, ) as mock_apply_interceptors, ): transport = transports.{{ service.grpc_transport_name }}( @@ -977,6 +978,7 @@ def test_{{ service.name|snake_case }}_grpc_transport_custom_channel_interceptor grpc_helpers, "apply_channel_interceptors", return_value=mock_custom_channel, + create=True, ) as mock_apply_interceptors: transport = transports.{{ service.grpc_transport_name }}( channel=mock_custom_channel, From 13f12183a0e5df73fb918bb172bc1a5f3d55a3ba Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 11 Sep 2026 07:44:15 -0400 Subject: [PATCH 20/43] fix(gapic): use AnonymousCredentials in test_grpc_transport_channel_interceptors --- .../tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 index a0fe129f98d9..ec499686a51d 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 @@ -961,6 +961,7 @@ def test_{{ service.name|snake_case }}_grpc_transport_channel_interceptors(): ) as mock_apply_interceptors, ): transport = transports.{{ service.grpc_transport_name }}( + credentials=ga_credentials.AnonymousCredentials(), interceptors=[mock_interceptor], ) From 11ccd0d9df59638b1146ae59df5d8ebf4bf1b998 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 11 Sep 2026 12:47:44 -0400 Subject: [PATCH 21/43] test(gapic): update bazel integration goldens for otel channel tracing --- .../asset_v1/services/asset_service/client.py | 46 +++++++--- .../services/asset_service/transports/grpc.py | 32 ++++++- .../unit/gapic/asset_v1/test_asset_service.py | 88 +++++++++++++++++++ .../services/iam_credentials/client.py | 46 +++++++--- .../iam_credentials/transports/grpc.py | 32 ++++++- .../credentials_v1/test_iam_credentials.py | 88 +++++++++++++++++++ .../eventarc_v1/services/eventarc/client.py | 46 +++++++--- .../services/eventarc/transports/grpc.py | 32 ++++++- .../unit/gapic/eventarc_v1/test_eventarc.py | 88 +++++++++++++++++++ .../services/config_service_v2/client.py | 46 +++++++--- .../config_service_v2/transports/grpc.py | 32 ++++++- .../services/logging_service_v2/client.py | 46 +++++++--- .../logging_service_v2/transports/grpc.py | 32 ++++++- .../services/metrics_service_v2/client.py | 46 +++++++--- .../metrics_service_v2/transports/grpc.py | 32 ++++++- .../logging_v2/test_config_service_v2.py | 88 +++++++++++++++++++ .../logging_v2/test_logging_service_v2.py | 88 +++++++++++++++++++ .../logging_v2/test_metrics_service_v2.py | 88 +++++++++++++++++++ .../services/config_service_v2/client.py | 46 +++++++--- .../config_service_v2/transports/grpc.py | 32 ++++++- .../services/logging_service_v2/client.py | 46 +++++++--- .../logging_service_v2/transports/grpc.py | 32 ++++++- .../services/metrics_service_v2/client.py | 46 +++++++--- .../metrics_service_v2/transports/grpc.py | 32 ++++++- .../logging_v2/test_config_service_v2.py | 88 +++++++++++++++++++ .../logging_v2/test_logging_service_v2.py | 88 +++++++++++++++++++ .../logging_v2/test_metrics_service_v2.py | 88 +++++++++++++++++++ .../redis_v1/services/cloud_redis/client.py | 46 +++++++--- .../services/cloud_redis/transports/grpc.py | 32 ++++++- .../unit/gapic/redis_v1/test_cloud_redis.py | 88 +++++++++++++++++++ .../redis_v1/services/cloud_redis/client.py | 46 +++++++--- .../services/cloud_redis/transports/grpc.py | 32 ++++++- .../unit/gapic/redis_v1/test_cloud_redis.py | 88 +++++++++++++++++++ .../storage_batch_operations/client.py | 46 +++++++--- .../transports/grpc.py | 32 ++++++- .../test_storage_batch_operations.py | 88 +++++++++++++++++++ 36 files changed, 1848 insertions(+), 144 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py index ffc75791c484..12e669a8e11c 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py @@ -47,6 +47,13 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: _observability was added in google-api-core 2.35.0; guard for older versions +try: + from google.api_core import _observability # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + _observability = None # type: ignore[assignment] + _LOGGER = std_logging.getLogger(__name__) from google.cloud.asset_v1.services.asset_service import pagers @@ -545,18 +552,35 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., AssetServiceTransport], transport) ) + # When OpenTelemetry tracing is enabled, obtain the channel interceptor + # and pass it to the transport. + interceptors = [] + if ( + transport_init is AssetServiceGrpcTransport + and _observability is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None + ): + interceptors.append(otel_interceptor) + # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) + transport_kwargs = { + "credentials": credentials, + "credentials_file": self._client_options.credentials_file, + "host": self._api_endpoint, + "scopes": self._client_options.scopes, + "client_cert_source_for_mtls": self._client_cert_source, + "quota_project_id": self._client_options.quota_project_id, + "client_info": client_info, + "always_use_jwt_access": True, + "api_audience": self._client_options.api_audience, + **({"interceptors": interceptors} if interceptors else {}), + } + self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py index 848bb1096cbe..498ecc1dfa24 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -19,7 +19,20 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import grpc # type: ignore from google.api_core import grpc_helpers + +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +try: + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + ClientInterceptor = Union[ # type: ignore[misc,assignment] + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, + ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -28,7 +41,6 @@ from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore import proto # type: ignore from google.cloud.asset_v1.types import asset_service @@ -132,6 +144,14 @@ def __init__(self, *, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + ClientInterceptor, + Callable[[grpc.Channel], grpc.Channel], + ] + ] + ] = None, ) -> None: """Instantiate the transport. @@ -182,6 +202,9 @@ def __init__(self, *, to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): + Additional interceptors (or callables that apply interceptors) to apply to the + gRPC channel. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -259,6 +282,13 @@ def __init__(self, *, ], ) + apply_interceptors = getattr( + grpc_helpers, + "apply_channel_interceptors", + lambda channel, interceptors: channel, + ) + self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py index e86b23c549e4..1b833561fbe0 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py @@ -760,6 +760,94 @@ def test_asset_service_client_client_options_from_dict(): ) +def test_asset_service_client_otel_channel_injection_enabled(): + mock_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_interceptor + with ( + mock.patch( + "google.cloud.asset_v1.services.asset_service.client._observability", + mock_obs, + ), + mock.patch.object( + transports.AssetServiceGrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = AssetServiceClient(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert called_kwargs.get("interceptors") == [mock_interceptor] + + +def test_asset_service_client_otel_channel_injection_disabled(): + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = None + with ( + mock.patch( + "google.cloud.asset_v1.services.asset_service.client._observability", + mock_obs, + ), + mock.patch.object( + transports.AssetServiceGrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = AssetServiceClient(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert not called_kwargs.get("interceptors", []) + + +def test_asset_service_grpc_transport_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_channel = mock.Mock() + + with ( + mock.patch.object( + transports.AssetServiceGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_channel + + +def test_asset_service_grpc_transport_custom_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_custom_channel = mock.Mock(spec=grpc.Channel) + + with mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_custom_channel, + create=True, + ) as mock_apply_interceptors: + transport = transports.AssetServiceGrpcTransport( + channel=mock_custom_channel, + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_custom_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_custom_channel + + @pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index da065db5907b..65d424866a2a 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -47,6 +47,13 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: _observability was added in google-api-core 2.35.0; guard for older versions +try: + from google.api_core import _observability # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + _observability = None # type: ignore[assignment] + _LOGGER = std_logging.getLogger(__name__) from google.iam.credentials_v1.types import common @@ -482,18 +489,35 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., IAMCredentialsTransport], transport) ) + # When OpenTelemetry tracing is enabled, obtain the channel interceptor + # and pass it to the transport. + interceptors = [] + if ( + transport_init is IAMCredentialsGrpcTransport + and _observability is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None + ): + interceptors.append(otel_interceptor) + # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) + transport_kwargs = { + "credentials": credentials, + "credentials_file": self._client_options.credentials_file, + "host": self._api_endpoint, + "scopes": self._client_options.scopes, + "client_cert_source_for_mtls": self._client_cert_source, + "quota_project_id": self._client_options.quota_project_id, + "client_info": client_info, + "always_use_jwt_access": True, + "api_audience": self._client_options.api_audience, + **({"interceptors": interceptors} if interceptors else {}), + } + self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py index 18428ad7d6e0..7721d3534d56 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py @@ -19,7 +19,20 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import grpc # type: ignore from google.api_core import grpc_helpers + +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +try: + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + ClientInterceptor = Union[ # type: ignore[misc,assignment] + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, + ] from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -27,7 +40,6 @@ from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore import proto # type: ignore from google.iam.credentials_v1.types import common @@ -138,6 +150,14 @@ def __init__(self, *, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + ClientInterceptor, + Callable[[grpc.Channel], grpc.Channel], + ] + ] + ] = None, ) -> None: """Instantiate the transport. @@ -188,6 +208,9 @@ def __init__(self, *, to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): + Additional interceptors (or callables that apply interceptors) to apply to the + gRPC channel. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -264,6 +287,13 @@ def __init__(self, *, ], ) + apply_interceptors = getattr( + grpc_helpers, + "apply_channel_interceptors", + lambda channel, interceptors: channel, + ) + self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py index a13fa010afd5..dfc140216554 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py @@ -750,6 +750,94 @@ def test_iam_credentials_client_client_options_from_dict(): ) +def test_iam_credentials_client_otel_channel_injection_enabled(): + mock_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_interceptor + with ( + mock.patch( + "google.iam.credentials_v1.services.iam_credentials.client._observability", + mock_obs, + ), + mock.patch.object( + transports.IAMCredentialsGrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = IAMCredentialsClient(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert called_kwargs.get("interceptors") == [mock_interceptor] + + +def test_iam_credentials_client_otel_channel_injection_disabled(): + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = None + with ( + mock.patch( + "google.iam.credentials_v1.services.iam_credentials.client._observability", + mock_obs, + ), + mock.patch.object( + transports.IAMCredentialsGrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = IAMCredentialsClient(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert not called_kwargs.get("interceptors", []) + + +def test_iam_credentials_grpc_transport_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_channel = mock.Mock() + + with ( + mock.patch.object( + transports.IAMCredentialsGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + transport = transports.IAMCredentialsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_channel + + +def test_iam_credentials_grpc_transport_custom_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_custom_channel = mock.Mock(spec=grpc.Channel) + + with mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_custom_channel, + create=True, + ) as mock_apply_interceptors: + transport = transports.IAMCredentialsGrpcTransport( + channel=mock_custom_channel, + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_custom_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_custom_channel + + @pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc", grpc_helpers), (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index f5442cba6179..9cf97196a76d 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -47,6 +47,13 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: _observability was added in google-api-core 2.35.0; guard for older versions +try: + from google.api_core import _observability # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + _observability = None # type: ignore[assignment] + _LOGGER = std_logging.getLogger(__name__) from google.cloud.eventarc_v1.services.eventarc import pagers @@ -665,18 +672,35 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., EventarcTransport], transport) ) + # When OpenTelemetry tracing is enabled, obtain the channel interceptor + # and pass it to the transport. + interceptors = [] + if ( + transport_init is EventarcGrpcTransport + and _observability is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None + ): + interceptors.append(otel_interceptor) + # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) + transport_kwargs = { + "credentials": credentials, + "credentials_file": self._client_options.credentials_file, + "host": self._api_endpoint, + "scopes": self._client_options.scopes, + "client_cert_source_for_mtls": self._client_cert_source, + "quota_project_id": self._client_options.quota_project_id, + "client_info": client_info, + "always_use_jwt_access": True, + "api_audience": self._client_options.api_audience, + **({"interceptors": interceptors} if interceptors else {}), + } + self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py index ac5d9a0fbe92..9435b1510b97 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py @@ -19,7 +19,20 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import grpc # type: ignore from google.api_core import grpc_helpers + +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +try: + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + ClientInterceptor = Union[ # type: ignore[misc,assignment] + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, + ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -28,7 +41,6 @@ from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore import proto # type: ignore from google.cloud.eventarc_v1.types import channel @@ -146,6 +158,14 @@ def __init__(self, *, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + ClientInterceptor, + Callable[[grpc.Channel], grpc.Channel], + ] + ] + ] = None, ) -> None: """Instantiate the transport. @@ -196,6 +216,9 @@ def __init__(self, *, to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): + Additional interceptors (or callables that apply interceptors) to apply to the + gRPC channel. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -273,6 +296,13 @@ def __init__(self, *, ], ) + apply_interceptors = getattr( + grpc_helpers, + "apply_channel_interceptors", + lambda channel, interceptors: channel, + ) + self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py index 3720a1a84418..d1feb6c06e6b 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py @@ -781,6 +781,94 @@ def test_eventarc_client_client_options_from_dict(): ) +def test_eventarc_client_otel_channel_injection_enabled(): + mock_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_interceptor + with ( + mock.patch( + "google.cloud.eventarc_v1.services.eventarc.client._observability", + mock_obs, + ), + mock.patch.object( + transports.EventarcGrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = EventarcClient(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert called_kwargs.get("interceptors") == [mock_interceptor] + + +def test_eventarc_client_otel_channel_injection_disabled(): + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = None + with ( + mock.patch( + "google.cloud.eventarc_v1.services.eventarc.client._observability", + mock_obs, + ), + mock.patch.object( + transports.EventarcGrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = EventarcClient(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert not called_kwargs.get("interceptors", []) + + +def test_eventarc_grpc_transport_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_channel = mock.Mock() + + with ( + mock.patch.object( + transports.EventarcGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_channel + + +def test_eventarc_grpc_transport_custom_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_custom_channel = mock.Mock(spec=grpc.Channel) + + with mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_custom_channel, + create=True, + ) as mock_apply_interceptors: + transport = transports.EventarcGrpcTransport( + channel=mock_custom_channel, + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_custom_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_custom_channel + + @pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ (EventarcClient, transports.EventarcGrpcTransport, "grpc", grpc_helpers), (EventarcAsyncClient, transports.EventarcGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py index 2ec9186dedc1..4dc15021b0f6 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py @@ -47,6 +47,13 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: _observability was added in google-api-core 2.35.0; guard for older versions +try: + from google.api_core import _observability # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + _observability = None # type: ignore[assignment] + _LOGGER = std_logging.getLogger(__name__) from google.cloud.logging_v2.services.config_service_v2 import pagers @@ -538,18 +545,35 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., ConfigServiceV2Transport], transport) ) + # When OpenTelemetry tracing is enabled, obtain the channel interceptor + # and pass it to the transport. + interceptors = [] + if ( + transport_init is ConfigServiceV2GrpcTransport + and _observability is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None + ): + interceptors.append(otel_interceptor) + # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) + transport_kwargs = { + "credentials": credentials, + "credentials_file": self._client_options.credentials_file, + "host": self._api_endpoint, + "scopes": self._client_options.scopes, + "client_cert_source_for_mtls": self._client_cert_source, + "quota_project_id": self._client_options.quota_project_id, + "client_info": client_info, + "always_use_jwt_access": True, + "api_audience": self._client_options.api_audience, + **({"interceptors": interceptors} if interceptors else {}), + } + self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index d8122989787f..0bd5df37a0d4 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -19,7 +19,20 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import grpc # type: ignore from google.api_core import grpc_helpers + +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +try: + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + ClientInterceptor = Union[ # type: ignore[misc,assignment] + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, + ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -28,7 +41,6 @@ from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore import proto # type: ignore from google.cloud.logging_v2.types import logging_config @@ -132,6 +144,14 @@ def __init__(self, *, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + ClientInterceptor, + Callable[[grpc.Channel], grpc.Channel], + ] + ] + ] = None, ) -> None: """Instantiate the transport. @@ -182,6 +202,9 @@ def __init__(self, *, to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): + Additional interceptors (or callables that apply interceptors) to apply to the + gRPC channel. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -259,6 +282,13 @@ def __init__(self, *, ], ) + apply_interceptors = getattr( + grpc_helpers, + "apply_channel_interceptors", + lambda channel, interceptors: channel, + ) + self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py index dfaf6928a16d..a37a1d051862 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -47,6 +47,13 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: _observability was added in google-api-core 2.35.0; guard for older versions +try: + from google.api_core import _observability # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + _observability = None # type: ignore[assignment] + _LOGGER = std_logging.getLogger(__name__) from google.cloud.logging_v2.services.logging_service_v2 import pagers @@ -469,18 +476,35 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., LoggingServiceV2Transport], transport) ) + # When OpenTelemetry tracing is enabled, obtain the channel interceptor + # and pass it to the transport. + interceptors = [] + if ( + transport_init is LoggingServiceV2GrpcTransport + and _observability is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None + ): + interceptors.append(otel_interceptor) + # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) + transport_kwargs = { + "credentials": credentials, + "credentials_file": self._client_options.credentials_file, + "host": self._api_endpoint, + "scopes": self._client_options.scopes, + "client_cert_source_for_mtls": self._client_cert_source, + "quota_project_id": self._client_options.quota_project_id, + "client_info": client_info, + "always_use_jwt_access": True, + "api_audience": self._client_options.api_audience, + **({"interceptors": interceptors} if interceptors else {}), + } + self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index eeb3a8564ee0..2f37739ca465 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -19,7 +19,20 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import grpc # type: ignore from google.api_core import grpc_helpers + +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +try: + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + ClientInterceptor = Union[ # type: ignore[misc,assignment] + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, + ] from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -27,7 +40,6 @@ from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore import proto # type: ignore from google.cloud.logging_v2.types import logging @@ -131,6 +143,14 @@ def __init__(self, *, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + ClientInterceptor, + Callable[[grpc.Channel], grpc.Channel], + ] + ] + ] = None, ) -> None: """Instantiate the transport. @@ -181,6 +201,9 @@ def __init__(self, *, to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): + Additional interceptors (or callables that apply interceptors) to apply to the + gRPC channel. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -257,6 +280,13 @@ def __init__(self, *, ], ) + apply_interceptors = getattr( + grpc_helpers, + "apply_channel_interceptors", + lambda channel, interceptors: channel, + ) + self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py index 7319be93a38c..81e991c620d8 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -47,6 +47,13 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: _observability was added in google-api-core 2.35.0; guard for older versions +try: + from google.api_core import _observability # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + _observability = None # type: ignore[assignment] + _LOGGER = std_logging.getLogger(__name__) from google.cloud.logging_v2.services.metrics_service_v2 import pagers @@ -470,18 +477,35 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., MetricsServiceV2Transport], transport) ) + # When OpenTelemetry tracing is enabled, obtain the channel interceptor + # and pass it to the transport. + interceptors = [] + if ( + transport_init is MetricsServiceV2GrpcTransport + and _observability is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None + ): + interceptors.append(otel_interceptor) + # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) + transport_kwargs = { + "credentials": credentials, + "credentials_file": self._client_options.credentials_file, + "host": self._api_endpoint, + "scopes": self._client_options.scopes, + "client_cert_source_for_mtls": self._client_cert_source, + "quota_project_id": self._client_options.quota_project_id, + "client_info": client_info, + "always_use_jwt_access": True, + "api_audience": self._client_options.api_audience, + **({"interceptors": interceptors} if interceptors else {}), + } + self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index 2b6003f77476..2a27a9753aa9 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -19,7 +19,20 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import grpc # type: ignore from google.api_core import grpc_helpers + +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +try: + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + ClientInterceptor = Union[ # type: ignore[misc,assignment] + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, + ] from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -27,7 +40,6 @@ from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore import proto # type: ignore from google.cloud.logging_v2.types import logging_metrics @@ -131,6 +143,14 @@ def __init__(self, *, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + ClientInterceptor, + Callable[[grpc.Channel], grpc.Channel], + ] + ] + ] = None, ) -> None: """Instantiate the transport. @@ -181,6 +201,9 @@ def __init__(self, *, to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): + Additional interceptors (or callables that apply interceptors) to apply to the + gRPC channel. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -257,6 +280,13 @@ def __init__(self, *, ], ) + apply_interceptors = getattr( + grpc_helpers, + "apply_channel_interceptors", + lambda channel, interceptors: channel, + ) + self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py index 638aac7a87f8..94a39fe4f05c 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -736,6 +736,94 @@ def test_config_service_v2_client_client_options_from_dict(): ) +def test_config_service_v2_client_otel_channel_injection_enabled(): + mock_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_interceptor + with ( + mock.patch( + "google.cloud.logging_v2.services.config_service_v2.client._observability", + mock_obs, + ), + mock.patch.object( + transports.ConfigServiceV2GrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = ConfigServiceV2Client(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert called_kwargs.get("interceptors") == [mock_interceptor] + + +def test_config_service_v2_client_otel_channel_injection_disabled(): + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = None + with ( + mock.patch( + "google.cloud.logging_v2.services.config_service_v2.client._observability", + mock_obs, + ), + mock.patch.object( + transports.ConfigServiceV2GrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = ConfigServiceV2Client(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert not called_kwargs.get("interceptors", []) + + +def test_config_service_v2_grpc_transport_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_channel = mock.Mock() + + with ( + mock.patch.object( + transports.ConfigServiceV2GrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + transport = transports.ConfigServiceV2GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_channel + + +def test_config_service_v2_grpc_transport_custom_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_custom_channel = mock.Mock(spec=grpc.Channel) + + with mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_custom_channel, + create=True, + ) as mock_apply_interceptors: + transport = transports.ConfigServiceV2GrpcTransport( + channel=mock_custom_channel, + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_custom_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_custom_channel + + @pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ (ConfigServiceV2Client, transports.ConfigServiceV2GrpcTransport, "grpc", grpc_helpers), (ConfigServiceV2AsyncClient, transports.ConfigServiceV2GrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py index e1a950c64f4c..ec398711b928 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -737,6 +737,94 @@ def test_logging_service_v2_client_client_options_from_dict(): ) +def test_logging_service_v2_client_otel_channel_injection_enabled(): + mock_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_interceptor + with ( + mock.patch( + "google.cloud.logging_v2.services.logging_service_v2.client._observability", + mock_obs, + ), + mock.patch.object( + transports.LoggingServiceV2GrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = LoggingServiceV2Client(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert called_kwargs.get("interceptors") == [mock_interceptor] + + +def test_logging_service_v2_client_otel_channel_injection_disabled(): + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = None + with ( + mock.patch( + "google.cloud.logging_v2.services.logging_service_v2.client._observability", + mock_obs, + ), + mock.patch.object( + transports.LoggingServiceV2GrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = LoggingServiceV2Client(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert not called_kwargs.get("interceptors", []) + + +def test_logging_service_v2_grpc_transport_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_channel = mock.Mock() + + with ( + mock.patch.object( + transports.LoggingServiceV2GrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + transport = transports.LoggingServiceV2GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_channel + + +def test_logging_service_v2_grpc_transport_custom_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_custom_channel = mock.Mock(spec=grpc.Channel) + + with mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_custom_channel, + create=True, + ) as mock_apply_interceptors: + transport = transports.LoggingServiceV2GrpcTransport( + channel=mock_custom_channel, + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_custom_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_custom_channel + + @pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ (LoggingServiceV2Client, transports.LoggingServiceV2GrpcTransport, "grpc", grpc_helpers), (LoggingServiceV2AsyncClient, transports.LoggingServiceV2GrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index e2db5c8a9a2a..bc55c44d2a43 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -735,6 +735,94 @@ def test_metrics_service_v2_client_client_options_from_dict(): ) +def test_metrics_service_v2_client_otel_channel_injection_enabled(): + mock_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_interceptor + with ( + mock.patch( + "google.cloud.logging_v2.services.metrics_service_v2.client._observability", + mock_obs, + ), + mock.patch.object( + transports.MetricsServiceV2GrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = MetricsServiceV2Client(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert called_kwargs.get("interceptors") == [mock_interceptor] + + +def test_metrics_service_v2_client_otel_channel_injection_disabled(): + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = None + with ( + mock.patch( + "google.cloud.logging_v2.services.metrics_service_v2.client._observability", + mock_obs, + ), + mock.patch.object( + transports.MetricsServiceV2GrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = MetricsServiceV2Client(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert not called_kwargs.get("interceptors", []) + + +def test_metrics_service_v2_grpc_transport_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_channel = mock.Mock() + + with ( + mock.patch.object( + transports.MetricsServiceV2GrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + transport = transports.MetricsServiceV2GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_channel + + +def test_metrics_service_v2_grpc_transport_custom_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_custom_channel = mock.Mock(spec=grpc.Channel) + + with mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_custom_channel, + create=True, + ) as mock_apply_interceptors: + transport = transports.MetricsServiceV2GrpcTransport( + channel=mock_custom_channel, + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_custom_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_custom_channel + + @pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ (MetricsServiceV2Client, transports.MetricsServiceV2GrpcTransport, "grpc", grpc_helpers), (MetricsServiceV2AsyncClient, transports.MetricsServiceV2GrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py index e136bf06d85d..c06e45ec5def 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py @@ -47,6 +47,13 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: _observability was added in google-api-core 2.35.0; guard for older versions +try: + from google.api_core import _observability # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + _observability = None # type: ignore[assignment] + _LOGGER = std_logging.getLogger(__name__) from google.cloud.logging_v2.services.config_service_v2 import pagers @@ -538,18 +545,35 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., ConfigServiceV2Transport], transport) ) + # When OpenTelemetry tracing is enabled, obtain the channel interceptor + # and pass it to the transport. + interceptors = [] + if ( + transport_init is ConfigServiceV2GrpcTransport + and _observability is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None + ): + interceptors.append(otel_interceptor) + # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) + transport_kwargs = { + "credentials": credentials, + "credentials_file": self._client_options.credentials_file, + "host": self._api_endpoint, + "scopes": self._client_options.scopes, + "client_cert_source_for_mtls": self._client_cert_source, + "quota_project_id": self._client_options.quota_project_id, + "client_info": client_info, + "always_use_jwt_access": True, + "api_audience": self._client_options.api_audience, + **({"interceptors": interceptors} if interceptors else {}), + } + self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index d8122989787f..0bd5df37a0d4 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -19,7 +19,20 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import grpc # type: ignore from google.api_core import grpc_helpers + +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +try: + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + ClientInterceptor = Union[ # type: ignore[misc,assignment] + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, + ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -28,7 +41,6 @@ from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore import proto # type: ignore from google.cloud.logging_v2.types import logging_config @@ -132,6 +144,14 @@ def __init__(self, *, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + ClientInterceptor, + Callable[[grpc.Channel], grpc.Channel], + ] + ] + ] = None, ) -> None: """Instantiate the transport. @@ -182,6 +202,9 @@ def __init__(self, *, to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): + Additional interceptors (or callables that apply interceptors) to apply to the + gRPC channel. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -259,6 +282,13 @@ def __init__(self, *, ], ) + apply_interceptors = getattr( + grpc_helpers, + "apply_channel_interceptors", + lambda channel, interceptors: channel, + ) + self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py index dfaf6928a16d..a37a1d051862 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -47,6 +47,13 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: _observability was added in google-api-core 2.35.0; guard for older versions +try: + from google.api_core import _observability # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + _observability = None # type: ignore[assignment] + _LOGGER = std_logging.getLogger(__name__) from google.cloud.logging_v2.services.logging_service_v2 import pagers @@ -469,18 +476,35 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., LoggingServiceV2Transport], transport) ) + # When OpenTelemetry tracing is enabled, obtain the channel interceptor + # and pass it to the transport. + interceptors = [] + if ( + transport_init is LoggingServiceV2GrpcTransport + and _observability is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None + ): + interceptors.append(otel_interceptor) + # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) + transport_kwargs = { + "credentials": credentials, + "credentials_file": self._client_options.credentials_file, + "host": self._api_endpoint, + "scopes": self._client_options.scopes, + "client_cert_source_for_mtls": self._client_cert_source, + "quota_project_id": self._client_options.quota_project_id, + "client_info": client_info, + "always_use_jwt_access": True, + "api_audience": self._client_options.api_audience, + **({"interceptors": interceptors} if interceptors else {}), + } + self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index eeb3a8564ee0..2f37739ca465 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -19,7 +19,20 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import grpc # type: ignore from google.api_core import grpc_helpers + +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +try: + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + ClientInterceptor = Union[ # type: ignore[misc,assignment] + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, + ] from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -27,7 +40,6 @@ from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore import proto # type: ignore from google.cloud.logging_v2.types import logging @@ -131,6 +143,14 @@ def __init__(self, *, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + ClientInterceptor, + Callable[[grpc.Channel], grpc.Channel], + ] + ] + ] = None, ) -> None: """Instantiate the transport. @@ -181,6 +201,9 @@ def __init__(self, *, to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): + Additional interceptors (or callables that apply interceptors) to apply to the + gRPC channel. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -257,6 +280,13 @@ def __init__(self, *, ], ) + apply_interceptors = getattr( + grpc_helpers, + "apply_channel_interceptors", + lambda channel, interceptors: channel, + ) + self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py index 46949c293cd9..4d9582f65bf4 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -47,6 +47,13 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: _observability was added in google-api-core 2.35.0; guard for older versions +try: + from google.api_core import _observability # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + _observability = None # type: ignore[assignment] + _LOGGER = std_logging.getLogger(__name__) from google.cloud.logging_v2.services.metrics_service_v2 import pagers @@ -470,18 +477,35 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., MetricsServiceV2Transport], transport) ) + # When OpenTelemetry tracing is enabled, obtain the channel interceptor + # and pass it to the transport. + interceptors = [] + if ( + transport_init is MetricsServiceV2GrpcTransport + and _observability is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None + ): + interceptors.append(otel_interceptor) + # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) + transport_kwargs = { + "credentials": credentials, + "credentials_file": self._client_options.credentials_file, + "host": self._api_endpoint, + "scopes": self._client_options.scopes, + "client_cert_source_for_mtls": self._client_cert_source, + "quota_project_id": self._client_options.quota_project_id, + "client_info": client_info, + "always_use_jwt_access": True, + "api_audience": self._client_options.api_audience, + **({"interceptors": interceptors} if interceptors else {}), + } + self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index 2b6003f77476..2a27a9753aa9 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -19,7 +19,20 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import grpc # type: ignore from google.api_core import grpc_helpers + +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +try: + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + ClientInterceptor = Union[ # type: ignore[misc,assignment] + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, + ] from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -27,7 +40,6 @@ from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore import proto # type: ignore from google.cloud.logging_v2.types import logging_metrics @@ -131,6 +143,14 @@ def __init__(self, *, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + ClientInterceptor, + Callable[[grpc.Channel], grpc.Channel], + ] + ] + ] = None, ) -> None: """Instantiate the transport. @@ -181,6 +201,9 @@ def __init__(self, *, to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): + Additional interceptors (or callables that apply interceptors) to apply to the + gRPC channel. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -257,6 +280,13 @@ def __init__(self, *, ], ) + apply_interceptors = getattr( + grpc_helpers, + "apply_channel_interceptors", + lambda channel, interceptors: channel, + ) + self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py index c63237e51f6c..e6de5df4ceaf 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -736,6 +736,94 @@ def test_base_config_service_v2_client_client_options_from_dict(): ) +def test_base_config_service_v2_client_otel_channel_injection_enabled(): + mock_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_interceptor + with ( + mock.patch( + "google.cloud.logging_v2.services.config_service_v2.client._observability", + mock_obs, + ), + mock.patch.object( + transports.ConfigServiceV2GrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = BaseConfigServiceV2Client(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert called_kwargs.get("interceptors") == [mock_interceptor] + + +def test_base_config_service_v2_client_otel_channel_injection_disabled(): + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = None + with ( + mock.patch( + "google.cloud.logging_v2.services.config_service_v2.client._observability", + mock_obs, + ), + mock.patch.object( + transports.ConfigServiceV2GrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = BaseConfigServiceV2Client(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert not called_kwargs.get("interceptors", []) + + +def test_config_service_v2_grpc_transport_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_channel = mock.Mock() + + with ( + mock.patch.object( + transports.ConfigServiceV2GrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + transport = transports.ConfigServiceV2GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_channel + + +def test_config_service_v2_grpc_transport_custom_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_custom_channel = mock.Mock(spec=grpc.Channel) + + with mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_custom_channel, + create=True, + ) as mock_apply_interceptors: + transport = transports.ConfigServiceV2GrpcTransport( + channel=mock_custom_channel, + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_custom_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_custom_channel + + @pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ (BaseConfigServiceV2Client, transports.ConfigServiceV2GrpcTransport, "grpc", grpc_helpers), (BaseConfigServiceV2AsyncClient, transports.ConfigServiceV2GrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py index e1a950c64f4c..ec398711b928 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -737,6 +737,94 @@ def test_logging_service_v2_client_client_options_from_dict(): ) +def test_logging_service_v2_client_otel_channel_injection_enabled(): + mock_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_interceptor + with ( + mock.patch( + "google.cloud.logging_v2.services.logging_service_v2.client._observability", + mock_obs, + ), + mock.patch.object( + transports.LoggingServiceV2GrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = LoggingServiceV2Client(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert called_kwargs.get("interceptors") == [mock_interceptor] + + +def test_logging_service_v2_client_otel_channel_injection_disabled(): + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = None + with ( + mock.patch( + "google.cloud.logging_v2.services.logging_service_v2.client._observability", + mock_obs, + ), + mock.patch.object( + transports.LoggingServiceV2GrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = LoggingServiceV2Client(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert not called_kwargs.get("interceptors", []) + + +def test_logging_service_v2_grpc_transport_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_channel = mock.Mock() + + with ( + mock.patch.object( + transports.LoggingServiceV2GrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + transport = transports.LoggingServiceV2GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_channel + + +def test_logging_service_v2_grpc_transport_custom_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_custom_channel = mock.Mock(spec=grpc.Channel) + + with mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_custom_channel, + create=True, + ) as mock_apply_interceptors: + transport = transports.LoggingServiceV2GrpcTransport( + channel=mock_custom_channel, + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_custom_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_custom_channel + + @pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ (LoggingServiceV2Client, transports.LoggingServiceV2GrpcTransport, "grpc", grpc_helpers), (LoggingServiceV2AsyncClient, transports.LoggingServiceV2GrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index 5cb0ed20e2b1..59ceebba8a28 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -735,6 +735,94 @@ def test_base_metrics_service_v2_client_client_options_from_dict(): ) +def test_base_metrics_service_v2_client_otel_channel_injection_enabled(): + mock_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_interceptor + with ( + mock.patch( + "google.cloud.logging_v2.services.metrics_service_v2.client._observability", + mock_obs, + ), + mock.patch.object( + transports.MetricsServiceV2GrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = BaseMetricsServiceV2Client(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert called_kwargs.get("interceptors") == [mock_interceptor] + + +def test_base_metrics_service_v2_client_otel_channel_injection_disabled(): + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = None + with ( + mock.patch( + "google.cloud.logging_v2.services.metrics_service_v2.client._observability", + mock_obs, + ), + mock.patch.object( + transports.MetricsServiceV2GrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = BaseMetricsServiceV2Client(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert not called_kwargs.get("interceptors", []) + + +def test_metrics_service_v2_grpc_transport_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_channel = mock.Mock() + + with ( + mock.patch.object( + transports.MetricsServiceV2GrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + transport = transports.MetricsServiceV2GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_channel + + +def test_metrics_service_v2_grpc_transport_custom_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_custom_channel = mock.Mock(spec=grpc.Channel) + + with mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_custom_channel, + create=True, + ) as mock_apply_interceptors: + transport = transports.MetricsServiceV2GrpcTransport( + channel=mock_custom_channel, + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_custom_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_custom_channel + + @pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ (BaseMetricsServiceV2Client, transports.MetricsServiceV2GrpcTransport, "grpc", grpc_helpers), (BaseMetricsServiceV2AsyncClient, transports.MetricsServiceV2GrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py index 7b2e7759cd73..54ec658e93aa 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -47,6 +47,13 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: _observability was added in google-api-core 2.35.0; guard for older versions +try: + from google.api_core import _observability # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + _observability = None # type: ignore[assignment] + _LOGGER = std_logging.getLogger(__name__) from google.cloud.location import locations_pb2 # type: ignore @@ -532,18 +539,35 @@ def __init__(self, *, if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): credentials = google.auth._default.get_api_key_credentials(api_key_value) + # When OpenTelemetry tracing is enabled, obtain the channel interceptor + # and pass it to the transport. + interceptors = [] + if ( + transport_init is CloudRedisGrpcTransport + and _observability is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None + ): + interceptors.append(otel_interceptor) + # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) + transport_kwargs = { + "credentials": credentials, + "credentials_file": self._client_options.credentials_file, + "host": self._api_endpoint, + "scopes": self._client_options.scopes, + "client_cert_source_for_mtls": self._client_cert_source, + "quota_project_id": self._client_options.quota_project_id, + "client_info": client_info, + "always_use_jwt_access": True, + "api_audience": self._client_options.api_audience, + **({"interceptors": interceptors} if interceptors else {}), + } + self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index addfbf37e166..b2a32b47bb95 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -19,7 +19,20 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import grpc # type: ignore from google.api_core import grpc_helpers + +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +try: + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + ClientInterceptor = Union[ # type: ignore[misc,assignment] + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, + ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -28,7 +41,6 @@ from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore import proto # type: ignore from google.cloud.location import locations_pb2 # type: ignore @@ -152,6 +164,14 @@ def __init__(self, *, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + ClientInterceptor, + Callable[[grpc.Channel], grpc.Channel], + ] + ] + ] = None, ) -> None: """Instantiate the transport. @@ -202,6 +222,9 @@ def __init__(self, *, to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): + Additional interceptors (or callables that apply interceptors) to apply to the + gRPC channel. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -279,6 +302,13 @@ def __init__(self, *, ], ) + apply_interceptors = getattr( + grpc_helpers, + "apply_channel_interceptors", + lambda channel, interceptors: channel, + ) + self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py index 6bd8b8b5009c..632bd64909f4 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -768,6 +768,94 @@ def test_cloud_redis_client_client_options_from_dict(): ) +def test_cloud_redis_client_otel_channel_injection_enabled(): + mock_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_interceptor + with ( + mock.patch( + "google.cloud.redis_v1.services.cloud_redis.client._observability", + mock_obs, + ), + mock.patch.object( + transports.CloudRedisGrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = CloudRedisClient(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert called_kwargs.get("interceptors") == [mock_interceptor] + + +def test_cloud_redis_client_otel_channel_injection_disabled(): + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = None + with ( + mock.patch( + "google.cloud.redis_v1.services.cloud_redis.client._observability", + mock_obs, + ), + mock.patch.object( + transports.CloudRedisGrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = CloudRedisClient(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert not called_kwargs.get("interceptors", []) + + +def test_cloud_redis_grpc_transport_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_channel = mock.Mock() + + with ( + mock.patch.object( + transports.CloudRedisGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_channel + + +def test_cloud_redis_grpc_transport_custom_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_custom_channel = mock.Mock(spec=grpc.Channel) + + with mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_custom_channel, + create=True, + ) as mock_apply_interceptors: + transport = transports.CloudRedisGrpcTransport( + channel=mock_custom_channel, + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_custom_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_custom_channel + + @pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ (CloudRedisClient, transports.CloudRedisGrpcTransport, "grpc", grpc_helpers), (CloudRedisAsyncClient, transports.CloudRedisGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py index 771b0baa9989..a9817bce76fb 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py @@ -47,6 +47,13 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: _observability was added in google-api-core 2.35.0; guard for older versions +try: + from google.api_core import _observability # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + _observability = None # type: ignore[assignment] + _LOGGER = std_logging.getLogger(__name__) from google.cloud.location import locations_pb2 # type: ignore @@ -532,18 +539,35 @@ def __init__(self, *, if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): credentials = google.auth._default.get_api_key_credentials(api_key_value) + # When OpenTelemetry tracing is enabled, obtain the channel interceptor + # and pass it to the transport. + interceptors = [] + if ( + transport_init is CloudRedisGrpcTransport + and _observability is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None + ): + interceptors.append(otel_interceptor) + # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) + transport_kwargs = { + "credentials": credentials, + "credentials_file": self._client_options.credentials_file, + "host": self._api_endpoint, + "scopes": self._client_options.scopes, + "client_cert_source_for_mtls": self._client_cert_source, + "quota_project_id": self._client_options.quota_project_id, + "client_info": client_info, + "always_use_jwt_access": True, + "api_audience": self._client_options.api_audience, + **({"interceptors": interceptors} if interceptors else {}), + } + self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index cae682b3d0ae..c05af1e2e635 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -19,7 +19,20 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import grpc # type: ignore from google.api_core import grpc_helpers + +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +try: + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + ClientInterceptor = Union[ # type: ignore[misc,assignment] + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, + ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -28,7 +41,6 @@ from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore import proto # type: ignore from google.cloud.location import locations_pb2 # type: ignore @@ -152,6 +164,14 @@ def __init__(self, *, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + ClientInterceptor, + Callable[[grpc.Channel], grpc.Channel], + ] + ] + ] = None, ) -> None: """Instantiate the transport. @@ -202,6 +222,9 @@ def __init__(self, *, to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): + Additional interceptors (or callables that apply interceptors) to apply to the + gRPC channel. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -279,6 +302,13 @@ def __init__(self, *, ], ) + apply_interceptors = getattr( + grpc_helpers, + "apply_channel_interceptors", + lambda channel, interceptors: channel, + ) + self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py index 44a69d3d2277..9094b0af41d2 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -768,6 +768,94 @@ def test_cloud_redis_client_client_options_from_dict(): ) +def test_cloud_redis_client_otel_channel_injection_enabled(): + mock_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_interceptor + with ( + mock.patch( + "google.cloud.redis_v1.services.cloud_redis.client._observability", + mock_obs, + ), + mock.patch.object( + transports.CloudRedisGrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = CloudRedisClient(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert called_kwargs.get("interceptors") == [mock_interceptor] + + +def test_cloud_redis_client_otel_channel_injection_disabled(): + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = None + with ( + mock.patch( + "google.cloud.redis_v1.services.cloud_redis.client._observability", + mock_obs, + ), + mock.patch.object( + transports.CloudRedisGrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = CloudRedisClient(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert not called_kwargs.get("interceptors", []) + + +def test_cloud_redis_grpc_transport_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_channel = mock.Mock() + + with ( + mock.patch.object( + transports.CloudRedisGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_channel + + +def test_cloud_redis_grpc_transport_custom_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_custom_channel = mock.Mock(spec=grpc.Channel) + + with mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_custom_channel, + create=True, + ) as mock_apply_interceptors: + transport = transports.CloudRedisGrpcTransport( + channel=mock_custom_channel, + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_custom_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_custom_channel + + @pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ (CloudRedisClient, transports.CloudRedisGrpcTransport, "grpc", grpc_helpers), (CloudRedisAsyncClient, transports.CloudRedisGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py index ee8cac5e7107..1ef4640b848d 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py @@ -49,6 +49,13 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: _observability was added in google-api-core 2.35.0; guard for older versions +try: + from google.api_core import _observability # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + _observability = None # type: ignore[assignment] + _LOGGER = std_logging.getLogger(__name__) from google.cloud.location import locations_pb2 # type: ignore @@ -506,18 +513,35 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., StorageBatchOperationsTransport], transport) ) + # When OpenTelemetry tracing is enabled, obtain the channel interceptor + # and pass it to the transport. + interceptors = [] + if ( + transport_init is StorageBatchOperationsGrpcTransport + and _observability is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None + ): + interceptors.append(otel_interceptor) + # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) + transport_kwargs = { + "credentials": credentials, + "credentials_file": self._client_options.credentials_file, + "host": self._api_endpoint, + "scopes": self._client_options.scopes, + "client_cert_source_for_mtls": self._client_cert_source, + "quota_project_id": self._client_options.quota_project_id, + "client_info": client_info, + "always_use_jwt_access": True, + "api_audience": self._client_options.api_audience, + **({"interceptors": interceptors} if interceptors else {}), + } + self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py index 1f997d49aabd..033f96587427 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py @@ -19,7 +19,20 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import grpc # type: ignore from google.api_core import grpc_helpers + +# Optional: OpenTelemetry tracing capabilities for grpc channel injection +# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +try: + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +except ImportError: # pragma: NO COVER + ClientInterceptor = Union[ # type: ignore[misc,assignment] + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, + ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -28,7 +41,6 @@ from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore import proto # type: ignore from google.cloud.location import locations_pb2 # type: ignore @@ -138,6 +150,14 @@ def __init__(self, *, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + ClientInterceptor, + Callable[[grpc.Channel], grpc.Channel], + ] + ] + ] = None, ) -> None: """Instantiate the transport. @@ -188,6 +208,9 @@ def __init__(self, *, to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): + Additional interceptors (or callables that apply interceptors) to apply to the + gRPC channel. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -265,6 +288,13 @@ def __init__(self, *, ], ) + apply_interceptors = getattr( + grpc_helpers, + "apply_channel_interceptors", + lambda channel, interceptors: channel, + ) + self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py index 91d1b992fe18..2d51c66c5a73 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py @@ -760,6 +760,94 @@ def test_storage_batch_operations_client_client_options_from_dict(): ) +def test_storage_batch_operations_client_otel_channel_injection_enabled(): + mock_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_interceptor + with ( + mock.patch( + "google.cloud.storagebatchoperations_v1.services.storage_batch_operations.client._observability", + mock_obs, + ), + mock.patch.object( + transports.StorageBatchOperationsGrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = StorageBatchOperationsClient(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert called_kwargs.get("interceptors") == [mock_interceptor] + + +def test_storage_batch_operations_client_otel_channel_injection_disabled(): + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = None + with ( + mock.patch( + "google.cloud.storagebatchoperations_v1.services.storage_batch_operations.client._observability", + mock_obs, + ), + mock.patch.object( + transports.StorageBatchOperationsGrpcTransport, "__init__", return_value=None + ) as patched_transport_init, + ): + client = StorageBatchOperationsClient(transport="grpc") + + mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + called_kwargs = patched_transport_init.call_args.kwargs + assert not called_kwargs.get("interceptors", []) + + +def test_storage_batch_operations_grpc_transport_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_channel = mock.Mock() + + with ( + mock.patch.object( + transports.StorageBatchOperationsGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + transport = transports.StorageBatchOperationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_channel + + +def test_storage_batch_operations_grpc_transport_custom_channel_interceptors(): + mock_interceptor = mock.Mock() + mock_custom_channel = mock.Mock(spec=grpc.Channel) + + with mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_custom_channel, + create=True, + ) as mock_apply_interceptors: + transport = transports.StorageBatchOperationsGrpcTransport( + channel=mock_custom_channel, + interceptors=[mock_interceptor], + ) + + mock_apply_interceptors.assert_called_once_with( + mock_custom_channel, [mock_interceptor] + ) + assert transport.grpc_channel == mock_custom_channel + + @pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ (StorageBatchOperationsClient, transports.StorageBatchOperationsGrpcTransport, "grpc", grpc_helpers), (StorageBatchOperationsAsyncClient, transports.StorageBatchOperationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), From a7dad4fda00da0e6d5ad01ee8fee7dc5c50f7136 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 14 Sep 2026 08:15:19 -0400 Subject: [PATCH 22/43] ci(gapic): add OpenTelemetry test dependencies to showcase nox sessions --- packages/gapic-generator/noxfile.py | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/packages/gapic-generator/noxfile.py b/packages/gapic-generator/noxfile.py index a9724ae3b450..2dc40ae96b05 100644 --- a/packages/gapic-generator/noxfile.py +++ b/packages/gapic-generator/noxfile.py @@ -18,18 +18,18 @@ # PIP_INDEX_URL=https://pypi.org/simple nox from __future__ import absolute_import -from concurrent.futures import ThreadPoolExecutor -from pathlib import Path + import os +import shutil import sys import tempfile import typing -import nox # type: ignore - +from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from os import path -import shutil +from pathlib import Path +import nox # type: ignore nox.options.error_on_missing_interpreters = True @@ -407,6 +407,11 @@ def showcase( # Use pytest-asyncio<1.0.0 while we investigate the recent failure described in # https://github.com/googleapis/gapic-generator-python/issues/2399 session.install("pytest", "pytest-asyncio<1.0.0") + session.install( + "opentelemetry-api", + "opentelemetry-sdk", + "opentelemetry-instrumentation-grpc", + ) test_directory = Path("tests", "system") ignore_file = env.get("IGNORE_FILE") pytest_command = [ @@ -498,7 +503,13 @@ def showcase_pqc( with showcase_library(session, templates=templates, other_opts=other_opts): session.install("pytest", "pytest-asyncio") session.install("--upgrade", "grpcio>=1.83.0", "grpcio-status>=1.83.0") - session.run("py.test", "--quiet", "--tls", *(session.posargs or ["tests/system/test_pqc.py"]), env=env) + session.run( + "py.test", + "--quiet", + "--tls", + *(session.posargs or ["tests/system/test_pqc.py"]), + env=env, + ) def run_showcase_unit_tests(session, fail_under=100, rest_async_io_enabled=False): @@ -508,6 +519,8 @@ def run_showcase_unit_tests(session, fail_under=100, rest_async_io_enabled=False "pytest-cov", "pytest-xdist", "pytest-asyncio", + "opentelemetry-api", + "opentelemetry-sdk", ) # Freeze and print python environment package versions session.run("python", "-m", "pip", "freeze") From 858ff5240a186483f853505e899bec3c1115efa7 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 14 Sep 2026 08:15:26 -0400 Subject: [PATCH 23/43] test(gapic): support client_options and otel interceptor in system test harness --- .../gapic-generator/tests/system/conftest.py | 64 ++++++++++++------- 1 file changed, 42 insertions(+), 22 deletions(-) diff --git a/packages/gapic-generator/tests/system/conftest.py b/packages/gapic-generator/tests/system/conftest.py index 73169dd8a79f..6d331f7a295e 100644 --- a/packages/gapic-generator/tests/system/conftest.py +++ b/packages/gapic-generator/tests/system/conftest.py @@ -13,17 +13,21 @@ # limitations under the License. -import grpc -from unittest import mock import os -import pytest -import pytest_asyncio -from requests.adapters import HTTPAdapter - from typing import Sequence, Tuple +from unittest import mock +import grpc +import pytest +import pytest_asyncio from google.api_core.client_options import ClientOptions # type: ignore from google.showcase_v1beta1.services.echo.transports import EchoRestInterceptor +from requests.adapters import HTTPAdapter + +try: + from google.api_core import _observability +except ImportError: + _observability = None try: from google.auth.aio import credentials as ga_credentials_async @@ -34,20 +38,18 @@ HAS_GOOGLE_AUTH_AIO = False import google.auth from google.auth import credentials as ga_credentials -from google.showcase import EchoClient -from google.showcase import IdentityClient -from google.showcase import MessagingClient +from google.showcase import EchoClient, IdentityClient, MessagingClient if os.environ.get("GAPIC_PYTHON_ASYNC", "true") == "true": - from grpc.experimental import aio import asyncio - from google.showcase import EchoAsyncClient - from google.showcase import IdentityAsyncClient + + from google.showcase import EchoAsyncClient, IdentityAsyncClient + from grpc.experimental import aio try: from google.showcase_v1beta1.services.echo.transports import ( - AsyncEchoRestTransport, AsyncEchoRestInterceptor, + AsyncEchoRestTransport, ) HAS_ASYNC_REST_ECHO_TRANSPORT = True @@ -132,8 +134,8 @@ def callback(): return cert, key -client_options = ClientOptions() -client_options.client_cert_source = callback +default_mtls_client_options = ClientOptions() +default_mtls_client_options.client_cert_source = callback def pytest_addoption(parser): @@ -141,7 +143,9 @@ def pytest_addoption(parser): "--mtls", action="store_true", help="Run system test with mutual TLS channel" ) parser.addoption( - "--tls", action="store_true", help="Run system test with standard one-way TLS channel" + "--tls", + action="store_true", + help="Run system test with standard one-way TLS channel", ) @@ -153,6 +157,7 @@ def construct_client( channel_creator=grpc.insecure_channel, # for grpc,grpc_asyncio only credentials=ga_credentials.AnonymousCredentials(), transport_endpoint="localhost:7469", + client_options=None, ): if use_mtls: with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): @@ -162,7 +167,7 @@ def construct_client( mock_ssl_cred.return_value = ssl_credentials client = client_class( credentials=credentials, - client_options=client_options, + client_options=client_options or default_mtls_client_options, ) mock_ssl_cred.assert_called_once_with( certificate_chain=cert, private_key=key @@ -173,9 +178,15 @@ def construct_client( if transport_name in ["grpc", "grpc_asyncio"]: # TODO(gapic-generator-python/issues/1914): Need to test grpc transports without a channel_creator assert channel_creator + interceptors = [] + if _observability is not None and transport_name == "grpc": + otel_interceptor = _observability.get_otel_interceptor(client_options) + if otel_interceptor is not None: + interceptors.append(otel_interceptor) transport = transport_cls( credentials=credentials, channel=channel_creator(transport_endpoint), + interceptors=interceptors if interceptors else None, ) elif transport_name in ["rest", "rest_asyncio"]: # The custom host explicitly bypasses https. @@ -187,7 +198,7 @@ def construct_client( else: raise RuntimeError(f"Unexpected transport type: {transport_name}") - client = client_class(transport=transport) + client = client_class(transport=transport, client_options=client_options) return client @@ -340,7 +351,9 @@ def _read_response_metadata_stream(self): def intercept_unary_unary(self, continuation, client_call_details, request): self._add_request_metadata(client_call_details) response = continuation(client_call_details, request) - metadata = [(k, str(v)) for k, v in response.initial_metadata()] + [(k, str(v)) for k, v in response.trailing_metadata()] + metadata = [(k, str(v)) for k, v in response.initial_metadata()] + [ + (k, str(v)) for k, v in response.trailing_metadata() + ] self.response_metadata = metadata return response @@ -399,7 +412,9 @@ async def _add_request_metadata(self, client_call_details): async def intercept_unary_unary(self, continuation, client_call_details, request): await self._add_request_metadata(client_call_details) response = await continuation(client_call_details, request) - metadata = [(k, str(v)) for k, v in await response.initial_metadata()] + [(k, str(v)) for k, v in await response.trailing_metadata()] + metadata = [(k, str(v)) for k, v in await response.initial_metadata()] + [ + (k, str(v)) for k, v in await response.trailing_metadata() + ] self.response_metadata = metadata return response @@ -458,9 +473,13 @@ async def intercepted_echo_grpc_async(use_mtls, use_tls): ) host = "localhost:7469" if use_mtls: - channel = grpc.aio.secure_channel(host, ssl_credentials, interceptors=[interceptor]) + channel = grpc.aio.secure_channel( + host, ssl_credentials, interceptors=[interceptor] + ) elif use_tls: - channel = grpc.aio.secure_channel(host, tls_credentials, interceptors=[interceptor]) + channel = grpc.aio.secure_channel( + host, tls_credentials, interceptors=[interceptor] + ) else: channel = grpc.aio.insecure_channel(host, interceptors=[interceptor]) transport = EchoAsyncClient.get_transport_class("grpc_asyncio")( @@ -472,6 +491,7 @@ async def intercepted_echo_grpc_async(use_mtls, use_tls): class HostNameIgnoringAdapter(HTTPAdapter): """Custom HTTPAdapter that disables hostname verification for local self-signed certs.""" + def cert_verify(self, conn, url, verify, cert): super().cert_verify(conn, url, verify, cert) conn.assert_hostname = False From b1c66e4d89af98119af4394b294defbd9ad57b75 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 14 Sep 2026 08:15:31 -0400 Subject: [PATCH 24/43] test(gapic): add showcase system test suite for OpenTelemetry channel tracing --- .../tests/system/test_tracing.py | 210 ++++++++++++++++++ 1 file changed, 210 insertions(+) create mode 100644 packages/gapic-generator/tests/system/test_tracing.py diff --git a/packages/gapic-generator/tests/system/test_tracing.py b/packages/gapic-generator/tests/system/test_tracing.py new file mode 100644 index 000000000000..4857587525f9 --- /dev/null +++ b/packages/gapic-generator/tests/system/test_tracing.py @@ -0,0 +1,210 @@ +# 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 +# +# https://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 + +try: + from opentelemetry import trace + from opentelemetry.sdk.trace import TracerProvider + from opentelemetry.sdk.trace.export import SimpleSpanProcessor + from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( + InMemorySpanExporter, + ) + + HAS_OPENTELEMETRY = True +except ImportError: + HAS_OPENTELEMETRY = False + +if not HAS_OPENTELEMETRY: + pytest.skip("OpenTelemetry is not installed", allow_module_level=True) + +from google import showcase +from google.api_core import exceptions +from google.api_core import retry as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials +from google.rpc import code_pb2 +from google.showcase import EchoClient + +from .conftest import construct_client + + +@pytest.fixture +def span_exporter(): + """Provides an isolated InMemorySpanExporter and TracerProvider for test assertions.""" + exporter = InMemorySpanExporter() + provider = TracerProvider() + processor = SimpleSpanProcessor(exporter) + provider.add_span_processor(processor) + + yield exporter, provider + + exporter.clear() + + +@pytest.fixture +def otel_echo_client(span_exporter, use_mtls): + """Constructs an EchoClient wired with an in-memory TracerProvider.""" + exporter, provider = span_exporter + options = ClientOptions( + tracing_enabled=True, + tracer_provider=provider, + ) + client = construct_client( + EchoClient, + use_mtls, + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + return client, exporter + + +def test_sync_unary_tracing(otel_echo_client): + """Verifies that a synchronous unary RPC generates a trace span with expected attributes.""" + client, exporter = otel_echo_client + + response = client.echo(showcase.EchoRequest(content="hello world")) + assert response.content == "hello world" + + spans = exporter.get_finished_spans() + assert len(spans) == 1 + + span = spans[0] + assert span.name == "google.showcase.v1beta1.Echo/Echo" + assert span.attributes.get("rpc.system.name") == "grpc" + assert span.attributes.get("rpc.method") == "google.showcase.v1beta1.Echo/Echo" + assert span.attributes.get("rpc.response.status_code") == "OK" + assert span.attributes.get("url.domain") == "googleapis.com" + assert span.kind == trace.SpanKind.CLIENT + + +def test_unary_retries_tracing(span_exporter, use_mtls): + """Verifies that each attempt of a retried RPC generates a separate span.""" + exporter, provider = span_exporter + options = ClientOptions( + tracing_enabled=True, + tracer_provider=provider, + ) + client = construct_client( + EchoClient, + use_mtls, + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Configure a custom retry policy with 2 attempts on DeadlineExceeded + custom_retry = retries.Retry( + predicate=retries.if_exception_type(exceptions.DeadlineExceeded), + initial=0.05, + maximum=0.1, + multiplier=1.0, + deadline=0.3, + ) + + with pytest.raises((exceptions.DeadlineExceeded, exceptions.RetryError)): + client.echo( + { + "error": { + "code": code_pb2.Code.Value("DEADLINE_EXCEEDED"), + "message": "Simulated deadline exceeded error for retry testing.", + }, + }, + retry=custom_retry, + ) + + spans = exporter.get_finished_spans() + # At least two attempts should have been made and recorded + assert len(spans) >= 2 + for span in spans: + assert span.name == "google.showcase.v1beta1.Echo/Echo" + assert span.attributes.get("rpc.system.name") == "grpc" + assert span.attributes.get("rpc.method") == "google.showcase.v1beta1.Echo/Echo" + # Non-successful attempt should not have rpc.response.status_code == "OK" + assert span.attributes.get("rpc.response.status_code") != "OK" + + +def test_tracing_disabled_default(use_mtls): + """Verifies that default client options emit zero spans (zero overhead guarantee).""" + exporter = InMemorySpanExporter() + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + + client = construct_client( + EchoClient, + use_mtls, + credentials=ga_credentials.AnonymousCredentials(), + ) + + response = client.echo(showcase.EchoRequest(content="no tracing")) + assert response.content == "no tracing" + + # Zero spans must be emitted when tracing is disabled + assert len(exporter.get_finished_spans()) == 0 + + +def test_custom_tracer_provider(use_mtls): + """Verifies that spans are emitted exclusively to the injected custom TracerProvider.""" + custom_exporter = InMemorySpanExporter() + custom_provider = TracerProvider() + custom_provider.add_span_processor(SimpleSpanProcessor(custom_exporter)) + + other_exporter = InMemorySpanExporter() + other_provider = TracerProvider() + other_provider.add_span_processor(SimpleSpanProcessor(other_exporter)) + + options = ClientOptions( + tracing_enabled=True, + tracer_provider=custom_provider, + ) + client = construct_client( + EchoClient, + use_mtls, + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + + response = client.echo(showcase.EchoRequest(content="isolated trace")) + assert response.content == "isolated trace" + + assert len(custom_exporter.get_finished_spans()) == 1 + assert len(other_exporter.get_finished_spans()) == 0 + + +def test_env_var_opt_in(span_exporter, use_mtls): + """Verifies that setting the environment variable enables tracing without tracing_enabled=True.""" + exporter, provider = span_exporter + + options = ClientOptions( + tracer_provider=provider, + ) + + env_patch = { + "GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED": "true", + } + with mock.patch.dict(os.environ, env_patch): + client = construct_client( + EchoClient, + use_mtls, + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + response = client.echo(showcase.EchoRequest(content="env opt in")) + assert response.content == "env opt in" + + spans = exporter.get_finished_spans() + assert len(spans) == 1 + assert spans[0].name == "google.showcase.v1beta1.Echo/Echo" From b409ba6846dde6b2aca225d36e21b3886df1973a Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 14 Sep 2026 09:22:29 -0400 Subject: [PATCH 25/43] feat(gapic): broaden transport subclass check and harden tracing tests - Broaden transport check in client.py.j2 to allow gRPC transport subclasses. - Align version comments in client.py.j2 and grpc.py.j2 to 2.36.0+. - Synchronize all golden client and transport files with template updates. - Harden zero-overhead and custom tracer provider isolation assertions in test_tracing.py. - Add direct client initialization test to verify template injection end-to-end. --- .../%sub/services/%service/client.py.j2 | 5 +- .../services/%service/transports/grpc.py.j2 | 2 +- .../asset_v1/services/asset_service/client.py | 5 +- .../services/asset_service/transports/grpc.py | 2 +- .../services/iam_credentials/client.py | 5 +- .../iam_credentials/transports/grpc.py | 2 +- .../eventarc_v1/services/eventarc/client.py | 5 +- .../services/eventarc/transports/grpc.py | 2 +- .../services/config_service_v2/client.py | 5 +- .../config_service_v2/transports/grpc.py | 2 +- .../services/logging_service_v2/client.py | 5 +- .../logging_service_v2/transports/grpc.py | 2 +- .../services/metrics_service_v2/client.py | 5 +- .../metrics_service_v2/transports/grpc.py | 2 +- .../services/config_service_v2/client.py | 5 +- .../config_service_v2/transports/grpc.py | 2 +- .../services/logging_service_v2/client.py | 5 +- .../logging_service_v2/transports/grpc.py | 2 +- .../services/metrics_service_v2/client.py | 5 +- .../metrics_service_v2/transports/grpc.py | 2 +- .../redis_v1/services/cloud_redis/client.py | 5 +- .../services/cloud_redis/transports/grpc.py | 2 +- .../redis_v1/services/cloud_redis/client.py | 5 +- .../services/cloud_redis/transports/grpc.py | 2 +- .../storage_batch_operations/client.py | 5 +- .../transports/grpc.py | 2 +- .../tests/system/test_tracing.py | 103 +++++++++++++++--- 27 files changed, 139 insertions(+), 55 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 index 5156805f1e38..157f014508dd 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 @@ -54,7 +54,7 @@ except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.36.0+; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER @@ -543,7 +543,8 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): interceptors = [] {% if 'grpc' in opts.transport %} if ( - transport_init is {{ service.grpc_transport_name }} + isinstance(transport_init, type) + and issubclass(transport_init, {{ service.grpc_transport_name }}) and _observability is not None and ( otel_interceptor := _observability.get_otel_interceptor( diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 index 75b6304c0316..8da1dfcce160 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 @@ -14,7 +14,7 @@ import grpc # type: ignore from google.api_core import grpc_helpers # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions try: from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py index 12e669a8e11c..492935dd8e5a 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py @@ -48,7 +48,7 @@ CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.36.0+; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER @@ -556,7 +556,8 @@ def __init__(self, *, # and pass it to the transport. interceptors = [] if ( - transport_init is AssetServiceGrpcTransport + isinstance(transport_init, type) + and issubclass(transport_init, AssetServiceGrpcTransport) and _observability is not None and ( otel_interceptor := _observability.get_otel_interceptor( diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py index 498ecc1dfa24..1c92f07d98b4 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -23,7 +23,7 @@ from google.api_core import grpc_helpers # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions try: from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index 65d424866a2a..814806e76f0a 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -48,7 +48,7 @@ CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.36.0+; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER @@ -493,7 +493,8 @@ def __init__(self, *, # and pass it to the transport. interceptors = [] if ( - transport_init is IAMCredentialsGrpcTransport + isinstance(transport_init, type) + and issubclass(transport_init, IAMCredentialsGrpcTransport) and _observability is not None and ( otel_interceptor := _observability.get_otel_interceptor( diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py index 7721d3534d56..a1940f375c9c 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py @@ -23,7 +23,7 @@ from google.api_core import grpc_helpers # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions try: from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index 9cf97196a76d..1df357a593f2 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -48,7 +48,7 @@ CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.36.0+; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER @@ -676,7 +676,8 @@ def __init__(self, *, # and pass it to the transport. interceptors = [] if ( - transport_init is EventarcGrpcTransport + isinstance(transport_init, type) + and issubclass(transport_init, EventarcGrpcTransport) and _observability is not None and ( otel_interceptor := _observability.get_otel_interceptor( diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py index 9435b1510b97..503167d1e16b 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py @@ -23,7 +23,7 @@ from google.api_core import grpc_helpers # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions try: from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py index 4dc15021b0f6..de57e35ed2ac 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py @@ -48,7 +48,7 @@ CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.36.0+; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER @@ -549,7 +549,8 @@ def __init__(self, *, # and pass it to the transport. interceptors = [] if ( - transport_init is ConfigServiceV2GrpcTransport + isinstance(transport_init, type) + and issubclass(transport_init, ConfigServiceV2GrpcTransport) and _observability is not None and ( otel_interceptor := _observability.get_otel_interceptor( diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index 0bd5df37a0d4..940e3a761b31 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -23,7 +23,7 @@ from google.api_core import grpc_helpers # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions try: from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py index a37a1d051862..9fefe7597513 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -48,7 +48,7 @@ CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.36.0+; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER @@ -480,7 +480,8 @@ def __init__(self, *, # and pass it to the transport. interceptors = [] if ( - transport_init is LoggingServiceV2GrpcTransport + isinstance(transport_init, type) + and issubclass(transport_init, LoggingServiceV2GrpcTransport) and _observability is not None and ( otel_interceptor := _observability.get_otel_interceptor( diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index 2f37739ca465..b97b20ffe806 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -23,7 +23,7 @@ from google.api_core import grpc_helpers # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions try: from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py index 81e991c620d8..0e683c58063f 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -48,7 +48,7 @@ CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.36.0+; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER @@ -481,7 +481,8 @@ def __init__(self, *, # and pass it to the transport. interceptors = [] if ( - transport_init is MetricsServiceV2GrpcTransport + isinstance(transport_init, type) + and issubclass(transport_init, MetricsServiceV2GrpcTransport) and _observability is not None and ( otel_interceptor := _observability.get_otel_interceptor( diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index 2a27a9753aa9..dab5b52cf0dc 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -23,7 +23,7 @@ from google.api_core import grpc_helpers # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions try: from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py index c06e45ec5def..aefac0da88fb 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py @@ -48,7 +48,7 @@ CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.36.0+; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER @@ -549,7 +549,8 @@ def __init__(self, *, # and pass it to the transport. interceptors = [] if ( - transport_init is ConfigServiceV2GrpcTransport + isinstance(transport_init, type) + and issubclass(transport_init, ConfigServiceV2GrpcTransport) and _observability is not None and ( otel_interceptor := _observability.get_otel_interceptor( diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index 0bd5df37a0d4..940e3a761b31 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -23,7 +23,7 @@ from google.api_core import grpc_helpers # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions try: from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py index a37a1d051862..9fefe7597513 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -48,7 +48,7 @@ CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.36.0+; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER @@ -480,7 +480,8 @@ def __init__(self, *, # and pass it to the transport. interceptors = [] if ( - transport_init is LoggingServiceV2GrpcTransport + isinstance(transport_init, type) + and issubclass(transport_init, LoggingServiceV2GrpcTransport) and _observability is not None and ( otel_interceptor := _observability.get_otel_interceptor( diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index 2f37739ca465..b97b20ffe806 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -23,7 +23,7 @@ from google.api_core import grpc_helpers # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions try: from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py index 4d9582f65bf4..c636aaca7e86 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -48,7 +48,7 @@ CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.36.0+; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER @@ -481,7 +481,8 @@ def __init__(self, *, # and pass it to the transport. interceptors = [] if ( - transport_init is MetricsServiceV2GrpcTransport + isinstance(transport_init, type) + and issubclass(transport_init, MetricsServiceV2GrpcTransport) and _observability is not None and ( otel_interceptor := _observability.get_otel_interceptor( diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index 2a27a9753aa9..dab5b52cf0dc 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -23,7 +23,7 @@ from google.api_core import grpc_helpers # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions try: from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py index 54ec658e93aa..e8f258ff21d3 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -48,7 +48,7 @@ CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.36.0+; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER @@ -543,7 +543,8 @@ def __init__(self, *, # and pass it to the transport. interceptors = [] if ( - transport_init is CloudRedisGrpcTransport + isinstance(transport_init, type) + and issubclass(transport_init, CloudRedisGrpcTransport) and _observability is not None and ( otel_interceptor := _observability.get_otel_interceptor( diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index b2a32b47bb95..becf980c03c1 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -23,7 +23,7 @@ from google.api_core import grpc_helpers # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions try: from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py index a9817bce76fb..828f6d48211e 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py @@ -48,7 +48,7 @@ CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.36.0+; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER @@ -543,7 +543,8 @@ def __init__(self, *, # and pass it to the transport. interceptors = [] if ( - transport_init is CloudRedisGrpcTransport + isinstance(transport_init, type) + and issubclass(transport_init, CloudRedisGrpcTransport) and _observability is not None and ( otel_interceptor := _observability.get_otel_interceptor( diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index c05af1e2e635..0cc07e360d58 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -23,7 +23,7 @@ from google.api_core import grpc_helpers # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions try: from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py index 1ef4640b848d..448ac3f79873 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py @@ -50,7 +50,7 @@ CLIENT_LOGGING_SUPPORTED = False # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: _observability was added in google-api-core 2.35.0; guard for older versions +# Note: _observability was added in google-api-core 2.36.0+; guard for older versions try: from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER @@ -517,7 +517,8 @@ def __init__(self, *, # and pass it to the transport. interceptors = [] if ( - transport_init is StorageBatchOperationsGrpcTransport + isinstance(transport_init, type) + and issubclass(transport_init, StorageBatchOperationsGrpcTransport) and _observability is not None and ( otel_interceptor := _observability.get_otel_interceptor( diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py index 033f96587427..d3555f1bf2a5 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py @@ -23,7 +23,7 @@ from google.api_core import grpc_helpers # Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.25.0+; fallback for older versions +# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions try: from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] except ImportError: # pragma: NO COVER diff --git a/packages/gapic-generator/tests/system/test_tracing.py b/packages/gapic-generator/tests/system/test_tracing.py index 4857587525f9..b187a7ba2015 100644 --- a/packages/gapic-generator/tests/system/test_tracing.py +++ b/packages/gapic-generator/tests/system/test_tracing.py @@ -15,6 +15,7 @@ import os from unittest import mock +import grpc import pytest try: @@ -138,14 +139,30 @@ def test_unary_retries_tracing(span_exporter, use_mtls): def test_tracing_disabled_default(use_mtls): - """Verifies that default client options emit zero spans (zero overhead guarantee).""" + """Verifies that default client options emit zero spans (zero overhead guarantee). + + Ensures that configuring a `TracerProvider` in `ClientOptions` without explicitly + enabling tracing (via `tracing_enabled=True` or the environment variable + `GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED`) records zero spans and incurs + no tracing overhead. + + An active `TracerProvider` with an in-memory exporter is passed to the client. + The test executes an actual unary RPC and asserts that no finished spans are + recorded. + """ exporter = InMemorySpanExporter() provider = TracerProvider() provider.add_span_processor(SimpleSpanProcessor(exporter)) + # Provide the provider, but leave tracing_enabled=False / unset + options = ClientOptions( + tracing_enabled=False, + tracer_provider=provider, + ) client = construct_client( EchoClient, use_mtls, + client_options=options, credentials=ga_credentials.AnonymousCredentials(), ) @@ -157,31 +174,85 @@ def test_tracing_disabled_default(use_mtls): def test_custom_tracer_provider(use_mtls): - """Verifies that spans are emitted exclusively to the injected custom TracerProvider.""" + """Verifies that spans are emitted exclusively to the injected custom TracerProvider. + + Ensures strict isolation of trace data: when a client is configured with a + custom `TracerProvider`, generated RPC spans must be routed solely to that + provider's exporters and never leak into the ambient/global `TracerProvider`. + + Configures an ambient global `TracerProvider` with `global_exporter`, while + configuring the client with `custom_provider` and `custom_exporter`. After + executing an RPC, the test asserts that `custom_exporter` captured the span + while `global_exporter` recorded zero spans. + """ custom_exporter = InMemorySpanExporter() custom_provider = TracerProvider() custom_provider.add_span_processor(SimpleSpanProcessor(custom_exporter)) - other_exporter = InMemorySpanExporter() - other_provider = TracerProvider() - other_provider.add_span_processor(SimpleSpanProcessor(other_exporter)) + global_exporter = InMemorySpanExporter() + global_provider = TracerProvider() + global_provider.add_span_processor(SimpleSpanProcessor(global_exporter)) + + # Temporarily set the ambient global tracer provider + original_provider = trace.get_tracer_provider() + trace.set_tracer_provider(global_provider) + try: + options = ClientOptions( + tracing_enabled=True, + tracer_provider=custom_provider, + ) + client = construct_client( + EchoClient, + use_mtls, + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + + response = client.echo(showcase.EchoRequest(content="isolated trace")) + assert response.content == "isolated trace" + + assert len(custom_exporter.get_finished_spans()) == 1 + assert len(global_exporter.get_finished_spans()) == 0 + finally: + trace.set_tracer_provider(original_provider) + +def test_direct_client_initialization_tracing(span_exporter): + """Verifies end-to-end trace injection via direct EchoClient instantiation. + + Validates the template wiring in `client.py.j2` directly. In system test + harnesses, `construct_client` often creates the transport instance manually, + which bypasses `client.py`'s `if not transport_provided:` branch. This test + instantiates `EchoClient(client_options=...)` directly to prove that the client + resolves `_observability.get_otel_interceptor` and passes it to `EchoGrpcTransport`. + + Constructs `EchoClient` without a pre-instantiated transport. Patches + `EchoGrpcTransport.create_channel` solely to target the local insecure Showcase + endpoint (`localhost:7469`). Executes `client.echo()` and asserts span generation. + """ + exporter, provider = span_exporter options = ClientOptions( tracing_enabled=True, - tracer_provider=custom_provider, - ) - client = construct_client( - EchoClient, - use_mtls, - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), + tracer_provider=provider, ) - response = client.echo(showcase.EchoRequest(content="isolated trace")) - assert response.content == "isolated trace" + with mock.patch.object( + EchoClient.get_transport_class("grpc"), + "create_channel", + side_effect=lambda host, **kwargs: grpc.insecure_channel("localhost:7469"), + ): + # Client constructs the transport and wires interceptors itself + client = EchoClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + response = client.echo(showcase.EchoRequest(content="direct client wiring")) + assert response.content == "direct client wiring" - assert len(custom_exporter.get_finished_spans()) == 1 - assert len(other_exporter.get_finished_spans()) == 0 + spans = exporter.get_finished_spans() + assert len(spans) == 1 + assert spans[0].name == "google.showcase.v1beta1.Echo/Echo" + assert spans[0].attributes.get("rpc.system.name") == "grpc" def test_env_var_opt_in(span_exporter, use_mtls): From 2059f32059336c8a1e276e05e98b66ff75a00f55 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 15 Sep 2026 10:29:11 -0400 Subject: [PATCH 26/43] refactor(gapic): guard ClientInterceptor under TYPE_CHECKING in transport template - Place ClientInterceptor import under if TYPE_CHECKING: in grpc.py.j2 to eliminate runtime import overhead and avoid import failures on older google-api-core versions. - String-quote "ClientInterceptor" in the interceptors type annotation for GrpcTransport.__init__. - Regenerate and synchronize all golden gRPC transport files. --- .../%sub/services/%service/transports/grpc.py.j2 | 16 ++++------------ .../services/asset_service/transports/grpc.py | 16 ++++------------ .../services/iam_credentials/transports/grpc.py | 16 ++++------------ .../services/eventarc/transports/grpc.py | 16 ++++------------ .../config_service_v2/transports/grpc.py | 16 ++++------------ .../logging_service_v2/transports/grpc.py | 16 ++++------------ .../metrics_service_v2/transports/grpc.py | 16 ++++------------ .../config_service_v2/transports/grpc.py | 16 ++++------------ .../logging_service_v2/transports/grpc.py | 16 ++++------------ .../metrics_service_v2/transports/grpc.py | 16 ++++------------ .../services/cloud_redis/transports/grpc.py | 16 ++++------------ .../services/cloud_redis/transports/grpc.py | 16 ++++------------ .../storage_batch_operations/transports/grpc.py | 16 ++++------------ 13 files changed, 52 insertions(+), 156 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 index 8da1dfcce160..6d281c171caf 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 @@ -8,22 +8,14 @@ import json import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers -# Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions -try: +if TYPE_CHECKING: # pragma: NO COVER + # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -except ImportError: # pragma: NO COVER - ClientInterceptor = Union[ # type: ignore[misc,assignment] - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, - ] {% if service.has_lro %} from google.api_core import operations_v1 {% endif %} @@ -138,7 +130,7 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport): interceptors: Optional[ Sequence[ Union[ - ClientInterceptor, + "ClientInterceptor", Callable[[grpc.Channel], grpc.Channel], ] ] diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py index 1c92f07d98b4..1d6580b80ed4 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -17,22 +17,14 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers -# Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions -try: +if TYPE_CHECKING: + # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -except ImportError: # pragma: NO COVER - ClientInterceptor = Union[ # type: ignore[misc,assignment] - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, - ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -147,7 +139,7 @@ def __init__(self, *, interceptors: Optional[ Sequence[ Union[ - ClientInterceptor, + "ClientInterceptor", Callable[[grpc.Channel], grpc.Channel], ] ] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py index a1940f375c9c..b29bf163cc58 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py @@ -17,22 +17,14 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers -# Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions -try: +if TYPE_CHECKING: + # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -except ImportError: # pragma: NO COVER - ClientInterceptor = Union[ # type: ignore[misc,assignment] - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, - ] from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -153,7 +145,7 @@ def __init__(self, *, interceptors: Optional[ Sequence[ Union[ - ClientInterceptor, + "ClientInterceptor", Callable[[grpc.Channel], grpc.Channel], ] ] diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py index 503167d1e16b..0e18c592e1ac 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py @@ -17,22 +17,14 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers -# Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions -try: +if TYPE_CHECKING: + # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -except ImportError: # pragma: NO COVER - ClientInterceptor = Union[ # type: ignore[misc,assignment] - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, - ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -161,7 +153,7 @@ def __init__(self, *, interceptors: Optional[ Sequence[ Union[ - ClientInterceptor, + "ClientInterceptor", Callable[[grpc.Channel], grpc.Channel], ] ] diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index 940e3a761b31..5b427443797b 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -17,22 +17,14 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers -# Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions -try: +if TYPE_CHECKING: + # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -except ImportError: # pragma: NO COVER - ClientInterceptor = Union[ # type: ignore[misc,assignment] - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, - ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -147,7 +139,7 @@ def __init__(self, *, interceptors: Optional[ Sequence[ Union[ - ClientInterceptor, + "ClientInterceptor", Callable[[grpc.Channel], grpc.Channel], ] ] diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index b97b20ffe806..4e2e4196e99b 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -17,22 +17,14 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers -# Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions -try: +if TYPE_CHECKING: + # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -except ImportError: # pragma: NO COVER - ClientInterceptor = Union[ # type: ignore[misc,assignment] - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, - ] from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -146,7 +138,7 @@ def __init__(self, *, interceptors: Optional[ Sequence[ Union[ - ClientInterceptor, + "ClientInterceptor", Callable[[grpc.Channel], grpc.Channel], ] ] diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index dab5b52cf0dc..1dc6897f9301 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -17,22 +17,14 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers -# Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions -try: +if TYPE_CHECKING: + # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -except ImportError: # pragma: NO COVER - ClientInterceptor = Union[ # type: ignore[misc,assignment] - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, - ] from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -146,7 +138,7 @@ def __init__(self, *, interceptors: Optional[ Sequence[ Union[ - ClientInterceptor, + "ClientInterceptor", Callable[[grpc.Channel], grpc.Channel], ] ] diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index 940e3a761b31..5b427443797b 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -17,22 +17,14 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers -# Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions -try: +if TYPE_CHECKING: + # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -except ImportError: # pragma: NO COVER - ClientInterceptor = Union[ # type: ignore[misc,assignment] - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, - ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -147,7 +139,7 @@ def __init__(self, *, interceptors: Optional[ Sequence[ Union[ - ClientInterceptor, + "ClientInterceptor", Callable[[grpc.Channel], grpc.Channel], ] ] diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index b97b20ffe806..4e2e4196e99b 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -17,22 +17,14 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers -# Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions -try: +if TYPE_CHECKING: + # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -except ImportError: # pragma: NO COVER - ClientInterceptor = Union[ # type: ignore[misc,assignment] - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, - ] from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -146,7 +138,7 @@ def __init__(self, *, interceptors: Optional[ Sequence[ Union[ - ClientInterceptor, + "ClientInterceptor", Callable[[grpc.Channel], grpc.Channel], ] ] diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index dab5b52cf0dc..1dc6897f9301 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -17,22 +17,14 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers -# Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions -try: +if TYPE_CHECKING: + # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -except ImportError: # pragma: NO COVER - ClientInterceptor = Union[ # type: ignore[misc,assignment] - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, - ] from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore @@ -146,7 +138,7 @@ def __init__(self, *, interceptors: Optional[ Sequence[ Union[ - ClientInterceptor, + "ClientInterceptor", Callable[[grpc.Channel], grpc.Channel], ] ] diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index becf980c03c1..e72d49a74546 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -17,22 +17,14 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers -# Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions -try: +if TYPE_CHECKING: + # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -except ImportError: # pragma: NO COVER - ClientInterceptor = Union[ # type: ignore[misc,assignment] - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, - ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -167,7 +159,7 @@ def __init__(self, *, interceptors: Optional[ Sequence[ Union[ - ClientInterceptor, + "ClientInterceptor", Callable[[grpc.Channel], grpc.Channel], ] ] diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index 0cc07e360d58..5658d2c5826d 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -17,22 +17,14 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers -# Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions -try: +if TYPE_CHECKING: + # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -except ImportError: # pragma: NO COVER - ClientInterceptor = Union[ # type: ignore[misc,assignment] - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, - ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -167,7 +159,7 @@ def __init__(self, *, interceptors: Optional[ Sequence[ Union[ - ClientInterceptor, + "ClientInterceptor", Callable[[grpc.Channel], grpc.Channel], ] ] diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py index d3555f1bf2a5..45be455f447f 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py @@ -17,22 +17,14 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers -# Optional: OpenTelemetry tracing capabilities for grpc channel injection -# Note: ClientInterceptor was added in google-api-core 2.36.0+; fallback for older versions -try: +if TYPE_CHECKING: + # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -except ImportError: # pragma: NO COVER - ClientInterceptor = Union[ # type: ignore[misc,assignment] - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, - ] from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore @@ -153,7 +145,7 @@ def __init__(self, *, interceptors: Optional[ Sequence[ Union[ - ClientInterceptor, + "ClientInterceptor", Callable[[grpc.Channel], grpc.Channel], ] ] From 66a6f0ebe2fbf734880cb33677c9016a297828d1 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 15 Sep 2026 11:49:04 -0400 Subject: [PATCH 27/43] test(gapic): synchronize NO COVER pragma in golden gRPC transports Align if TYPE_CHECKING: in golden gRPC transport files with # pragma: NO COVER to match grpc.py.j2 template output. --- .../cloud/asset_v1/services/asset_service/transports/grpc.py | 2 +- .../credentials_v1/services/iam_credentials/transports/grpc.py | 2 +- .../cloud/eventarc_v1/services/eventarc/transports/grpc.py | 2 +- .../logging_v2/services/config_service_v2/transports/grpc.py | 2 +- .../logging_v2/services/logging_service_v2/transports/grpc.py | 2 +- .../logging_v2/services/metrics_service_v2/transports/grpc.py | 2 +- .../logging_v2/services/config_service_v2/transports/grpc.py | 2 +- .../logging_v2/services/logging_service_v2/transports/grpc.py | 2 +- .../logging_v2/services/metrics_service_v2/transports/grpc.py | 2 +- .../cloud/redis_v1/services/cloud_redis/transports/grpc.py | 2 +- .../cloud/redis_v1/services/cloud_redis/transports/grpc.py | 2 +- .../services/storage_batch_operations/transports/grpc.py | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py index 1d6580b80ed4..267e843bd30b 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -22,7 +22,7 @@ import grpc # type: ignore from google.api_core import grpc_helpers -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py index b29bf163cc58..afb217d40e8e 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py @@ -22,7 +22,7 @@ import grpc # type: ignore from google.api_core import grpc_helpers -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import gapic_v1 diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py index 0e18c592e1ac..37492a456a3c 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py @@ -22,7 +22,7 @@ import grpc # type: ignore from google.api_core import grpc_helpers -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index 5b427443797b..a984a2b148fa 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -22,7 +22,7 @@ import grpc # type: ignore from google.api_core import grpc_helpers -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index 4e2e4196e99b..b84d55ab637e 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -22,7 +22,7 @@ import grpc # type: ignore from google.api_core import grpc_helpers -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import gapic_v1 diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index 1dc6897f9301..68a021a84ba8 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -22,7 +22,7 @@ import grpc # type: ignore from google.api_core import grpc_helpers -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import gapic_v1 diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index 5b427443797b..a984a2b148fa 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -22,7 +22,7 @@ import grpc # type: ignore from google.api_core import grpc_helpers -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index 4e2e4196e99b..b84d55ab637e 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -22,7 +22,7 @@ import grpc # type: ignore from google.api_core import grpc_helpers -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import gapic_v1 diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index 1dc6897f9301..68a021a84ba8 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -22,7 +22,7 @@ import grpc # type: ignore from google.api_core import grpc_helpers -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import gapic_v1 diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index e72d49a74546..df9d22081945 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -22,7 +22,7 @@ import grpc # type: ignore from google.api_core import grpc_helpers -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index 5658d2c5826d..448117af19b0 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -22,7 +22,7 @@ import grpc # type: ignore from google.api_core import grpc_helpers -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py index 45be455f447f..6af36576dacc 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py @@ -22,7 +22,7 @@ import grpc # type: ignore from google.api_core import grpc_helpers -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 From 7ebebfaba64c23cedab124391bf1a0a993e02b8b Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 15 Sep 2026 19:34:24 -0400 Subject: [PATCH 28/43] test(gapic): support flexible import of construct_client in system tracing tests --- packages/gapic-generator/tests/system/test_tracing.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/gapic-generator/tests/system/test_tracing.py b/packages/gapic-generator/tests/system/test_tracing.py index b187a7ba2015..8906b8666cd4 100644 --- a/packages/gapic-generator/tests/system/test_tracing.py +++ b/packages/gapic-generator/tests/system/test_tracing.py @@ -41,7 +41,10 @@ from google.rpc import code_pb2 from google.showcase import EchoClient -from .conftest import construct_client +try: + from .conftest import construct_client +except (ImportError, ValueError): + from conftest import construct_client @pytest.fixture From a7956a5c3bef80eebbcd2bc5d5fc6729f972031c Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 15 Sep 2026 19:34:31 -0400 Subject: [PATCH 29/43] feat(gapic): resolve OTel interceptor in GrpcTransport and pass client_options to wrapped methods --- .../%sub/services/%service/client.py.j2 | 24 ++++----- .../services/%service/transports/base.py.j2 | 35 ++++++++++++- .../services/%service/transports/grpc.py.j2 | 20 +++++++- .../%name_%version/%sub/test_%service.py.j2 | 49 ++++++++++++++++--- 4 files changed, 104 insertions(+), 24 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 index 157f014508dd..0d3cd51c33c4 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 @@ -11,6 +11,7 @@ from collections import OrderedDict import functools {% endif %} from http import HTTPStatus +import inspect import json import logging as std_logging import os @@ -538,23 +539,18 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): else cast(Callable[..., {{ service.name }}Transport], transport) ) {% endif %} - # When OpenTelemetry tracing is enabled, obtain the channel interceptor - # and pass it to the transport. - interceptors = [] - {% if 'grpc' in opts.transport %} + # When OpenTelemetry tracing is enabled, pass client_options to the transport + # so it can wire tracing interceptors and method spans. + client_options = None if ( - isinstance(transport_init, type) - and issubclass(transport_init, {{ service.grpc_transport_name }}) - and _observability is not None + _observability is not None + and _observability.is_otel_capabilities_enabled(self._client_options) and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) + not isinstance(transport_init, type) + or issubclass(transport_init, {{ service.grpc_transport_name }}) ) - is not None ): - interceptors.append(otel_interceptor) - {% endif %} + client_options = self._client_options # initialize with the provided callable or the passed in class transport_kwargs = { @@ -567,7 +563,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"interceptors": interceptors} if interceptors else {}), + **({"client_options": client_options} if client_options else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 index f0cf1178da69..602695caa1b2 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 @@ -3,6 +3,7 @@ {% block content %} import abc +import inspect from typing import {% if service.any_extended_operations_methods %}Any, {% endif %}Awaitable, Callable, Dict, Optional, Sequence, Union {% set package_path = api.naming.module_namespace|join('.') + "." + api.naming.versioned_module_name %} @@ -10,6 +11,7 @@ from {{package_path}} import gapic_version as package_version import google.auth # type: ignore import google.api_core +from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries @@ -75,6 +77,7 @@ class {{ service.name }}Transport(abc.ABC): client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -105,6 +108,9 @@ class {{ service.name }}Transport(abc.ABC): to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. """ {% if service.any_extended_operations_methods %} self._extended_operations_services: Dict[str, Any] = {} @@ -145,17 +151,38 @@ class {{ service.name }}Transport(abc.ABC): host += ':443' self._host = host + self._client_options = client_options + # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments + # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility + # with older versions of google-api-core. + self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrapped_methods: Dict[Callable, Callable] = {} @property def host(self): return self._host + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_tracing: + kwargs["client_options"] = self._client_options + try: + kwargs["kind"] = self.kind + # Base transport raises NotImplementedError for abstract kind property. + # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + except NotImplementedError: # pragma: NO COVER + pass + return gapic_v1.method.wrap_method(func, *args, **kwargs) + # Remove tracing-specific arguments if older google-api-core is installed + for k in ["client_options", "method_name", "is_streaming", "kind"]: + kwargs.pop(k, None) + return gapic_v1.method.wrap_method(func, *args, **kwargs) + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { {% for method in service.methods.values() %} - self.{{ method.transport_safe_name|snake_case }}: gapic_v1.method.wrap_method( + self.{{ method.transport_safe_name|snake_case }}: self._wrap_method( self.{{ method.transport_safe_name|snake_case }}, {% if method.retry %} default_retry=retries.Retry( @@ -178,10 +205,14 @@ class {{ service.name }}Transport(abc.ABC): {% endif %} default_timeout={{ method.timeout }}, client_info=client_info, + method_name="{{ '.'.join(method.meta.address.package) }}.{{ service.name }}/{{ method.name }}", + {% if method.client_streaming or method.server_streaming %} + is_streaming=True, + {% endif %} ), {% endfor %}{# method in service.methods.values() #} {% for method_name in api.mixin_api_methods.keys() %} - self.{{ method_name|snake_case }}: gapic_v1.method.wrap_method( + self.{{ method_name|snake_case }}: self._wrap_method( self.{{ method_name|snake_case }}, default_timeout=None, client_info=client_info, diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 index 6d281c171caf..94ba82a2f11a 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 @@ -19,7 +19,12 @@ if TYPE_CHECKING: # pragma: NO COVER {% if service.has_lro %} from google.api_core import operations_v1 {% endif %} +from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +try: + from google.api_core import _observability +except ImportError: # pragma: NO COVER + _observability = None import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -135,6 +140,7 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport): ] ] ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, ) -> None: """Instantiate the transport. @@ -188,6 +194,9 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport): interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): Additional interceptors (or callables that apply interceptors) to apply to the gRPC channel. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -246,6 +255,7 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport): client_info=client_info, always_use_jwt_access=always_use_jwt_access, api_audience=api_audience, + client_options=client_options, ) if not self._grpc_channel: @@ -267,12 +277,20 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport): ], ) + channel_interceptors = list(interceptors) if interceptors else [] + if ( + _observability is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and otel_interceptor not in channel_interceptors + ): + channel_interceptors.append(otel_interceptor) + apply_interceptors = getattr( grpc_helpers, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 index ec499686a51d..760f1973140e 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 @@ -905,9 +905,8 @@ def test_{{ service.client_name|snake_case }}_client_options_from_dict(): def test_{{ service.client_name|snake_case }}_otel_channel_injection_enabled(): - mock_interceptor = mock.Mock() mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = mock_interceptor + mock_obs.is_otel_capabilities_enabled.return_value = True with ( mock.patch( "{{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join('.') }}.services.{{ service.name|snake_case }}.client._observability", @@ -919,14 +918,14 @@ def test_{{ service.client_name|snake_case }}_otel_channel_injection_enabled(): ): client = {{ service.client_name }}(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert called_kwargs.get("interceptors") == [mock_interceptor] + assert called_kwargs.get("client_options") == client._client_options def test_{{ service.client_name|snake_case }}_otel_channel_injection_disabled(): mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = None + mock_obs.is_otel_capabilities_enabled.return_value = False with ( mock.patch( "{{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join('.') }}.services.{{ service.name|snake_case }}.client._observability", @@ -938,9 +937,9 @@ def test_{{ service.client_name|snake_case }}_otel_channel_injection_disabled(): ): client = {{ service.client_name }}(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert not called_kwargs.get("interceptors", []) + assert not called_kwargs.get("client_options") def test_{{ service.name|snake_case }}_grpc_transport_channel_interceptors(): @@ -971,6 +970,42 @@ def test_{{ service.name|snake_case }}_grpc_transport_channel_interceptors(): assert transport.grpc_channel == mock_channel +def test_{{ service.name|snake_case }}_grpc_transport_otel_channel_interceptor(): + mock_otel_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_otel_interceptor + mock_channel = mock.Mock() + + with ( + mock.patch( + "{{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join('.') }}.services.{{ service.name|snake_case }}.transports.grpc._observability", + mock_obs, + ), + mock.patch.object( + transports.{{ service.grpc_transport_name }}, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + options = client_options.ClientOptions() + transport = transports.{{ service.grpc_transport_name }}( + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + + mock_obs.get_otel_interceptor.assert_called_once_with(options) + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_otel_interceptor] + ) + assert transport.grpc_channel == mock_channel + + def test_{{ service.name|snake_case }}_grpc_transport_custom_channel_interceptors(): mock_interceptor = mock.Mock() mock_custom_channel = mock.Mock(spec=grpc.Channel) From cd5299a3b473b179652fc41c1ca018f2be08ddcd Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 15 Sep 2026 19:53:22 -0400 Subject: [PATCH 30/43] test(gapic): update bazel integration goldens for transport tracing updates --- .../asset_v1/services/asset_service/client.py | 22 ++- .../services/asset_service/transports/base.py | 98 ++++++++--- .../services/asset_service/transports/grpc.py | 20 ++- .../unit/gapic/asset_v1/test_asset_service.py | 49 +++++- .../services/iam_credentials/client.py | 22 ++- .../iam_credentials/transports/base.py | 39 ++++- .../iam_credentials/transports/grpc.py | 20 ++- .../credentials_v1/test_iam_credentials.py | 49 +++++- .../eventarc_v1/services/eventarc/client.py | 22 ++- .../services/eventarc/transports/base.py | 162 ++++++++++++------ .../services/eventarc/transports/grpc.py | 20 ++- .../unit/gapic/eventarc_v1/test_eventarc.py | 49 +++++- .../services/config_service_v2/client.py | 22 ++- .../config_service_v2/transports/base.py | 129 ++++++++++---- .../config_service_v2/transports/grpc.py | 20 ++- .../services/logging_service_v2/client.py | 22 ++- .../logging_service_v2/transports/base.py | 52 +++++- .../logging_service_v2/transports/grpc.py | 20 ++- .../services/metrics_service_v2/client.py | 22 ++- .../metrics_service_v2/transports/base.py | 48 +++++- .../metrics_service_v2/transports/grpc.py | 20 ++- .../logging_v2/test_config_service_v2.py | 49 +++++- .../logging_v2/test_logging_service_v2.py | 49 +++++- .../logging_v2/test_metrics_service_v2.py | 49 +++++- .../services/config_service_v2/client.py | 22 ++- .../config_service_v2/transports/base.py | 129 ++++++++++---- .../config_service_v2/transports/grpc.py | 20 ++- .../services/logging_service_v2/client.py | 22 ++- .../logging_service_v2/transports/base.py | 52 +++++- .../logging_service_v2/transports/grpc.py | 20 ++- .../services/metrics_service_v2/client.py | 22 ++- .../metrics_service_v2/transports/base.py | 48 +++++- .../metrics_service_v2/transports/grpc.py | 20 ++- .../logging_v2/test_config_service_v2.py | 49 +++++- .../logging_v2/test_logging_service_v2.py | 49 +++++- .../logging_v2/test_metrics_service_v2.py | 49 +++++- .../redis_v1/services/cloud_redis/client.py | 22 ++- .../services/cloud_redis/transports/base.py | 74 ++++++-- .../services/cloud_redis/transports/grpc.py | 20 ++- .../unit/gapic/redis_v1/test_cloud_redis.py | 49 +++++- .../redis_v1/services/cloud_redis/client.py | 22 ++- .../services/cloud_redis/transports/base.py | 56 ++++-- .../services/cloud_redis/transports/grpc.py | 20 ++- .../unit/gapic/redis_v1/test_cloud_redis.py | 49 +++++- .../storage_batch_operations/client.py | 22 ++- .../transports/base.py | 60 +++++-- .../transports/grpc.py | 20 ++- .../test_storage_batch_operations.py | 49 +++++- 48 files changed, 1576 insertions(+), 463 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py index 492935dd8e5a..cc1089e93d63 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py @@ -15,6 +15,7 @@ # from collections import OrderedDict from http import HTTPStatus +import inspect import json import logging as std_logging import os @@ -552,21 +553,18 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., AssetServiceTransport], transport) ) - # When OpenTelemetry tracing is enabled, obtain the channel interceptor - # and pass it to the transport. - interceptors = [] + # When OpenTelemetry tracing is enabled, pass client_options to the transport + # so it can wire tracing interceptors and method spans. + client_options = None if ( - isinstance(transport_init, type) - and issubclass(transport_init, AssetServiceGrpcTransport) - and _observability is not None + _observability is not None + and _observability.is_otel_capabilities_enabled(self._client_options) and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) + not isinstance(transport_init, type) + or issubclass(transport_init, AssetServiceGrpcTransport) ) - is not None ): - interceptors.append(otel_interceptor) + client_options = self._client_options # initialize with the provided callable or the passed in class transport_kwargs = { @@ -579,7 +577,7 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"interceptors": interceptors} if interceptors else {}), + **({"client_options": client_options} if client_options else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py index 2afbe7e1d6c8..23fd770b2c5a 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py @@ -14,12 +14,14 @@ # limitations under the License. # import abc +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.asset_v1 import gapic_version as package_version import google.auth # type: ignore import google.api_core +from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries @@ -55,6 +57,7 @@ def __init__( client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -85,6 +88,9 @@ def __init__( to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. """ # Save the scopes. @@ -122,26 +128,49 @@ def __init__( host += ':443' self._host = host + self._client_options = client_options + # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments + # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility + # with older versions of google-api-core. + self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrapped_methods: Dict[Callable, Callable] = {} @property def host(self): return self._host + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_tracing: + kwargs["client_options"] = self._client_options + try: + kwargs["kind"] = self.kind + # Base transport raises NotImplementedError for abstract kind property. + # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + except NotImplementedError: # pragma: NO COVER + pass + return gapic_v1.method.wrap_method(func, *args, **kwargs) + # Remove tracing-specific arguments if older google-api-core is installed + for k in ["client_options", "method_name", "is_streaming", "kind"]: + kwargs.pop(k, None) + return gapic_v1.method.wrap_method(func, *args, **kwargs) + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { - self.export_assets: gapic_v1.method.wrap_method( + self.export_assets: self._wrap_method( self.export_assets, default_timeout=60.0, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/ExportAssets", ), - self.list_assets: gapic_v1.method.wrap_method( + self.list_assets: self._wrap_method( self.list_assets, default_timeout=None, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/ListAssets", ), - self.batch_get_assets_history: gapic_v1.method.wrap_method( + self.batch_get_assets_history: self._wrap_method( self.batch_get_assets_history, default_retry=retries.Retry( initial=0.1, @@ -155,13 +184,15 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/BatchGetAssetsHistory", ), - self.create_feed: gapic_v1.method.wrap_method( + self.create_feed: self._wrap_method( self.create_feed, default_timeout=60.0, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/CreateFeed", ), - self.get_feed: gapic_v1.method.wrap_method( + self.get_feed: self._wrap_method( self.get_feed, default_retry=retries.Retry( initial=0.1, @@ -175,8 +206,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/GetFeed", ), - self.list_feeds: gapic_v1.method.wrap_method( + self.list_feeds: self._wrap_method( self.list_feeds, default_retry=retries.Retry( initial=0.1, @@ -190,13 +222,15 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/ListFeeds", ), - self.update_feed: gapic_v1.method.wrap_method( + self.update_feed: self._wrap_method( self.update_feed, default_timeout=60.0, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/UpdateFeed", ), - self.delete_feed: gapic_v1.method.wrap_method( + self.delete_feed: self._wrap_method( self.delete_feed, default_retry=retries.Retry( initial=0.1, @@ -210,8 +244,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/DeleteFeed", ), - self.search_all_resources: gapic_v1.method.wrap_method( + self.search_all_resources: self._wrap_method( self.search_all_resources, default_retry=retries.Retry( initial=0.1, @@ -225,8 +260,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=15.0, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/SearchAllResources", ), - self.search_all_iam_policies: gapic_v1.method.wrap_method( + self.search_all_iam_policies: self._wrap_method( self.search_all_iam_policies, default_retry=retries.Retry( initial=0.1, @@ -240,8 +276,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=15.0, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/SearchAllIamPolicies", ), - self.analyze_iam_policy: gapic_v1.method.wrap_method( + self.analyze_iam_policy: self._wrap_method( self.analyze_iam_policy, default_retry=retries.Retry( initial=0.1, @@ -254,68 +291,81 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=300.0, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/AnalyzeIamPolicy", ), - self.analyze_iam_policy_longrunning: gapic_v1.method.wrap_method( + self.analyze_iam_policy_longrunning: self._wrap_method( self.analyze_iam_policy_longrunning, default_timeout=60.0, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/AnalyzeIamPolicyLongrunning", ), - self.analyze_move: gapic_v1.method.wrap_method( + self.analyze_move: self._wrap_method( self.analyze_move, default_timeout=None, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/AnalyzeMove", ), - self.query_assets: gapic_v1.method.wrap_method( + self.query_assets: self._wrap_method( self.query_assets, default_timeout=None, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/QueryAssets", ), - self.create_saved_query: gapic_v1.method.wrap_method( + self.create_saved_query: self._wrap_method( self.create_saved_query, default_timeout=None, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/CreateSavedQuery", ), - self.get_saved_query: gapic_v1.method.wrap_method( + self.get_saved_query: self._wrap_method( self.get_saved_query, default_timeout=None, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/GetSavedQuery", ), - self.list_saved_queries: gapic_v1.method.wrap_method( + self.list_saved_queries: self._wrap_method( self.list_saved_queries, default_timeout=None, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/ListSavedQueries", ), - self.update_saved_query: gapic_v1.method.wrap_method( + self.update_saved_query: self._wrap_method( self.update_saved_query, default_timeout=None, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/UpdateSavedQuery", ), - self.delete_saved_query: gapic_v1.method.wrap_method( + self.delete_saved_query: self._wrap_method( self.delete_saved_query, default_timeout=None, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/DeleteSavedQuery", ), - self.batch_get_effective_iam_policies: gapic_v1.method.wrap_method( + self.batch_get_effective_iam_policies: self._wrap_method( self.batch_get_effective_iam_policies, default_timeout=None, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/BatchGetEffectiveIamPolicies", ), - self.analyze_org_policies: gapic_v1.method.wrap_method( + self.analyze_org_policies: self._wrap_method( self.analyze_org_policies, default_timeout=None, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/AnalyzeOrgPolicies", ), - self.analyze_org_policy_governed_containers: gapic_v1.method.wrap_method( + self.analyze_org_policy_governed_containers: self._wrap_method( self.analyze_org_policy_governed_containers, default_timeout=None, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedContainers", ), - self.analyze_org_policy_governed_assets: gapic_v1.method.wrap_method( + self.analyze_org_policy_governed_assets: self._wrap_method( self.analyze_org_policy_governed_assets, default_timeout=None, client_info=client_info, + method_name="google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedAssets", ), - self.get_operation: gapic_v1.method.wrap_method( + self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py index 267e843bd30b..d284544892cf 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -26,7 +26,12 @@ # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 +from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +try: + from google.api_core import _observability +except ImportError: # pragma: NO COVER + _observability = None import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,6 +149,7 @@ def __init__(self, *, ] ] ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, ) -> None: """Instantiate the transport. @@ -197,6 +203,9 @@ def __init__(self, *, interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): Additional interceptors (or callables that apply interceptors) to apply to the gRPC channel. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -253,6 +262,7 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, api_audience=api_audience, + client_options=client_options, ) if not self._grpc_channel: @@ -274,12 +284,20 @@ def __init__(self, *, ], ) + channel_interceptors = list(interceptors) if interceptors else [] + if ( + _observability is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and otel_interceptor not in channel_interceptors + ): + channel_interceptors.append(otel_interceptor) + apply_interceptors = getattr( grpc_helpers, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py index 1b833561fbe0..e40f13e5dd1b 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py @@ -761,9 +761,8 @@ def test_asset_service_client_client_options_from_dict(): def test_asset_service_client_otel_channel_injection_enabled(): - mock_interceptor = mock.Mock() mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = mock_interceptor + mock_obs.is_otel_capabilities_enabled.return_value = True with ( mock.patch( "google.cloud.asset_v1.services.asset_service.client._observability", @@ -775,14 +774,14 @@ def test_asset_service_client_otel_channel_injection_enabled(): ): client = AssetServiceClient(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert called_kwargs.get("interceptors") == [mock_interceptor] + assert called_kwargs.get("client_options") == client._client_options def test_asset_service_client_otel_channel_injection_disabled(): mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = None + mock_obs.is_otel_capabilities_enabled.return_value = False with ( mock.patch( "google.cloud.asset_v1.services.asset_service.client._observability", @@ -794,9 +793,9 @@ def test_asset_service_client_otel_channel_injection_disabled(): ): client = AssetServiceClient(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert not called_kwargs.get("interceptors", []) + assert not called_kwargs.get("client_options") def test_asset_service_grpc_transport_channel_interceptors(): @@ -827,6 +826,42 @@ def test_asset_service_grpc_transport_channel_interceptors(): assert transport.grpc_channel == mock_channel +def test_asset_service_grpc_transport_otel_channel_interceptor(): + mock_otel_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_otel_interceptor + mock_channel = mock.Mock() + + with ( + mock.patch( + "google.cloud.asset_v1.services.asset_service.transports.grpc._observability", + mock_obs, + ), + mock.patch.object( + transports.AssetServiceGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + options = client_options.ClientOptions() + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + + mock_obs.get_otel_interceptor.assert_called_once_with(options) + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_otel_interceptor] + ) + assert transport.grpc_channel == mock_channel + + def test_asset_service_grpc_transport_custom_channel_interceptors(): mock_interceptor = mock.Mock() mock_custom_channel = mock.Mock(spec=grpc.Channel) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index 814806e76f0a..301e04b7f19d 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -15,6 +15,7 @@ # from collections import OrderedDict from http import HTTPStatus +import inspect import json import logging as std_logging import os @@ -489,21 +490,18 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., IAMCredentialsTransport], transport) ) - # When OpenTelemetry tracing is enabled, obtain the channel interceptor - # and pass it to the transport. - interceptors = [] + # When OpenTelemetry tracing is enabled, pass client_options to the transport + # so it can wire tracing interceptors and method spans. + client_options = None if ( - isinstance(transport_init, type) - and issubclass(transport_init, IAMCredentialsGrpcTransport) - and _observability is not None + _observability is not None + and _observability.is_otel_capabilities_enabled(self._client_options) and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) + not isinstance(transport_init, type) + or issubclass(transport_init, IAMCredentialsGrpcTransport) ) - is not None ): - interceptors.append(otel_interceptor) + client_options = self._client_options # initialize with the provided callable or the passed in class transport_kwargs = { @@ -516,7 +514,7 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"interceptors": interceptors} if interceptors else {}), + **({"client_options": client_options} if client_options else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py index 37bcbf2cb766..dcbb46130e2e 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py @@ -14,12 +14,14 @@ # limitations under the License. # import abc +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.iam.credentials_v1 import gapic_version as package_version import google.auth # type: ignore import google.api_core +from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries @@ -52,6 +54,7 @@ def __init__( client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -82,6 +85,9 @@ def __init__( to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. """ # Save the scopes. @@ -119,16 +125,37 @@ def __init__( host += ':443' self._host = host + self._client_options = client_options + # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments + # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility + # with older versions of google-api-core. + self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrapped_methods: Dict[Callable, Callable] = {} @property def host(self): return self._host + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_tracing: + kwargs["client_options"] = self._client_options + try: + kwargs["kind"] = self.kind + # Base transport raises NotImplementedError for abstract kind property. + # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + except NotImplementedError: # pragma: NO COVER + pass + return gapic_v1.method.wrap_method(func, *args, **kwargs) + # Remove tracing-specific arguments if older google-api-core is installed + for k in ["client_options", "method_name", "is_streaming", "kind"]: + kwargs.pop(k, None) + return gapic_v1.method.wrap_method(func, *args, **kwargs) + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { - self.generate_access_token: gapic_v1.method.wrap_method( + self.generate_access_token: self._wrap_method( self.generate_access_token, default_retry=retries.Retry( initial=0.1, @@ -142,8 +169,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.iam.credentials.v1.IAMCredentials/GenerateAccessToken", ), - self.generate_id_token: gapic_v1.method.wrap_method( + self.generate_id_token: self._wrap_method( self.generate_id_token, default_retry=retries.Retry( initial=0.1, @@ -157,8 +185,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.iam.credentials.v1.IAMCredentials/GenerateIdToken", ), - self.sign_blob: gapic_v1.method.wrap_method( + self.sign_blob: self._wrap_method( self.sign_blob, default_retry=retries.Retry( initial=0.1, @@ -172,8 +201,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.iam.credentials.v1.IAMCredentials/SignBlob", ), - self.sign_jwt: gapic_v1.method.wrap_method( + self.sign_jwt: self._wrap_method( self.sign_jwt, default_retry=retries.Retry( initial=0.1, @@ -187,6 +217,7 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.iam.credentials.v1.IAMCredentials/SignJwt", ), } diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py index afb217d40e8e..2cafce86ffa2 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py @@ -25,7 +25,12 @@ if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +try: + from google.api_core import _observability +except ImportError: # pragma: NO COVER + _observability = None import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -150,6 +155,7 @@ def __init__(self, *, ] ] ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, ) -> None: """Instantiate the transport. @@ -203,6 +209,9 @@ def __init__(self, *, interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): Additional interceptors (or callables that apply interceptors) to apply to the gRPC channel. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -258,6 +267,7 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, api_audience=api_audience, + client_options=client_options, ) if not self._grpc_channel: @@ -279,12 +289,20 @@ def __init__(self, *, ], ) + channel_interceptors = list(interceptors) if interceptors else [] + if ( + _observability is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and otel_interceptor not in channel_interceptors + ): + channel_interceptors.append(otel_interceptor) + apply_interceptors = getattr( grpc_helpers, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py index dfc140216554..978a42823245 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py @@ -751,9 +751,8 @@ def test_iam_credentials_client_client_options_from_dict(): def test_iam_credentials_client_otel_channel_injection_enabled(): - mock_interceptor = mock.Mock() mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = mock_interceptor + mock_obs.is_otel_capabilities_enabled.return_value = True with ( mock.patch( "google.iam.credentials_v1.services.iam_credentials.client._observability", @@ -765,14 +764,14 @@ def test_iam_credentials_client_otel_channel_injection_enabled(): ): client = IAMCredentialsClient(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert called_kwargs.get("interceptors") == [mock_interceptor] + assert called_kwargs.get("client_options") == client._client_options def test_iam_credentials_client_otel_channel_injection_disabled(): mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = None + mock_obs.is_otel_capabilities_enabled.return_value = False with ( mock.patch( "google.iam.credentials_v1.services.iam_credentials.client._observability", @@ -784,9 +783,9 @@ def test_iam_credentials_client_otel_channel_injection_disabled(): ): client = IAMCredentialsClient(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert not called_kwargs.get("interceptors", []) + assert not called_kwargs.get("client_options") def test_iam_credentials_grpc_transport_channel_interceptors(): @@ -817,6 +816,42 @@ def test_iam_credentials_grpc_transport_channel_interceptors(): assert transport.grpc_channel == mock_channel +def test_iam_credentials_grpc_transport_otel_channel_interceptor(): + mock_otel_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_otel_interceptor + mock_channel = mock.Mock() + + with ( + mock.patch( + "google.iam.credentials_v1.services.iam_credentials.transports.grpc._observability", + mock_obs, + ), + mock.patch.object( + transports.IAMCredentialsGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + options = client_options.ClientOptions() + transport = transports.IAMCredentialsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + + mock_obs.get_otel_interceptor.assert_called_once_with(options) + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_otel_interceptor] + ) + assert transport.grpc_channel == mock_channel + + def test_iam_credentials_grpc_transport_custom_channel_interceptors(): mock_interceptor = mock.Mock() mock_custom_channel = mock.Mock(spec=grpc.Channel) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index 1df357a593f2..08327225cefa 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -15,6 +15,7 @@ # from collections import OrderedDict from http import HTTPStatus +import inspect import json import logging as std_logging import os @@ -672,21 +673,18 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., EventarcTransport], transport) ) - # When OpenTelemetry tracing is enabled, obtain the channel interceptor - # and pass it to the transport. - interceptors = [] + # When OpenTelemetry tracing is enabled, pass client_options to the transport + # so it can wire tracing interceptors and method spans. + client_options = None if ( - isinstance(transport_init, type) - and issubclass(transport_init, EventarcGrpcTransport) - and _observability is not None + _observability is not None + and _observability.is_otel_capabilities_enabled(self._client_options) and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) + not isinstance(transport_init, type) + or issubclass(transport_init, EventarcGrpcTransport) ) - is not None ): - interceptors.append(otel_interceptor) + client_options = self._client_options # initialize with the provided callable or the passed in class transport_kwargs = { @@ -699,7 +697,7 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"interceptors": interceptors} if interceptors else {}), + **({"client_options": client_options} if client_options else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py index 3c054d084716..d5bfd80d5de1 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py @@ -14,12 +14,14 @@ # limitations under the License. # import abc +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.eventarc_v1 import gapic_version as package_version import google.auth # type: ignore import google.api_core +from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries @@ -67,6 +69,7 @@ def __init__( client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -97,6 +100,9 @@ def __init__( to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. """ # Save the scopes. @@ -134,251 +140,311 @@ def __init__( host += ':443' self._host = host + self._client_options = client_options + # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments + # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility + # with older versions of google-api-core. + self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrapped_methods: Dict[Callable, Callable] = {} @property def host(self): return self._host + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_tracing: + kwargs["client_options"] = self._client_options + try: + kwargs["kind"] = self.kind + # Base transport raises NotImplementedError for abstract kind property. + # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + except NotImplementedError: # pragma: NO COVER + pass + return gapic_v1.method.wrap_method(func, *args, **kwargs) + # Remove tracing-specific arguments if older google-api-core is installed + for k in ["client_options", "method_name", "is_streaming", "kind"]: + kwargs.pop(k, None) + return gapic_v1.method.wrap_method(func, *args, **kwargs) + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { - self.get_trigger: gapic_v1.method.wrap_method( + self.get_trigger: self._wrap_method( self.get_trigger, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/GetTrigger", ), - self.list_triggers: gapic_v1.method.wrap_method( + self.list_triggers: self._wrap_method( self.list_triggers, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/ListTriggers", ), - self.create_trigger: gapic_v1.method.wrap_method( + self.create_trigger: self._wrap_method( self.create_trigger, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/CreateTrigger", ), - self.update_trigger: gapic_v1.method.wrap_method( + self.update_trigger: self._wrap_method( self.update_trigger, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/UpdateTrigger", ), - self.delete_trigger: gapic_v1.method.wrap_method( + self.delete_trigger: self._wrap_method( self.delete_trigger, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/DeleteTrigger", ), - self.get_channel: gapic_v1.method.wrap_method( + self.get_channel: self._wrap_method( self.get_channel, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/GetChannel", ), - self.list_channels: gapic_v1.method.wrap_method( + self.list_channels: self._wrap_method( self.list_channels, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/ListChannels", ), - self.create_channel_: gapic_v1.method.wrap_method( + self.create_channel_: self._wrap_method( self.create_channel_, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/CreateChannel", ), - self.update_channel: gapic_v1.method.wrap_method( + self.update_channel: self._wrap_method( self.update_channel, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/UpdateChannel", ), - self.delete_channel: gapic_v1.method.wrap_method( + self.delete_channel: self._wrap_method( self.delete_channel, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/DeleteChannel", ), - self.get_provider: gapic_v1.method.wrap_method( + self.get_provider: self._wrap_method( self.get_provider, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/GetProvider", ), - self.list_providers: gapic_v1.method.wrap_method( + self.list_providers: self._wrap_method( self.list_providers, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/ListProviders", ), - self.get_channel_connection: gapic_v1.method.wrap_method( + self.get_channel_connection: self._wrap_method( self.get_channel_connection, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/GetChannelConnection", ), - self.list_channel_connections: gapic_v1.method.wrap_method( + self.list_channel_connections: self._wrap_method( self.list_channel_connections, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/ListChannelConnections", ), - self.create_channel_connection: gapic_v1.method.wrap_method( + self.create_channel_connection: self._wrap_method( self.create_channel_connection, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/CreateChannelConnection", ), - self.delete_channel_connection: gapic_v1.method.wrap_method( + self.delete_channel_connection: self._wrap_method( self.delete_channel_connection, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/DeleteChannelConnection", ), - self.get_google_channel_config: gapic_v1.method.wrap_method( + self.get_google_channel_config: self._wrap_method( self.get_google_channel_config, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/GetGoogleChannelConfig", ), - self.update_google_channel_config: gapic_v1.method.wrap_method( + self.update_google_channel_config: self._wrap_method( self.update_google_channel_config, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/UpdateGoogleChannelConfig", ), - self.get_message_bus: gapic_v1.method.wrap_method( + self.get_message_bus: self._wrap_method( self.get_message_bus, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/GetMessageBus", ), - self.list_message_buses: gapic_v1.method.wrap_method( + self.list_message_buses: self._wrap_method( self.list_message_buses, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/ListMessageBuses", ), - self.list_message_bus_enrollments: gapic_v1.method.wrap_method( + self.list_message_bus_enrollments: self._wrap_method( self.list_message_bus_enrollments, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/ListMessageBusEnrollments", ), - self.create_message_bus: gapic_v1.method.wrap_method( + self.create_message_bus: self._wrap_method( self.create_message_bus, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/CreateMessageBus", ), - self.update_message_bus: gapic_v1.method.wrap_method( + self.update_message_bus: self._wrap_method( self.update_message_bus, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/UpdateMessageBus", ), - self.delete_message_bus: gapic_v1.method.wrap_method( + self.delete_message_bus: self._wrap_method( self.delete_message_bus, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/DeleteMessageBus", ), - self.get_enrollment: gapic_v1.method.wrap_method( + self.get_enrollment: self._wrap_method( self.get_enrollment, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/GetEnrollment", ), - self.list_enrollments: gapic_v1.method.wrap_method( + self.list_enrollments: self._wrap_method( self.list_enrollments, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/ListEnrollments", ), - self.create_enrollment: gapic_v1.method.wrap_method( + self.create_enrollment: self._wrap_method( self.create_enrollment, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/CreateEnrollment", ), - self.update_enrollment: gapic_v1.method.wrap_method( + self.update_enrollment: self._wrap_method( self.update_enrollment, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/UpdateEnrollment", ), - self.delete_enrollment: gapic_v1.method.wrap_method( + self.delete_enrollment: self._wrap_method( self.delete_enrollment, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/DeleteEnrollment", ), - self.get_pipeline: gapic_v1.method.wrap_method( + self.get_pipeline: self._wrap_method( self.get_pipeline, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/GetPipeline", ), - self.list_pipelines: gapic_v1.method.wrap_method( + self.list_pipelines: self._wrap_method( self.list_pipelines, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/ListPipelines", ), - self.create_pipeline: gapic_v1.method.wrap_method( + self.create_pipeline: self._wrap_method( self.create_pipeline, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/CreatePipeline", ), - self.update_pipeline: gapic_v1.method.wrap_method( + self.update_pipeline: self._wrap_method( self.update_pipeline, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/UpdatePipeline", ), - self.delete_pipeline: gapic_v1.method.wrap_method( + self.delete_pipeline: self._wrap_method( self.delete_pipeline, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/DeletePipeline", ), - self.get_google_api_source: gapic_v1.method.wrap_method( + self.get_google_api_source: self._wrap_method( self.get_google_api_source, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/GetGoogleApiSource", ), - self.list_google_api_sources: gapic_v1.method.wrap_method( + self.list_google_api_sources: self._wrap_method( self.list_google_api_sources, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/ListGoogleApiSources", ), - self.create_google_api_source: gapic_v1.method.wrap_method( + self.create_google_api_source: self._wrap_method( self.create_google_api_source, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/CreateGoogleApiSource", ), - self.update_google_api_source: gapic_v1.method.wrap_method( + self.update_google_api_source: self._wrap_method( self.update_google_api_source, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/UpdateGoogleApiSource", ), - self.delete_google_api_source: gapic_v1.method.wrap_method( + self.delete_google_api_source: self._wrap_method( self.delete_google_api_source, default_timeout=None, client_info=client_info, + method_name="google.cloud.eventarc.v1.Eventarc/DeleteGoogleApiSource", ), - self.get_location: gapic_v1.method.wrap_method( + self.get_location: self._wrap_method( self.get_location, default_timeout=None, client_info=client_info, ), - self.list_locations: gapic_v1.method.wrap_method( + self.list_locations: self._wrap_method( self.list_locations, default_timeout=None, client_info=client_info, ), - self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy: self._wrap_method( self.get_iam_policy, default_timeout=None, client_info=client_info, ), - self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy: self._wrap_method( self.set_iam_policy, default_timeout=None, client_info=client_info, ), - self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions: self._wrap_method( self.test_iam_permissions, default_timeout=None, client_info=client_info, ), - self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, ), - self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation: self._wrap_method( self.delete_operation, default_timeout=None, client_info=client_info, ), - self.get_operation: gapic_v1.method.wrap_method( + self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, ), - self.list_operations: gapic_v1.method.wrap_method( + self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py index 37492a456a3c..3bd3e6f759de 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py @@ -26,7 +26,12 @@ # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 +from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +try: + from google.api_core import _observability +except ImportError: # pragma: NO COVER + _observability = None import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -158,6 +163,7 @@ def __init__(self, *, ] ] ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, ) -> None: """Instantiate the transport. @@ -211,6 +217,9 @@ def __init__(self, *, interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): Additional interceptors (or callables that apply interceptors) to apply to the gRPC channel. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -267,6 +276,7 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, api_audience=api_audience, + client_options=client_options, ) if not self._grpc_channel: @@ -288,12 +298,20 @@ def __init__(self, *, ], ) + channel_interceptors = list(interceptors) if interceptors else [] + if ( + _observability is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and otel_interceptor not in channel_interceptors + ): + channel_interceptors.append(otel_interceptor) + apply_interceptors = getattr( grpc_helpers, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py index d1feb6c06e6b..32d94476b8ab 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py @@ -782,9 +782,8 @@ def test_eventarc_client_client_options_from_dict(): def test_eventarc_client_otel_channel_injection_enabled(): - mock_interceptor = mock.Mock() mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = mock_interceptor + mock_obs.is_otel_capabilities_enabled.return_value = True with ( mock.patch( "google.cloud.eventarc_v1.services.eventarc.client._observability", @@ -796,14 +795,14 @@ def test_eventarc_client_otel_channel_injection_enabled(): ): client = EventarcClient(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert called_kwargs.get("interceptors") == [mock_interceptor] + assert called_kwargs.get("client_options") == client._client_options def test_eventarc_client_otel_channel_injection_disabled(): mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = None + mock_obs.is_otel_capabilities_enabled.return_value = False with ( mock.patch( "google.cloud.eventarc_v1.services.eventarc.client._observability", @@ -815,9 +814,9 @@ def test_eventarc_client_otel_channel_injection_disabled(): ): client = EventarcClient(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert not called_kwargs.get("interceptors", []) + assert not called_kwargs.get("client_options") def test_eventarc_grpc_transport_channel_interceptors(): @@ -848,6 +847,42 @@ def test_eventarc_grpc_transport_channel_interceptors(): assert transport.grpc_channel == mock_channel +def test_eventarc_grpc_transport_otel_channel_interceptor(): + mock_otel_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_otel_interceptor + mock_channel = mock.Mock() + + with ( + mock.patch( + "google.cloud.eventarc_v1.services.eventarc.transports.grpc._observability", + mock_obs, + ), + mock.patch.object( + transports.EventarcGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + options = client_options.ClientOptions() + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + + mock_obs.get_otel_interceptor.assert_called_once_with(options) + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_otel_interceptor] + ) + assert transport.grpc_channel == mock_channel + + def test_eventarc_grpc_transport_custom_channel_interceptors(): mock_interceptor = mock.Mock() mock_custom_channel = mock.Mock(spec=grpc.Channel) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py index de57e35ed2ac..0f1870360427 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py @@ -15,6 +15,7 @@ # from collections import OrderedDict from http import HTTPStatus +import inspect import json import logging as std_logging import os @@ -545,21 +546,18 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., ConfigServiceV2Transport], transport) ) - # When OpenTelemetry tracing is enabled, obtain the channel interceptor - # and pass it to the transport. - interceptors = [] + # When OpenTelemetry tracing is enabled, pass client_options to the transport + # so it can wire tracing interceptors and method spans. + client_options = None if ( - isinstance(transport_init, type) - and issubclass(transport_init, ConfigServiceV2GrpcTransport) - and _observability is not None + _observability is not None + and _observability.is_otel_capabilities_enabled(self._client_options) and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) + not isinstance(transport_init, type) + or issubclass(transport_init, ConfigServiceV2GrpcTransport) ) - is not None ): - interceptors.append(otel_interceptor) + client_options = self._client_options # initialize with the provided callable or the passed in class transport_kwargs = { @@ -572,7 +570,7 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"interceptors": interceptors} if interceptors else {}), + **({"client_options": client_options} if client_options else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py index dada98436600..f76b68bfee94 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -14,12 +14,14 @@ # limitations under the License. # import abc +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.logging_v2 import gapic_version as package_version import google.auth # type: ignore import google.api_core +from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries @@ -58,6 +60,7 @@ def __init__( client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -88,6 +91,9 @@ def __init__( to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. """ # Save the scopes. @@ -125,81 +131,115 @@ def __init__( host += ':443' self._host = host + self._client_options = client_options + # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments + # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility + # with older versions of google-api-core. + self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrapped_methods: Dict[Callable, Callable] = {} @property def host(self): return self._host + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_tracing: + kwargs["client_options"] = self._client_options + try: + kwargs["kind"] = self.kind + # Base transport raises NotImplementedError for abstract kind property. + # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + except NotImplementedError: # pragma: NO COVER + pass + return gapic_v1.method.wrap_method(func, *args, **kwargs) + # Remove tracing-specific arguments if older google-api-core is installed + for k in ["client_options", "method_name", "is_streaming", "kind"]: + kwargs.pop(k, None) + return gapic_v1.method.wrap_method(func, *args, **kwargs) + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { - self.list_buckets: gapic_v1.method.wrap_method( + self.list_buckets: self._wrap_method( self.list_buckets, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/ListBuckets", ), - self.get_bucket: gapic_v1.method.wrap_method( + self.get_bucket: self._wrap_method( self.get_bucket, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetBucket", ), - self.create_bucket_async: gapic_v1.method.wrap_method( + self.create_bucket_async: self._wrap_method( self.create_bucket_async, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CreateBucketAsync", ), - self.update_bucket_async: gapic_v1.method.wrap_method( + self.update_bucket_async: self._wrap_method( self.update_bucket_async, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateBucketAsync", ), - self.create_bucket: gapic_v1.method.wrap_method( + self.create_bucket: self._wrap_method( self.create_bucket, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CreateBucket", ), - self.update_bucket: gapic_v1.method.wrap_method( + self.update_bucket: self._wrap_method( self.update_bucket, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateBucket", ), - self.delete_bucket: gapic_v1.method.wrap_method( + self.delete_bucket: self._wrap_method( self.delete_bucket, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/DeleteBucket", ), - self.undelete_bucket: gapic_v1.method.wrap_method( + self.undelete_bucket: self._wrap_method( self.undelete_bucket, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UndeleteBucket", ), - self.list_views: gapic_v1.method.wrap_method( + self.list_views: self._wrap_method( self.list_views, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/ListViews", ), - self.get_view: gapic_v1.method.wrap_method( + self.get_view: self._wrap_method( self.get_view, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetView", ), - self.create_view: gapic_v1.method.wrap_method( + self.create_view: self._wrap_method( self.create_view, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CreateView", ), - self.update_view: gapic_v1.method.wrap_method( + self.update_view: self._wrap_method( self.update_view, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateView", ), - self.delete_view: gapic_v1.method.wrap_method( + self.delete_view: self._wrap_method( self.delete_view, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/DeleteView", ), - self.list_sinks: gapic_v1.method.wrap_method( + self.list_sinks: self._wrap_method( self.list_sinks, default_retry=retries.Retry( initial=0.1, @@ -214,8 +254,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/ListSinks", ), - self.get_sink: gapic_v1.method.wrap_method( + self.get_sink: self._wrap_method( self.get_sink, default_retry=retries.Retry( initial=0.1, @@ -230,13 +271,15 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetSink", ), - self.create_sink: gapic_v1.method.wrap_method( + self.create_sink: self._wrap_method( self.create_sink, default_timeout=120.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CreateSink", ), - self.update_sink: gapic_v1.method.wrap_method( + self.update_sink: self._wrap_method( self.update_sink, default_retry=retries.Retry( initial=0.1, @@ -251,8 +294,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateSink", ), - self.delete_sink: gapic_v1.method.wrap_method( + self.delete_sink: self._wrap_method( self.delete_sink, default_retry=retries.Retry( initial=0.1, @@ -267,28 +311,33 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/DeleteSink", ), - self.create_link: gapic_v1.method.wrap_method( + self.create_link: self._wrap_method( self.create_link, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CreateLink", ), - self.delete_link: gapic_v1.method.wrap_method( + self.delete_link: self._wrap_method( self.delete_link, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/DeleteLink", ), - self.list_links: gapic_v1.method.wrap_method( + self.list_links: self._wrap_method( self.list_links, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/ListLinks", ), - self.get_link: gapic_v1.method.wrap_method( + self.get_link: self._wrap_method( self.get_link, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetLink", ), - self.list_exclusions: gapic_v1.method.wrap_method( + self.list_exclusions: self._wrap_method( self.list_exclusions, default_retry=retries.Retry( initial=0.1, @@ -303,8 +352,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/ListExclusions", ), - self.get_exclusion: gapic_v1.method.wrap_method( + self.get_exclusion: self._wrap_method( self.get_exclusion, default_retry=retries.Retry( initial=0.1, @@ -319,18 +369,21 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetExclusion", ), - self.create_exclusion: gapic_v1.method.wrap_method( + self.create_exclusion: self._wrap_method( self.create_exclusion, default_timeout=120.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CreateExclusion", ), - self.update_exclusion: gapic_v1.method.wrap_method( + self.update_exclusion: self._wrap_method( self.update_exclusion, default_timeout=120.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateExclusion", ), - self.delete_exclusion: gapic_v1.method.wrap_method( + self.delete_exclusion: self._wrap_method( self.delete_exclusion, default_retry=retries.Retry( initial=0.1, @@ -345,43 +398,49 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/DeleteExclusion", ), - self.get_cmek_settings: gapic_v1.method.wrap_method( + self.get_cmek_settings: self._wrap_method( self.get_cmek_settings, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetCmekSettings", ), - self.update_cmek_settings: gapic_v1.method.wrap_method( + self.update_cmek_settings: self._wrap_method( self.update_cmek_settings, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateCmekSettings", ), - self.get_settings: gapic_v1.method.wrap_method( + self.get_settings: self._wrap_method( self.get_settings, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetSettings", ), - self.update_settings: gapic_v1.method.wrap_method( + self.update_settings: self._wrap_method( self.update_settings, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateSettings", ), - self.copy_log_entries: gapic_v1.method.wrap_method( + self.copy_log_entries: self._wrap_method( self.copy_log_entries, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CopyLogEntries", ), - self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, ), - self.get_operation: gapic_v1.method.wrap_method( + self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, ), - self.list_operations: gapic_v1.method.wrap_method( + self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index a984a2b148fa..565161546fb6 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -26,7 +26,12 @@ # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 +from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +try: + from google.api_core import _observability +except ImportError: # pragma: NO COVER + _observability = None import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,6 +149,7 @@ def __init__(self, *, ] ] ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, ) -> None: """Instantiate the transport. @@ -197,6 +203,9 @@ def __init__(self, *, interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): Additional interceptors (or callables that apply interceptors) to apply to the gRPC channel. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -253,6 +262,7 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, api_audience=api_audience, + client_options=client_options, ) if not self._grpc_channel: @@ -274,12 +284,20 @@ def __init__(self, *, ], ) + channel_interceptors = list(interceptors) if interceptors else [] + if ( + _observability is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and otel_interceptor not in channel_interceptors + ): + channel_interceptors.append(otel_interceptor) + apply_interceptors = getattr( grpc_helpers, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py index 9fefe7597513..50469def8e08 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -15,6 +15,7 @@ # from collections import OrderedDict from http import HTTPStatus +import inspect import json import logging as std_logging import os @@ -476,21 +477,18 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., LoggingServiceV2Transport], transport) ) - # When OpenTelemetry tracing is enabled, obtain the channel interceptor - # and pass it to the transport. - interceptors = [] + # When OpenTelemetry tracing is enabled, pass client_options to the transport + # so it can wire tracing interceptors and method spans. + client_options = None if ( - isinstance(transport_init, type) - and issubclass(transport_init, LoggingServiceV2GrpcTransport) - and _observability is not None + _observability is not None + and _observability.is_otel_capabilities_enabled(self._client_options) and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) + not isinstance(transport_init, type) + or issubclass(transport_init, LoggingServiceV2GrpcTransport) ) - is not None ): - interceptors.append(otel_interceptor) + client_options = self._client_options # initialize with the provided callable or the passed in class transport_kwargs = { @@ -503,7 +501,7 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"interceptors": interceptors} if interceptors else {}), + **({"client_options": client_options} if client_options else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index 32f2a037688d..133f00107ae2 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -14,12 +14,14 @@ # limitations under the License. # import abc +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.logging_v2 import gapic_version as package_version import google.auth # type: ignore import google.api_core +from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries @@ -58,6 +60,7 @@ def __init__( client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -88,6 +91,9 @@ def __init__( to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. """ # Save the scopes. @@ -125,16 +131,37 @@ def __init__( host += ':443' self._host = host + self._client_options = client_options + # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments + # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility + # with older versions of google-api-core. + self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrapped_methods: Dict[Callable, Callable] = {} @property def host(self): return self._host + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_tracing: + kwargs["client_options"] = self._client_options + try: + kwargs["kind"] = self.kind + # Base transport raises NotImplementedError for abstract kind property. + # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + except NotImplementedError: # pragma: NO COVER + pass + return gapic_v1.method.wrap_method(func, *args, **kwargs) + # Remove tracing-specific arguments if older google-api-core is installed + for k in ["client_options", "method_name", "is_streaming", "kind"]: + kwargs.pop(k, None) + return gapic_v1.method.wrap_method(func, *args, **kwargs) + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { - self.delete_log: gapic_v1.method.wrap_method( + self.delete_log: self._wrap_method( self.delete_log, default_retry=retries.Retry( initial=0.1, @@ -149,8 +176,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.LoggingServiceV2/DeleteLog", ), - self.write_log_entries: gapic_v1.method.wrap_method( + self.write_log_entries: self._wrap_method( self.write_log_entries, default_retry=retries.Retry( initial=0.1, @@ -165,8 +193,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.LoggingServiceV2/WriteLogEntries", ), - self.list_log_entries: gapic_v1.method.wrap_method( + self.list_log_entries: self._wrap_method( self.list_log_entries, default_retry=retries.Retry( initial=0.1, @@ -181,8 +210,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.LoggingServiceV2/ListLogEntries", ), - self.list_monitored_resource_descriptors: gapic_v1.method.wrap_method( + self.list_monitored_resource_descriptors: self._wrap_method( self.list_monitored_resource_descriptors, default_retry=retries.Retry( initial=0.1, @@ -197,8 +227,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors", ), - self.list_logs: gapic_v1.method.wrap_method( + self.list_logs: self._wrap_method( self.list_logs, default_retry=retries.Retry( initial=0.1, @@ -213,8 +244,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.LoggingServiceV2/ListLogs", ), - self.tail_log_entries: gapic_v1.method.wrap_method( + self.tail_log_entries: self._wrap_method( self.tail_log_entries, default_retry=retries.Retry( initial=0.1, @@ -229,18 +261,20 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=3600.0, client_info=client_info, + method_name="google.logging.v2.LoggingServiceV2/TailLogEntries", + is_streaming=True, ), - self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, ), - self.get_operation: gapic_v1.method.wrap_method( + self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, ), - self.list_operations: gapic_v1.method.wrap_method( + self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index b84d55ab637e..260c3fdb13cd 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -25,7 +25,12 @@ if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +try: + from google.api_core import _observability +except ImportError: # pragma: NO COVER + _observability = None import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -143,6 +148,7 @@ def __init__(self, *, ] ] ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, ) -> None: """Instantiate the transport. @@ -196,6 +202,9 @@ def __init__(self, *, interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): Additional interceptors (or callables that apply interceptors) to apply to the gRPC channel. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -251,6 +260,7 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, api_audience=api_audience, + client_options=client_options, ) if not self._grpc_channel: @@ -272,12 +282,20 @@ def __init__(self, *, ], ) + channel_interceptors = list(interceptors) if interceptors else [] + if ( + _observability is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and otel_interceptor not in channel_interceptors + ): + channel_interceptors.append(otel_interceptor) + apply_interceptors = getattr( grpc_helpers, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py index 0e683c58063f..b8341f860cf0 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -15,6 +15,7 @@ # from collections import OrderedDict from http import HTTPStatus +import inspect import json import logging as std_logging import os @@ -477,21 +478,18 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., MetricsServiceV2Transport], transport) ) - # When OpenTelemetry tracing is enabled, obtain the channel interceptor - # and pass it to the transport. - interceptors = [] + # When OpenTelemetry tracing is enabled, pass client_options to the transport + # so it can wire tracing interceptors and method spans. + client_options = None if ( - isinstance(transport_init, type) - and issubclass(transport_init, MetricsServiceV2GrpcTransport) - and _observability is not None + _observability is not None + and _observability.is_otel_capabilities_enabled(self._client_options) and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) + not isinstance(transport_init, type) + or issubclass(transport_init, MetricsServiceV2GrpcTransport) ) - is not None ): - interceptors.append(otel_interceptor) + client_options = self._client_options # initialize with the provided callable or the passed in class transport_kwargs = { @@ -504,7 +502,7 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"interceptors": interceptors} if interceptors else {}), + **({"client_options": client_options} if client_options else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index f8a9522a02f5..292ad249a3f6 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -14,12 +14,14 @@ # limitations under the License. # import abc +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.logging_v2 import gapic_version as package_version import google.auth # type: ignore import google.api_core +from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries @@ -58,6 +60,7 @@ def __init__( client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -88,6 +91,9 @@ def __init__( to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. """ # Save the scopes. @@ -125,16 +131,37 @@ def __init__( host += ':443' self._host = host + self._client_options = client_options + # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments + # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility + # with older versions of google-api-core. + self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrapped_methods: Dict[Callable, Callable] = {} @property def host(self): return self._host + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_tracing: + kwargs["client_options"] = self._client_options + try: + kwargs["kind"] = self.kind + # Base transport raises NotImplementedError for abstract kind property. + # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + except NotImplementedError: # pragma: NO COVER + pass + return gapic_v1.method.wrap_method(func, *args, **kwargs) + # Remove tracing-specific arguments if older google-api-core is installed + for k in ["client_options", "method_name", "is_streaming", "kind"]: + kwargs.pop(k, None) + return gapic_v1.method.wrap_method(func, *args, **kwargs) + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { - self.list_log_metrics: gapic_v1.method.wrap_method( + self.list_log_metrics: self._wrap_method( self.list_log_metrics, default_retry=retries.Retry( initial=0.1, @@ -149,8 +176,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.MetricsServiceV2/ListLogMetrics", ), - self.get_log_metric: gapic_v1.method.wrap_method( + self.get_log_metric: self._wrap_method( self.get_log_metric, default_retry=retries.Retry( initial=0.1, @@ -165,13 +193,15 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.MetricsServiceV2/GetLogMetric", ), - self.create_log_metric: gapic_v1.method.wrap_method( + self.create_log_metric: self._wrap_method( self.create_log_metric, default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.MetricsServiceV2/CreateLogMetric", ), - self.update_log_metric: gapic_v1.method.wrap_method( + self.update_log_metric: self._wrap_method( self.update_log_metric, default_retry=retries.Retry( initial=0.1, @@ -186,8 +216,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.MetricsServiceV2/UpdateLogMetric", ), - self.delete_log_metric: gapic_v1.method.wrap_method( + self.delete_log_metric: self._wrap_method( self.delete_log_metric, default_retry=retries.Retry( initial=0.1, @@ -202,18 +233,19 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.MetricsServiceV2/DeleteLogMetric", ), - self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, ), - self.get_operation: gapic_v1.method.wrap_method( + self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, ), - self.list_operations: gapic_v1.method.wrap_method( + self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index 68a021a84ba8..c3c51258daa6 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -25,7 +25,12 @@ if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +try: + from google.api_core import _observability +except ImportError: # pragma: NO COVER + _observability = None import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -143,6 +148,7 @@ def __init__(self, *, ] ] ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, ) -> None: """Instantiate the transport. @@ -196,6 +202,9 @@ def __init__(self, *, interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): Additional interceptors (or callables that apply interceptors) to apply to the gRPC channel. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -251,6 +260,7 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, api_audience=api_audience, + client_options=client_options, ) if not self._grpc_channel: @@ -272,12 +282,20 @@ def __init__(self, *, ], ) + channel_interceptors = list(interceptors) if interceptors else [] + if ( + _observability is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and otel_interceptor not in channel_interceptors + ): + channel_interceptors.append(otel_interceptor) + apply_interceptors = getattr( grpc_helpers, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py index 94a39fe4f05c..2e5a7859329b 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -737,9 +737,8 @@ def test_config_service_v2_client_client_options_from_dict(): def test_config_service_v2_client_otel_channel_injection_enabled(): - mock_interceptor = mock.Mock() mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = mock_interceptor + mock_obs.is_otel_capabilities_enabled.return_value = True with ( mock.patch( "google.cloud.logging_v2.services.config_service_v2.client._observability", @@ -751,14 +750,14 @@ def test_config_service_v2_client_otel_channel_injection_enabled(): ): client = ConfigServiceV2Client(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert called_kwargs.get("interceptors") == [mock_interceptor] + assert called_kwargs.get("client_options") == client._client_options def test_config_service_v2_client_otel_channel_injection_disabled(): mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = None + mock_obs.is_otel_capabilities_enabled.return_value = False with ( mock.patch( "google.cloud.logging_v2.services.config_service_v2.client._observability", @@ -770,9 +769,9 @@ def test_config_service_v2_client_otel_channel_injection_disabled(): ): client = ConfigServiceV2Client(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert not called_kwargs.get("interceptors", []) + assert not called_kwargs.get("client_options") def test_config_service_v2_grpc_transport_channel_interceptors(): @@ -803,6 +802,42 @@ def test_config_service_v2_grpc_transport_channel_interceptors(): assert transport.grpc_channel == mock_channel +def test_config_service_v2_grpc_transport_otel_channel_interceptor(): + mock_otel_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_otel_interceptor + mock_channel = mock.Mock() + + with ( + mock.patch( + "google.cloud.logging_v2.services.config_service_v2.transports.grpc._observability", + mock_obs, + ), + mock.patch.object( + transports.ConfigServiceV2GrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + options = client_options.ClientOptions() + transport = transports.ConfigServiceV2GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + + mock_obs.get_otel_interceptor.assert_called_once_with(options) + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_otel_interceptor] + ) + assert transport.grpc_channel == mock_channel + + def test_config_service_v2_grpc_transport_custom_channel_interceptors(): mock_interceptor = mock.Mock() mock_custom_channel = mock.Mock(spec=grpc.Channel) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py index ec398711b928..d6e92d8f7d01 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -738,9 +738,8 @@ def test_logging_service_v2_client_client_options_from_dict(): def test_logging_service_v2_client_otel_channel_injection_enabled(): - mock_interceptor = mock.Mock() mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = mock_interceptor + mock_obs.is_otel_capabilities_enabled.return_value = True with ( mock.patch( "google.cloud.logging_v2.services.logging_service_v2.client._observability", @@ -752,14 +751,14 @@ def test_logging_service_v2_client_otel_channel_injection_enabled(): ): client = LoggingServiceV2Client(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert called_kwargs.get("interceptors") == [mock_interceptor] + assert called_kwargs.get("client_options") == client._client_options def test_logging_service_v2_client_otel_channel_injection_disabled(): mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = None + mock_obs.is_otel_capabilities_enabled.return_value = False with ( mock.patch( "google.cloud.logging_v2.services.logging_service_v2.client._observability", @@ -771,9 +770,9 @@ def test_logging_service_v2_client_otel_channel_injection_disabled(): ): client = LoggingServiceV2Client(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert not called_kwargs.get("interceptors", []) + assert not called_kwargs.get("client_options") def test_logging_service_v2_grpc_transport_channel_interceptors(): @@ -804,6 +803,42 @@ def test_logging_service_v2_grpc_transport_channel_interceptors(): assert transport.grpc_channel == mock_channel +def test_logging_service_v2_grpc_transport_otel_channel_interceptor(): + mock_otel_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_otel_interceptor + mock_channel = mock.Mock() + + with ( + mock.patch( + "google.cloud.logging_v2.services.logging_service_v2.transports.grpc._observability", + mock_obs, + ), + mock.patch.object( + transports.LoggingServiceV2GrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + options = client_options.ClientOptions() + transport = transports.LoggingServiceV2GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + + mock_obs.get_otel_interceptor.assert_called_once_with(options) + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_otel_interceptor] + ) + assert transport.grpc_channel == mock_channel + + def test_logging_service_v2_grpc_transport_custom_channel_interceptors(): mock_interceptor = mock.Mock() mock_custom_channel = mock.Mock(spec=grpc.Channel) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index bc55c44d2a43..63edef5214b7 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -736,9 +736,8 @@ def test_metrics_service_v2_client_client_options_from_dict(): def test_metrics_service_v2_client_otel_channel_injection_enabled(): - mock_interceptor = mock.Mock() mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = mock_interceptor + mock_obs.is_otel_capabilities_enabled.return_value = True with ( mock.patch( "google.cloud.logging_v2.services.metrics_service_v2.client._observability", @@ -750,14 +749,14 @@ def test_metrics_service_v2_client_otel_channel_injection_enabled(): ): client = MetricsServiceV2Client(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert called_kwargs.get("interceptors") == [mock_interceptor] + assert called_kwargs.get("client_options") == client._client_options def test_metrics_service_v2_client_otel_channel_injection_disabled(): mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = None + mock_obs.is_otel_capabilities_enabled.return_value = False with ( mock.patch( "google.cloud.logging_v2.services.metrics_service_v2.client._observability", @@ -769,9 +768,9 @@ def test_metrics_service_v2_client_otel_channel_injection_disabled(): ): client = MetricsServiceV2Client(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert not called_kwargs.get("interceptors", []) + assert not called_kwargs.get("client_options") def test_metrics_service_v2_grpc_transport_channel_interceptors(): @@ -802,6 +801,42 @@ def test_metrics_service_v2_grpc_transport_channel_interceptors(): assert transport.grpc_channel == mock_channel +def test_metrics_service_v2_grpc_transport_otel_channel_interceptor(): + mock_otel_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_otel_interceptor + mock_channel = mock.Mock() + + with ( + mock.patch( + "google.cloud.logging_v2.services.metrics_service_v2.transports.grpc._observability", + mock_obs, + ), + mock.patch.object( + transports.MetricsServiceV2GrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + options = client_options.ClientOptions() + transport = transports.MetricsServiceV2GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + + mock_obs.get_otel_interceptor.assert_called_once_with(options) + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_otel_interceptor] + ) + assert transport.grpc_channel == mock_channel + + def test_metrics_service_v2_grpc_transport_custom_channel_interceptors(): mock_interceptor = mock.Mock() mock_custom_channel = mock.Mock(spec=grpc.Channel) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py index aefac0da88fb..eea18eb4f790 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py @@ -15,6 +15,7 @@ # from collections import OrderedDict from http import HTTPStatus +import inspect import json import logging as std_logging import os @@ -545,21 +546,18 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., ConfigServiceV2Transport], transport) ) - # When OpenTelemetry tracing is enabled, obtain the channel interceptor - # and pass it to the transport. - interceptors = [] + # When OpenTelemetry tracing is enabled, pass client_options to the transport + # so it can wire tracing interceptors and method spans. + client_options = None if ( - isinstance(transport_init, type) - and issubclass(transport_init, ConfigServiceV2GrpcTransport) - and _observability is not None + _observability is not None + and _observability.is_otel_capabilities_enabled(self._client_options) and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) + not isinstance(transport_init, type) + or issubclass(transport_init, ConfigServiceV2GrpcTransport) ) - is not None ): - interceptors.append(otel_interceptor) + client_options = self._client_options # initialize with the provided callable or the passed in class transport_kwargs = { @@ -572,7 +570,7 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"interceptors": interceptors} if interceptors else {}), + **({"client_options": client_options} if client_options else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py index dada98436600..f76b68bfee94 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -14,12 +14,14 @@ # limitations under the License. # import abc +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.logging_v2 import gapic_version as package_version import google.auth # type: ignore import google.api_core +from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries @@ -58,6 +60,7 @@ def __init__( client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -88,6 +91,9 @@ def __init__( to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. """ # Save the scopes. @@ -125,81 +131,115 @@ def __init__( host += ':443' self._host = host + self._client_options = client_options + # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments + # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility + # with older versions of google-api-core. + self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrapped_methods: Dict[Callable, Callable] = {} @property def host(self): return self._host + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_tracing: + kwargs["client_options"] = self._client_options + try: + kwargs["kind"] = self.kind + # Base transport raises NotImplementedError for abstract kind property. + # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + except NotImplementedError: # pragma: NO COVER + pass + return gapic_v1.method.wrap_method(func, *args, **kwargs) + # Remove tracing-specific arguments if older google-api-core is installed + for k in ["client_options", "method_name", "is_streaming", "kind"]: + kwargs.pop(k, None) + return gapic_v1.method.wrap_method(func, *args, **kwargs) + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { - self.list_buckets: gapic_v1.method.wrap_method( + self.list_buckets: self._wrap_method( self.list_buckets, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/ListBuckets", ), - self.get_bucket: gapic_v1.method.wrap_method( + self.get_bucket: self._wrap_method( self.get_bucket, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetBucket", ), - self.create_bucket_async: gapic_v1.method.wrap_method( + self.create_bucket_async: self._wrap_method( self.create_bucket_async, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CreateBucketAsync", ), - self.update_bucket_async: gapic_v1.method.wrap_method( + self.update_bucket_async: self._wrap_method( self.update_bucket_async, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateBucketAsync", ), - self.create_bucket: gapic_v1.method.wrap_method( + self.create_bucket: self._wrap_method( self.create_bucket, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CreateBucket", ), - self.update_bucket: gapic_v1.method.wrap_method( + self.update_bucket: self._wrap_method( self.update_bucket, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateBucket", ), - self.delete_bucket: gapic_v1.method.wrap_method( + self.delete_bucket: self._wrap_method( self.delete_bucket, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/DeleteBucket", ), - self.undelete_bucket: gapic_v1.method.wrap_method( + self.undelete_bucket: self._wrap_method( self.undelete_bucket, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UndeleteBucket", ), - self.list_views: gapic_v1.method.wrap_method( + self.list_views: self._wrap_method( self.list_views, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/ListViews", ), - self.get_view: gapic_v1.method.wrap_method( + self.get_view: self._wrap_method( self.get_view, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetView", ), - self.create_view: gapic_v1.method.wrap_method( + self.create_view: self._wrap_method( self.create_view, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CreateView", ), - self.update_view: gapic_v1.method.wrap_method( + self.update_view: self._wrap_method( self.update_view, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateView", ), - self.delete_view: gapic_v1.method.wrap_method( + self.delete_view: self._wrap_method( self.delete_view, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/DeleteView", ), - self.list_sinks: gapic_v1.method.wrap_method( + self.list_sinks: self._wrap_method( self.list_sinks, default_retry=retries.Retry( initial=0.1, @@ -214,8 +254,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/ListSinks", ), - self.get_sink: gapic_v1.method.wrap_method( + self.get_sink: self._wrap_method( self.get_sink, default_retry=retries.Retry( initial=0.1, @@ -230,13 +271,15 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetSink", ), - self.create_sink: gapic_v1.method.wrap_method( + self.create_sink: self._wrap_method( self.create_sink, default_timeout=120.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CreateSink", ), - self.update_sink: gapic_v1.method.wrap_method( + self.update_sink: self._wrap_method( self.update_sink, default_retry=retries.Retry( initial=0.1, @@ -251,8 +294,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateSink", ), - self.delete_sink: gapic_v1.method.wrap_method( + self.delete_sink: self._wrap_method( self.delete_sink, default_retry=retries.Retry( initial=0.1, @@ -267,28 +311,33 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/DeleteSink", ), - self.create_link: gapic_v1.method.wrap_method( + self.create_link: self._wrap_method( self.create_link, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CreateLink", ), - self.delete_link: gapic_v1.method.wrap_method( + self.delete_link: self._wrap_method( self.delete_link, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/DeleteLink", ), - self.list_links: gapic_v1.method.wrap_method( + self.list_links: self._wrap_method( self.list_links, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/ListLinks", ), - self.get_link: gapic_v1.method.wrap_method( + self.get_link: self._wrap_method( self.get_link, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetLink", ), - self.list_exclusions: gapic_v1.method.wrap_method( + self.list_exclusions: self._wrap_method( self.list_exclusions, default_retry=retries.Retry( initial=0.1, @@ -303,8 +352,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/ListExclusions", ), - self.get_exclusion: gapic_v1.method.wrap_method( + self.get_exclusion: self._wrap_method( self.get_exclusion, default_retry=retries.Retry( initial=0.1, @@ -319,18 +369,21 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetExclusion", ), - self.create_exclusion: gapic_v1.method.wrap_method( + self.create_exclusion: self._wrap_method( self.create_exclusion, default_timeout=120.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CreateExclusion", ), - self.update_exclusion: gapic_v1.method.wrap_method( + self.update_exclusion: self._wrap_method( self.update_exclusion, default_timeout=120.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateExclusion", ), - self.delete_exclusion: gapic_v1.method.wrap_method( + self.delete_exclusion: self._wrap_method( self.delete_exclusion, default_retry=retries.Retry( initial=0.1, @@ -345,43 +398,49 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/DeleteExclusion", ), - self.get_cmek_settings: gapic_v1.method.wrap_method( + self.get_cmek_settings: self._wrap_method( self.get_cmek_settings, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetCmekSettings", ), - self.update_cmek_settings: gapic_v1.method.wrap_method( + self.update_cmek_settings: self._wrap_method( self.update_cmek_settings, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateCmekSettings", ), - self.get_settings: gapic_v1.method.wrap_method( + self.get_settings: self._wrap_method( self.get_settings, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/GetSettings", ), - self.update_settings: gapic_v1.method.wrap_method( + self.update_settings: self._wrap_method( self.update_settings, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/UpdateSettings", ), - self.copy_log_entries: gapic_v1.method.wrap_method( + self.copy_log_entries: self._wrap_method( self.copy_log_entries, default_timeout=None, client_info=client_info, + method_name="google.logging.v2.ConfigServiceV2/CopyLogEntries", ), - self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, ), - self.get_operation: gapic_v1.method.wrap_method( + self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, ), - self.list_operations: gapic_v1.method.wrap_method( + self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index a984a2b148fa..565161546fb6 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -26,7 +26,12 @@ # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 +from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +try: + from google.api_core import _observability +except ImportError: # pragma: NO COVER + _observability = None import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,6 +149,7 @@ def __init__(self, *, ] ] ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, ) -> None: """Instantiate the transport. @@ -197,6 +203,9 @@ def __init__(self, *, interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): Additional interceptors (or callables that apply interceptors) to apply to the gRPC channel. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -253,6 +262,7 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, api_audience=api_audience, + client_options=client_options, ) if not self._grpc_channel: @@ -274,12 +284,20 @@ def __init__(self, *, ], ) + channel_interceptors = list(interceptors) if interceptors else [] + if ( + _observability is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and otel_interceptor not in channel_interceptors + ): + channel_interceptors.append(otel_interceptor) + apply_interceptors = getattr( grpc_helpers, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py index 9fefe7597513..50469def8e08 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -15,6 +15,7 @@ # from collections import OrderedDict from http import HTTPStatus +import inspect import json import logging as std_logging import os @@ -476,21 +477,18 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., LoggingServiceV2Transport], transport) ) - # When OpenTelemetry tracing is enabled, obtain the channel interceptor - # and pass it to the transport. - interceptors = [] + # When OpenTelemetry tracing is enabled, pass client_options to the transport + # so it can wire tracing interceptors and method spans. + client_options = None if ( - isinstance(transport_init, type) - and issubclass(transport_init, LoggingServiceV2GrpcTransport) - and _observability is not None + _observability is not None + and _observability.is_otel_capabilities_enabled(self._client_options) and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) + not isinstance(transport_init, type) + or issubclass(transport_init, LoggingServiceV2GrpcTransport) ) - is not None ): - interceptors.append(otel_interceptor) + client_options = self._client_options # initialize with the provided callable or the passed in class transport_kwargs = { @@ -503,7 +501,7 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"interceptors": interceptors} if interceptors else {}), + **({"client_options": client_options} if client_options else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index 32f2a037688d..133f00107ae2 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -14,12 +14,14 @@ # limitations under the License. # import abc +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.logging_v2 import gapic_version as package_version import google.auth # type: ignore import google.api_core +from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries @@ -58,6 +60,7 @@ def __init__( client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -88,6 +91,9 @@ def __init__( to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. """ # Save the scopes. @@ -125,16 +131,37 @@ def __init__( host += ':443' self._host = host + self._client_options = client_options + # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments + # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility + # with older versions of google-api-core. + self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrapped_methods: Dict[Callable, Callable] = {} @property def host(self): return self._host + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_tracing: + kwargs["client_options"] = self._client_options + try: + kwargs["kind"] = self.kind + # Base transport raises NotImplementedError for abstract kind property. + # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + except NotImplementedError: # pragma: NO COVER + pass + return gapic_v1.method.wrap_method(func, *args, **kwargs) + # Remove tracing-specific arguments if older google-api-core is installed + for k in ["client_options", "method_name", "is_streaming", "kind"]: + kwargs.pop(k, None) + return gapic_v1.method.wrap_method(func, *args, **kwargs) + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { - self.delete_log: gapic_v1.method.wrap_method( + self.delete_log: self._wrap_method( self.delete_log, default_retry=retries.Retry( initial=0.1, @@ -149,8 +176,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.LoggingServiceV2/DeleteLog", ), - self.write_log_entries: gapic_v1.method.wrap_method( + self.write_log_entries: self._wrap_method( self.write_log_entries, default_retry=retries.Retry( initial=0.1, @@ -165,8 +193,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.LoggingServiceV2/WriteLogEntries", ), - self.list_log_entries: gapic_v1.method.wrap_method( + self.list_log_entries: self._wrap_method( self.list_log_entries, default_retry=retries.Retry( initial=0.1, @@ -181,8 +210,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.LoggingServiceV2/ListLogEntries", ), - self.list_monitored_resource_descriptors: gapic_v1.method.wrap_method( + self.list_monitored_resource_descriptors: self._wrap_method( self.list_monitored_resource_descriptors, default_retry=retries.Retry( initial=0.1, @@ -197,8 +227,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors", ), - self.list_logs: gapic_v1.method.wrap_method( + self.list_logs: self._wrap_method( self.list_logs, default_retry=retries.Retry( initial=0.1, @@ -213,8 +244,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.LoggingServiceV2/ListLogs", ), - self.tail_log_entries: gapic_v1.method.wrap_method( + self.tail_log_entries: self._wrap_method( self.tail_log_entries, default_retry=retries.Retry( initial=0.1, @@ -229,18 +261,20 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=3600.0, client_info=client_info, + method_name="google.logging.v2.LoggingServiceV2/TailLogEntries", + is_streaming=True, ), - self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, ), - self.get_operation: gapic_v1.method.wrap_method( + self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, ), - self.list_operations: gapic_v1.method.wrap_method( + self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index b84d55ab637e..260c3fdb13cd 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -25,7 +25,12 @@ if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +try: + from google.api_core import _observability +except ImportError: # pragma: NO COVER + _observability = None import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -143,6 +148,7 @@ def __init__(self, *, ] ] ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, ) -> None: """Instantiate the transport. @@ -196,6 +202,9 @@ def __init__(self, *, interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): Additional interceptors (or callables that apply interceptors) to apply to the gRPC channel. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -251,6 +260,7 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, api_audience=api_audience, + client_options=client_options, ) if not self._grpc_channel: @@ -272,12 +282,20 @@ def __init__(self, *, ], ) + channel_interceptors = list(interceptors) if interceptors else [] + if ( + _observability is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and otel_interceptor not in channel_interceptors + ): + channel_interceptors.append(otel_interceptor) + apply_interceptors = getattr( grpc_helpers, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py index c636aaca7e86..754b29849c6b 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -15,6 +15,7 @@ # from collections import OrderedDict from http import HTTPStatus +import inspect import json import logging as std_logging import os @@ -477,21 +478,18 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., MetricsServiceV2Transport], transport) ) - # When OpenTelemetry tracing is enabled, obtain the channel interceptor - # and pass it to the transport. - interceptors = [] + # When OpenTelemetry tracing is enabled, pass client_options to the transport + # so it can wire tracing interceptors and method spans. + client_options = None if ( - isinstance(transport_init, type) - and issubclass(transport_init, MetricsServiceV2GrpcTransport) - and _observability is not None + _observability is not None + and _observability.is_otel_capabilities_enabled(self._client_options) and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) + not isinstance(transport_init, type) + or issubclass(transport_init, MetricsServiceV2GrpcTransport) ) - is not None ): - interceptors.append(otel_interceptor) + client_options = self._client_options # initialize with the provided callable or the passed in class transport_kwargs = { @@ -504,7 +502,7 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"interceptors": interceptors} if interceptors else {}), + **({"client_options": client_options} if client_options else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index f8a9522a02f5..292ad249a3f6 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -14,12 +14,14 @@ # limitations under the License. # import abc +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.logging_v2 import gapic_version as package_version import google.auth # type: ignore import google.api_core +from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries @@ -58,6 +60,7 @@ def __init__( client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -88,6 +91,9 @@ def __init__( to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. """ # Save the scopes. @@ -125,16 +131,37 @@ def __init__( host += ':443' self._host = host + self._client_options = client_options + # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments + # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility + # with older versions of google-api-core. + self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrapped_methods: Dict[Callable, Callable] = {} @property def host(self): return self._host + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_tracing: + kwargs["client_options"] = self._client_options + try: + kwargs["kind"] = self.kind + # Base transport raises NotImplementedError for abstract kind property. + # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + except NotImplementedError: # pragma: NO COVER + pass + return gapic_v1.method.wrap_method(func, *args, **kwargs) + # Remove tracing-specific arguments if older google-api-core is installed + for k in ["client_options", "method_name", "is_streaming", "kind"]: + kwargs.pop(k, None) + return gapic_v1.method.wrap_method(func, *args, **kwargs) + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { - self.list_log_metrics: gapic_v1.method.wrap_method( + self.list_log_metrics: self._wrap_method( self.list_log_metrics, default_retry=retries.Retry( initial=0.1, @@ -149,8 +176,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.MetricsServiceV2/ListLogMetrics", ), - self.get_log_metric: gapic_v1.method.wrap_method( + self.get_log_metric: self._wrap_method( self.get_log_metric, default_retry=retries.Retry( initial=0.1, @@ -165,13 +193,15 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.MetricsServiceV2/GetLogMetric", ), - self.create_log_metric: gapic_v1.method.wrap_method( + self.create_log_metric: self._wrap_method( self.create_log_metric, default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.MetricsServiceV2/CreateLogMetric", ), - self.update_log_metric: gapic_v1.method.wrap_method( + self.update_log_metric: self._wrap_method( self.update_log_metric, default_retry=retries.Retry( initial=0.1, @@ -186,8 +216,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.MetricsServiceV2/UpdateLogMetric", ), - self.delete_log_metric: gapic_v1.method.wrap_method( + self.delete_log_metric: self._wrap_method( self.delete_log_metric, default_retry=retries.Retry( initial=0.1, @@ -202,18 +233,19 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.logging.v2.MetricsServiceV2/DeleteLogMetric", ), - self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, ), - self.get_operation: gapic_v1.method.wrap_method( + self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, ), - self.list_operations: gapic_v1.method.wrap_method( + self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index 68a021a84ba8..c3c51258daa6 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -25,7 +25,12 @@ if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +try: + from google.api_core import _observability +except ImportError: # pragma: NO COVER + _observability = None import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -143,6 +148,7 @@ def __init__(self, *, ] ] ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, ) -> None: """Instantiate the transport. @@ -196,6 +202,9 @@ def __init__(self, *, interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): Additional interceptors (or callables that apply interceptors) to apply to the gRPC channel. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -251,6 +260,7 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, api_audience=api_audience, + client_options=client_options, ) if not self._grpc_channel: @@ -272,12 +282,20 @@ def __init__(self, *, ], ) + channel_interceptors = list(interceptors) if interceptors else [] + if ( + _observability is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and otel_interceptor not in channel_interceptors + ): + channel_interceptors.append(otel_interceptor) + apply_interceptors = getattr( grpc_helpers, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py index e6de5df4ceaf..4f0b7e4ab632 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -737,9 +737,8 @@ def test_base_config_service_v2_client_client_options_from_dict(): def test_base_config_service_v2_client_otel_channel_injection_enabled(): - mock_interceptor = mock.Mock() mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = mock_interceptor + mock_obs.is_otel_capabilities_enabled.return_value = True with ( mock.patch( "google.cloud.logging_v2.services.config_service_v2.client._observability", @@ -751,14 +750,14 @@ def test_base_config_service_v2_client_otel_channel_injection_enabled(): ): client = BaseConfigServiceV2Client(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert called_kwargs.get("interceptors") == [mock_interceptor] + assert called_kwargs.get("client_options") == client._client_options def test_base_config_service_v2_client_otel_channel_injection_disabled(): mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = None + mock_obs.is_otel_capabilities_enabled.return_value = False with ( mock.patch( "google.cloud.logging_v2.services.config_service_v2.client._observability", @@ -770,9 +769,9 @@ def test_base_config_service_v2_client_otel_channel_injection_disabled(): ): client = BaseConfigServiceV2Client(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert not called_kwargs.get("interceptors", []) + assert not called_kwargs.get("client_options") def test_config_service_v2_grpc_transport_channel_interceptors(): @@ -803,6 +802,42 @@ def test_config_service_v2_grpc_transport_channel_interceptors(): assert transport.grpc_channel == mock_channel +def test_config_service_v2_grpc_transport_otel_channel_interceptor(): + mock_otel_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_otel_interceptor + mock_channel = mock.Mock() + + with ( + mock.patch( + "google.cloud.logging_v2.services.config_service_v2.transports.grpc._observability", + mock_obs, + ), + mock.patch.object( + transports.ConfigServiceV2GrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + options = client_options.ClientOptions() + transport = transports.ConfigServiceV2GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + + mock_obs.get_otel_interceptor.assert_called_once_with(options) + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_otel_interceptor] + ) + assert transport.grpc_channel == mock_channel + + def test_config_service_v2_grpc_transport_custom_channel_interceptors(): mock_interceptor = mock.Mock() mock_custom_channel = mock.Mock(spec=grpc.Channel) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py index ec398711b928..d6e92d8f7d01 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -738,9 +738,8 @@ def test_logging_service_v2_client_client_options_from_dict(): def test_logging_service_v2_client_otel_channel_injection_enabled(): - mock_interceptor = mock.Mock() mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = mock_interceptor + mock_obs.is_otel_capabilities_enabled.return_value = True with ( mock.patch( "google.cloud.logging_v2.services.logging_service_v2.client._observability", @@ -752,14 +751,14 @@ def test_logging_service_v2_client_otel_channel_injection_enabled(): ): client = LoggingServiceV2Client(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert called_kwargs.get("interceptors") == [mock_interceptor] + assert called_kwargs.get("client_options") == client._client_options def test_logging_service_v2_client_otel_channel_injection_disabled(): mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = None + mock_obs.is_otel_capabilities_enabled.return_value = False with ( mock.patch( "google.cloud.logging_v2.services.logging_service_v2.client._observability", @@ -771,9 +770,9 @@ def test_logging_service_v2_client_otel_channel_injection_disabled(): ): client = LoggingServiceV2Client(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert not called_kwargs.get("interceptors", []) + assert not called_kwargs.get("client_options") def test_logging_service_v2_grpc_transport_channel_interceptors(): @@ -804,6 +803,42 @@ def test_logging_service_v2_grpc_transport_channel_interceptors(): assert transport.grpc_channel == mock_channel +def test_logging_service_v2_grpc_transport_otel_channel_interceptor(): + mock_otel_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_otel_interceptor + mock_channel = mock.Mock() + + with ( + mock.patch( + "google.cloud.logging_v2.services.logging_service_v2.transports.grpc._observability", + mock_obs, + ), + mock.patch.object( + transports.LoggingServiceV2GrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + options = client_options.ClientOptions() + transport = transports.LoggingServiceV2GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + + mock_obs.get_otel_interceptor.assert_called_once_with(options) + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_otel_interceptor] + ) + assert transport.grpc_channel == mock_channel + + def test_logging_service_v2_grpc_transport_custom_channel_interceptors(): mock_interceptor = mock.Mock() mock_custom_channel = mock.Mock(spec=grpc.Channel) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index 59ceebba8a28..c9733a911372 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -736,9 +736,8 @@ def test_base_metrics_service_v2_client_client_options_from_dict(): def test_base_metrics_service_v2_client_otel_channel_injection_enabled(): - mock_interceptor = mock.Mock() mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = mock_interceptor + mock_obs.is_otel_capabilities_enabled.return_value = True with ( mock.patch( "google.cloud.logging_v2.services.metrics_service_v2.client._observability", @@ -750,14 +749,14 @@ def test_base_metrics_service_v2_client_otel_channel_injection_enabled(): ): client = BaseMetricsServiceV2Client(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert called_kwargs.get("interceptors") == [mock_interceptor] + assert called_kwargs.get("client_options") == client._client_options def test_base_metrics_service_v2_client_otel_channel_injection_disabled(): mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = None + mock_obs.is_otel_capabilities_enabled.return_value = False with ( mock.patch( "google.cloud.logging_v2.services.metrics_service_v2.client._observability", @@ -769,9 +768,9 @@ def test_base_metrics_service_v2_client_otel_channel_injection_disabled(): ): client = BaseMetricsServiceV2Client(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert not called_kwargs.get("interceptors", []) + assert not called_kwargs.get("client_options") def test_metrics_service_v2_grpc_transport_channel_interceptors(): @@ -802,6 +801,42 @@ def test_metrics_service_v2_grpc_transport_channel_interceptors(): assert transport.grpc_channel == mock_channel +def test_metrics_service_v2_grpc_transport_otel_channel_interceptor(): + mock_otel_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_otel_interceptor + mock_channel = mock.Mock() + + with ( + mock.patch( + "google.cloud.logging_v2.services.metrics_service_v2.transports.grpc._observability", + mock_obs, + ), + mock.patch.object( + transports.MetricsServiceV2GrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + options = client_options.ClientOptions() + transport = transports.MetricsServiceV2GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + + mock_obs.get_otel_interceptor.assert_called_once_with(options) + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_otel_interceptor] + ) + assert transport.grpc_channel == mock_channel + + def test_metrics_service_v2_grpc_transport_custom_channel_interceptors(): mock_interceptor = mock.Mock() mock_custom_channel = mock.Mock(spec=grpc.Channel) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py index e8f258ff21d3..dfd1e7898250 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -15,6 +15,7 @@ # from collections import OrderedDict from http import HTTPStatus +import inspect import json import logging as std_logging import os @@ -539,21 +540,18 @@ def __init__(self, *, if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): credentials = google.auth._default.get_api_key_credentials(api_key_value) - # When OpenTelemetry tracing is enabled, obtain the channel interceptor - # and pass it to the transport. - interceptors = [] + # When OpenTelemetry tracing is enabled, pass client_options to the transport + # so it can wire tracing interceptors and method spans. + client_options = None if ( - isinstance(transport_init, type) - and issubclass(transport_init, CloudRedisGrpcTransport) - and _observability is not None + _observability is not None + and _observability.is_otel_capabilities_enabled(self._client_options) and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) + not isinstance(transport_init, type) + or issubclass(transport_init, CloudRedisGrpcTransport) ) - is not None ): - interceptors.append(otel_interceptor) + client_options = self._client_options # initialize with the provided callable or the passed in class transport_kwargs = { @@ -566,7 +564,7 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"interceptors": interceptors} if interceptors else {}), + **({"client_options": client_options} if client_options else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py index 8e015f903a92..a46f83e02401 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -14,12 +14,14 @@ # limitations under the License. # import abc +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.redis_v1 import gapic_version as package_version import google.auth # type: ignore import google.api_core +from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries @@ -55,6 +57,7 @@ def __init__( client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -85,6 +88,9 @@ def __init__( to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. """ # Save the scopes. @@ -122,101 +128,133 @@ def __init__( host += ':443' self._host = host + self._client_options = client_options + # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments + # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility + # with older versions of google-api-core. + self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrapped_methods: Dict[Callable, Callable] = {} @property def host(self): return self._host + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_tracing: + kwargs["client_options"] = self._client_options + try: + kwargs["kind"] = self.kind + # Base transport raises NotImplementedError for abstract kind property. + # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + except NotImplementedError: # pragma: NO COVER + pass + return gapic_v1.method.wrap_method(func, *args, **kwargs) + # Remove tracing-specific arguments if older google-api-core is installed + for k in ["client_options", "method_name", "is_streaming", "kind"]: + kwargs.pop(k, None) + return gapic_v1.method.wrap_method(func, *args, **kwargs) + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { - self.list_instances: gapic_v1.method.wrap_method( + self.list_instances: self._wrap_method( self.list_instances, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/ListInstances", ), - self.get_instance: gapic_v1.method.wrap_method( + self.get_instance: self._wrap_method( self.get_instance, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/GetInstance", ), - self.get_instance_auth_string: gapic_v1.method.wrap_method( + self.get_instance_auth_string: self._wrap_method( self.get_instance_auth_string, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/GetInstanceAuthString", ), - self.create_instance: gapic_v1.method.wrap_method( + self.create_instance: self._wrap_method( self.create_instance, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/CreateInstance", ), - self.update_instance: gapic_v1.method.wrap_method( + self.update_instance: self._wrap_method( self.update_instance, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/UpdateInstance", ), - self.upgrade_instance: gapic_v1.method.wrap_method( + self.upgrade_instance: self._wrap_method( self.upgrade_instance, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/UpgradeInstance", ), - self.import_instance: gapic_v1.method.wrap_method( + self.import_instance: self._wrap_method( self.import_instance, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/ImportInstance", ), - self.export_instance: gapic_v1.method.wrap_method( + self.export_instance: self._wrap_method( self.export_instance, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/ExportInstance", ), - self.failover_instance: gapic_v1.method.wrap_method( + self.failover_instance: self._wrap_method( self.failover_instance, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/FailoverInstance", ), - self.delete_instance: gapic_v1.method.wrap_method( + self.delete_instance: self._wrap_method( self.delete_instance, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/DeleteInstance", ), - self.reschedule_maintenance: gapic_v1.method.wrap_method( + self.reschedule_maintenance: self._wrap_method( self.reschedule_maintenance, default_timeout=None, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/RescheduleMaintenance", ), - self.get_location: gapic_v1.method.wrap_method( + self.get_location: self._wrap_method( self.get_location, default_timeout=None, client_info=client_info, ), - self.list_locations: gapic_v1.method.wrap_method( + self.list_locations: self._wrap_method( self.list_locations, default_timeout=None, client_info=client_info, ), - self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, ), - self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation: self._wrap_method( self.delete_operation, default_timeout=None, client_info=client_info, ), - self.get_operation: gapic_v1.method.wrap_method( + self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, ), - self.list_operations: gapic_v1.method.wrap_method( + self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, ), - self.wait_operation: gapic_v1.method.wrap_method( + self.wait_operation: self._wrap_method( self.wait_operation, default_timeout=None, client_info=client_info, diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index df9d22081945..015ac807c15b 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -26,7 +26,12 @@ # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 +from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +try: + from google.api_core import _observability +except ImportError: # pragma: NO COVER + _observability = None import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -164,6 +169,7 @@ def __init__(self, *, ] ] ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, ) -> None: """Instantiate the transport. @@ -217,6 +223,9 @@ def __init__(self, *, interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): Additional interceptors (or callables that apply interceptors) to apply to the gRPC channel. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -273,6 +282,7 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, api_audience=api_audience, + client_options=client_options, ) if not self._grpc_channel: @@ -294,12 +304,20 @@ def __init__(self, *, ], ) + channel_interceptors = list(interceptors) if interceptors else [] + if ( + _observability is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and otel_interceptor not in channel_interceptors + ): + channel_interceptors.append(otel_interceptor) + apply_interceptors = getattr( grpc_helpers, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py index 632bd64909f4..2319eb5eaf30 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -769,9 +769,8 @@ def test_cloud_redis_client_client_options_from_dict(): def test_cloud_redis_client_otel_channel_injection_enabled(): - mock_interceptor = mock.Mock() mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = mock_interceptor + mock_obs.is_otel_capabilities_enabled.return_value = True with ( mock.patch( "google.cloud.redis_v1.services.cloud_redis.client._observability", @@ -783,14 +782,14 @@ def test_cloud_redis_client_otel_channel_injection_enabled(): ): client = CloudRedisClient(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert called_kwargs.get("interceptors") == [mock_interceptor] + assert called_kwargs.get("client_options") == client._client_options def test_cloud_redis_client_otel_channel_injection_disabled(): mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = None + mock_obs.is_otel_capabilities_enabled.return_value = False with ( mock.patch( "google.cloud.redis_v1.services.cloud_redis.client._observability", @@ -802,9 +801,9 @@ def test_cloud_redis_client_otel_channel_injection_disabled(): ): client = CloudRedisClient(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert not called_kwargs.get("interceptors", []) + assert not called_kwargs.get("client_options") def test_cloud_redis_grpc_transport_channel_interceptors(): @@ -835,6 +834,42 @@ def test_cloud_redis_grpc_transport_channel_interceptors(): assert transport.grpc_channel == mock_channel +def test_cloud_redis_grpc_transport_otel_channel_interceptor(): + mock_otel_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_otel_interceptor + mock_channel = mock.Mock() + + with ( + mock.patch( + "google.cloud.redis_v1.services.cloud_redis.transports.grpc._observability", + mock_obs, + ), + mock.patch.object( + transports.CloudRedisGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + options = client_options.ClientOptions() + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + + mock_obs.get_otel_interceptor.assert_called_once_with(options) + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_otel_interceptor] + ) + assert transport.grpc_channel == mock_channel + + def test_cloud_redis_grpc_transport_custom_channel_interceptors(): mock_interceptor = mock.Mock() mock_custom_channel = mock.Mock(spec=grpc.Channel) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py index 828f6d48211e..a79874b447b3 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py @@ -15,6 +15,7 @@ # from collections import OrderedDict from http import HTTPStatus +import inspect import json import logging as std_logging import os @@ -539,21 +540,18 @@ def __init__(self, *, if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): credentials = google.auth._default.get_api_key_credentials(api_key_value) - # When OpenTelemetry tracing is enabled, obtain the channel interceptor - # and pass it to the transport. - interceptors = [] + # When OpenTelemetry tracing is enabled, pass client_options to the transport + # so it can wire tracing interceptors and method spans. + client_options = None if ( - isinstance(transport_init, type) - and issubclass(transport_init, CloudRedisGrpcTransport) - and _observability is not None + _observability is not None + and _observability.is_otel_capabilities_enabled(self._client_options) and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) + not isinstance(transport_init, type) + or issubclass(transport_init, CloudRedisGrpcTransport) ) - is not None ): - interceptors.append(otel_interceptor) + client_options = self._client_options # initialize with the provided callable or the passed in class transport_kwargs = { @@ -566,7 +564,7 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"interceptors": interceptors} if interceptors else {}), + **({"client_options": client_options} if client_options else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py index 8b9a24ec87fa..3e441f674d6f 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -14,12 +14,14 @@ # limitations under the License. # import abc +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.redis_v1 import gapic_version as package_version import google.auth # type: ignore import google.api_core +from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries @@ -55,6 +57,7 @@ def __init__( client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -85,6 +88,9 @@ def __init__( to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. """ # Save the scopes. @@ -122,71 +128,97 @@ def __init__( host += ':443' self._host = host + self._client_options = client_options + # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments + # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility + # with older versions of google-api-core. + self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrapped_methods: Dict[Callable, Callable] = {} @property def host(self): return self._host + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_tracing: + kwargs["client_options"] = self._client_options + try: + kwargs["kind"] = self.kind + # Base transport raises NotImplementedError for abstract kind property. + # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + except NotImplementedError: # pragma: NO COVER + pass + return gapic_v1.method.wrap_method(func, *args, **kwargs) + # Remove tracing-specific arguments if older google-api-core is installed + for k in ["client_options", "method_name", "is_streaming", "kind"]: + kwargs.pop(k, None) + return gapic_v1.method.wrap_method(func, *args, **kwargs) + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { - self.list_instances: gapic_v1.method.wrap_method( + self.list_instances: self._wrap_method( self.list_instances, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/ListInstances", ), - self.get_instance: gapic_v1.method.wrap_method( + self.get_instance: self._wrap_method( self.get_instance, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/GetInstance", ), - self.create_instance: gapic_v1.method.wrap_method( + self.create_instance: self._wrap_method( self.create_instance, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/CreateInstance", ), - self.update_instance: gapic_v1.method.wrap_method( + self.update_instance: self._wrap_method( self.update_instance, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/UpdateInstance", ), - self.delete_instance: gapic_v1.method.wrap_method( + self.delete_instance: self._wrap_method( self.delete_instance, default_timeout=600.0, client_info=client_info, + method_name="google.cloud.redis.v1.CloudRedis/DeleteInstance", ), - self.get_location: gapic_v1.method.wrap_method( + self.get_location: self._wrap_method( self.get_location, default_timeout=None, client_info=client_info, ), - self.list_locations: gapic_v1.method.wrap_method( + self.list_locations: self._wrap_method( self.list_locations, default_timeout=None, client_info=client_info, ), - self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, ), - self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation: self._wrap_method( self.delete_operation, default_timeout=None, client_info=client_info, ), - self.get_operation: gapic_v1.method.wrap_method( + self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, ), - self.list_operations: gapic_v1.method.wrap_method( + self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, ), - self.wait_operation: gapic_v1.method.wrap_method( + self.wait_operation: self._wrap_method( self.wait_operation, default_timeout=None, client_info=client_info, diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index 448117af19b0..21dbcdda42f4 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -26,7 +26,12 @@ # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 +from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +try: + from google.api_core import _observability +except ImportError: # pragma: NO COVER + _observability = None import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -164,6 +169,7 @@ def __init__(self, *, ] ] ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, ) -> None: """Instantiate the transport. @@ -217,6 +223,9 @@ def __init__(self, *, interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): Additional interceptors (or callables that apply interceptors) to apply to the gRPC channel. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -273,6 +282,7 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, api_audience=api_audience, + client_options=client_options, ) if not self._grpc_channel: @@ -294,12 +304,20 @@ def __init__(self, *, ], ) + channel_interceptors = list(interceptors) if interceptors else [] + if ( + _observability is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and otel_interceptor not in channel_interceptors + ): + channel_interceptors.append(otel_interceptor) + apply_interceptors = getattr( grpc_helpers, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py index 9094b0af41d2..7b968b378489 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -769,9 +769,8 @@ def test_cloud_redis_client_client_options_from_dict(): def test_cloud_redis_client_otel_channel_injection_enabled(): - mock_interceptor = mock.Mock() mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = mock_interceptor + mock_obs.is_otel_capabilities_enabled.return_value = True with ( mock.patch( "google.cloud.redis_v1.services.cloud_redis.client._observability", @@ -783,14 +782,14 @@ def test_cloud_redis_client_otel_channel_injection_enabled(): ): client = CloudRedisClient(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert called_kwargs.get("interceptors") == [mock_interceptor] + assert called_kwargs.get("client_options") == client._client_options def test_cloud_redis_client_otel_channel_injection_disabled(): mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = None + mock_obs.is_otel_capabilities_enabled.return_value = False with ( mock.patch( "google.cloud.redis_v1.services.cloud_redis.client._observability", @@ -802,9 +801,9 @@ def test_cloud_redis_client_otel_channel_injection_disabled(): ): client = CloudRedisClient(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert not called_kwargs.get("interceptors", []) + assert not called_kwargs.get("client_options") def test_cloud_redis_grpc_transport_channel_interceptors(): @@ -835,6 +834,42 @@ def test_cloud_redis_grpc_transport_channel_interceptors(): assert transport.grpc_channel == mock_channel +def test_cloud_redis_grpc_transport_otel_channel_interceptor(): + mock_otel_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_otel_interceptor + mock_channel = mock.Mock() + + with ( + mock.patch( + "google.cloud.redis_v1.services.cloud_redis.transports.grpc._observability", + mock_obs, + ), + mock.patch.object( + transports.CloudRedisGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + options = client_options.ClientOptions() + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + + mock_obs.get_otel_interceptor.assert_called_once_with(options) + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_otel_interceptor] + ) + assert transport.grpc_channel == mock_channel + + def test_cloud_redis_grpc_transport_custom_channel_interceptors(): mock_interceptor = mock.Mock() mock_custom_channel = mock.Mock(spec=grpc.Channel) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py index 448ac3f79873..de2135721571 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py @@ -15,6 +15,7 @@ # from collections import OrderedDict from http import HTTPStatus +import inspect import json import logging as std_logging import os @@ -513,21 +514,18 @@ def __init__(self, *, if isinstance(transport, str) or transport is None else cast(Callable[..., StorageBatchOperationsTransport], transport) ) - # When OpenTelemetry tracing is enabled, obtain the channel interceptor - # and pass it to the transport. - interceptors = [] + # When OpenTelemetry tracing is enabled, pass client_options to the transport + # so it can wire tracing interceptors and method spans. + client_options = None if ( - isinstance(transport_init, type) - and issubclass(transport_init, StorageBatchOperationsGrpcTransport) - and _observability is not None + _observability is not None + and _observability.is_otel_capabilities_enabled(self._client_options) and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) + not isinstance(transport_init, type) + or issubclass(transport_init, StorageBatchOperationsGrpcTransport) ) - is not None ): - interceptors.append(otel_interceptor) + client_options = self._client_options # initialize with the provided callable or the passed in class transport_kwargs = { @@ -540,7 +538,7 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"interceptors": interceptors} if interceptors else {}), + **({"client_options": client_options} if client_options else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py index 1b5920f9153c..f7b33ea11619 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py @@ -14,12 +14,14 @@ # limitations under the License. # import abc +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.cloud.storagebatchoperations_v1 import gapic_version as package_version import google.auth # type: ignore import google.api_core +from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries @@ -57,6 +59,7 @@ def __init__( client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -87,6 +90,9 @@ def __init__( to the service that will be set when using certain 3rd party authentication flows. Audience is typically a resource identifier. If not set, the host value will be used as a default. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. """ # Save the scopes. @@ -124,16 +130,37 @@ def __init__( host += ':443' self._host = host + self._client_options = client_options + # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments + # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility + # with older versions of google-api-core. + self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrapped_methods: Dict[Callable, Callable] = {} @property def host(self): return self._host + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_tracing: + kwargs["client_options"] = self._client_options + try: + kwargs["kind"] = self.kind + # Base transport raises NotImplementedError for abstract kind property. + # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + except NotImplementedError: # pragma: NO COVER + pass + return gapic_v1.method.wrap_method(func, *args, **kwargs) + # Remove tracing-specific arguments if older google-api-core is installed + for k in ["client_options", "method_name", "is_streaming", "kind"]: + kwargs.pop(k, None) + return gapic_v1.method.wrap_method(func, *args, **kwargs) + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { - self.list_jobs: gapic_v1.method.wrap_method( + self.list_jobs: self._wrap_method( self.list_jobs, default_retry=retries.Retry( initial=1.0, @@ -146,8 +173,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.cloud.storagebatchoperations.v1.StorageBatchOperations/ListJobs", ), - self.get_job: gapic_v1.method.wrap_method( + self.get_job: self._wrap_method( self.get_job, default_retry=retries.Retry( initial=1.0, @@ -160,18 +188,21 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.cloud.storagebatchoperations.v1.StorageBatchOperations/GetJob", ), - self.create_job: gapic_v1.method.wrap_method( + self.create_job: self._wrap_method( self.create_job, default_timeout=60.0, client_info=client_info, + method_name="google.cloud.storagebatchoperations.v1.StorageBatchOperations/CreateJob", ), - self.delete_job: gapic_v1.method.wrap_method( + self.delete_job: self._wrap_method( self.delete_job, default_timeout=60.0, client_info=client_info, + method_name="google.cloud.storagebatchoperations.v1.StorageBatchOperations/DeleteJob", ), - self.cancel_job: gapic_v1.method.wrap_method( + self.cancel_job: self._wrap_method( self.cancel_job, default_retry=retries.Retry( initial=1.0, @@ -184,8 +215,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.cloud.storagebatchoperations.v1.StorageBatchOperations/CancelJob", ), - self.list_bucket_operations: gapic_v1.method.wrap_method( + self.list_bucket_operations: self._wrap_method( self.list_bucket_operations, default_retry=retries.Retry( initial=1.0, @@ -198,8 +230,9 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.cloud.storagebatchoperations.v1.StorageBatchOperations/ListBucketOperations", ), - self.get_bucket_operation: gapic_v1.method.wrap_method( + self.get_bucket_operation: self._wrap_method( self.get_bucket_operation, default_retry=retries.Retry( initial=1.0, @@ -212,33 +245,34 @@ def _prep_wrapped_messages(self, client_info): ), default_timeout=60.0, client_info=client_info, + method_name="google.cloud.storagebatchoperations.v1.StorageBatchOperations/GetBucketOperation", ), - self.get_location: gapic_v1.method.wrap_method( + self.get_location: self._wrap_method( self.get_location, default_timeout=None, client_info=client_info, ), - self.list_locations: gapic_v1.method.wrap_method( + self.list_locations: self._wrap_method( self.list_locations, default_timeout=None, client_info=client_info, ), - self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, ), - self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation: self._wrap_method( self.delete_operation, default_timeout=None, client_info=client_info, ), - self.get_operation: gapic_v1.method.wrap_method( + self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, ), - self.list_operations: gapic_v1.method.wrap_method( + self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py index 6af36576dacc..4b6b673b0db2 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py @@ -26,7 +26,12 @@ # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import operations_v1 +from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +try: + from google.api_core import _observability +except ImportError: # pragma: NO COVER + _observability = None import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -150,6 +155,7 @@ def __init__(self, *, ] ] ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, ) -> None: """Instantiate the transport. @@ -203,6 +209,9 @@ def __init__(self, *, interceptors (Optional[Sequence[Union[ClientInterceptor, Callable[[grpc.Channel], grpc.Channel]]]]): Additional interceptors (or callables that apply interceptors) to apply to the gRPC channel. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client, containing options such as + custom OpenTelemetry tracer providers. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -259,6 +268,7 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, api_audience=api_audience, + client_options=client_options, ) if not self._grpc_channel: @@ -280,12 +290,20 @@ def __init__(self, *, ], ) + channel_interceptors = list(interceptors) if interceptors else [] + if ( + _observability is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and otel_interceptor not in channel_interceptors + ): + channel_interceptors.append(otel_interceptor) + apply_interceptors = getattr( grpc_helpers, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, interceptors) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py index 2d51c66c5a73..80bc6cb76525 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py @@ -761,9 +761,8 @@ def test_storage_batch_operations_client_client_options_from_dict(): def test_storage_batch_operations_client_otel_channel_injection_enabled(): - mock_interceptor = mock.Mock() mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = mock_interceptor + mock_obs.is_otel_capabilities_enabled.return_value = True with ( mock.patch( "google.cloud.storagebatchoperations_v1.services.storage_batch_operations.client._observability", @@ -775,14 +774,14 @@ def test_storage_batch_operations_client_otel_channel_injection_enabled(): ): client = StorageBatchOperationsClient(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert called_kwargs.get("interceptors") == [mock_interceptor] + assert called_kwargs.get("client_options") == client._client_options def test_storage_batch_operations_client_otel_channel_injection_disabled(): mock_obs = mock.Mock() - mock_obs.get_otel_interceptor.return_value = None + mock_obs.is_otel_capabilities_enabled.return_value = False with ( mock.patch( "google.cloud.storagebatchoperations_v1.services.storage_batch_operations.client._observability", @@ -794,9 +793,9 @@ def test_storage_batch_operations_client_otel_channel_injection_disabled(): ): client = StorageBatchOperationsClient(transport="grpc") - mock_obs.get_otel_interceptor.assert_called_once_with(client._client_options) + mock_obs.is_otel_capabilities_enabled.assert_called_once_with(client._client_options) called_kwargs = patched_transport_init.call_args.kwargs - assert not called_kwargs.get("interceptors", []) + assert not called_kwargs.get("client_options") def test_storage_batch_operations_grpc_transport_channel_interceptors(): @@ -827,6 +826,42 @@ def test_storage_batch_operations_grpc_transport_channel_interceptors(): assert transport.grpc_channel == mock_channel +def test_storage_batch_operations_grpc_transport_otel_channel_interceptor(): + mock_otel_interceptor = mock.Mock() + mock_obs = mock.Mock() + mock_obs.get_otel_interceptor.return_value = mock_otel_interceptor + mock_channel = mock.Mock() + + with ( + mock.patch( + "google.cloud.storagebatchoperations_v1.services.storage_batch_operations.transports.grpc._observability", + mock_obs, + ), + mock.patch.object( + transports.StorageBatchOperationsGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.object( + grpc_helpers, + "apply_channel_interceptors", + return_value=mock_channel, + create=True, + ) as mock_apply_interceptors, + ): + options = client_options.ClientOptions() + transport = transports.StorageBatchOperationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + + mock_obs.get_otel_interceptor.assert_called_once_with(options) + mock_apply_interceptors.assert_called_once_with( + mock_channel, [mock_otel_interceptor] + ) + assert transport.grpc_channel == mock_channel + + def test_storage_batch_operations_grpc_transport_custom_channel_interceptors(): mock_interceptor = mock.Mock() mock_custom_channel = mock.Mock(spec=grpc.Channel) From 8b540c8637e1f881daed0c0c67e43c039f95c608 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 16 Sep 2026 06:55:54 -0400 Subject: [PATCH 31/43] fix(gapic): resolve showcase mypy error and ensure base transport wrap method coverage --- .../services/%service/transports/grpc.py.j2 | 7 ++-- .../%name_%version/%sub/test_%service.py.j2 | 35 +++++++++++++++++++ .../services/asset_service/transports/grpc.py | 7 ++-- .../unit/gapic/asset_v1/test_asset_service.py | 35 +++++++++++++++++++ .../iam_credentials/transports/grpc.py | 7 ++-- .../credentials_v1/test_iam_credentials.py | 35 +++++++++++++++++++ .../services/eventarc/transports/grpc.py | 7 ++-- .../unit/gapic/eventarc_v1/test_eventarc.py | 35 +++++++++++++++++++ .../config_service_v2/transports/grpc.py | 7 ++-- .../logging_service_v2/transports/grpc.py | 7 ++-- .../metrics_service_v2/transports/grpc.py | 7 ++-- .../logging_v2/test_config_service_v2.py | 35 +++++++++++++++++++ .../logging_v2/test_logging_service_v2.py | 35 +++++++++++++++++++ .../logging_v2/test_metrics_service_v2.py | 35 +++++++++++++++++++ .../config_service_v2/transports/grpc.py | 7 ++-- .../logging_service_v2/transports/grpc.py | 7 ++-- .../metrics_service_v2/transports/grpc.py | 7 ++-- .../logging_v2/test_config_service_v2.py | 35 +++++++++++++++++++ .../logging_v2/test_logging_service_v2.py | 35 +++++++++++++++++++ .../logging_v2/test_metrics_service_v2.py | 35 +++++++++++++++++++ .../services/cloud_redis/transports/grpc.py | 7 ++-- .../unit/gapic/redis_v1/test_cloud_redis.py | 35 +++++++++++++++++++ .../services/cloud_redis/transports/grpc.py | 7 ++-- .../unit/gapic/redis_v1/test_cloud_redis.py | 35 +++++++++++++++++++ .../transports/grpc.py | 7 ++-- .../test_storage_batch_operations.py | 35 +++++++++++++++++++ 26 files changed, 520 insertions(+), 26 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 index 94ba82a2f11a..fc8b3e6ffb9e 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 @@ -21,10 +21,13 @@ from google.api_core import operations_v1 {% endif %} from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +# The _observability module was introduced in google-api-core 2.36.0+. +# On older versions of google-api-core or when type-checking against them, +# mypy may flag attr-defined or assignment errors when fallback to None occurs. try: - from google.api_core import _observability + from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER - _observability = None + _observability = None # type: ignore[assignment] import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 index 760f1973140e..f09088ceae26 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 @@ -1369,6 +1369,41 @@ def test_{{ service.name|snake_case }}_base_transport_with_adc(): adc.assert_called_once() +def test_{{ service.name|snake_case }}_base_transport_wrap_method(): + mock_wrap = mock.Mock() + with mock.patch("google.api_core.gapic_v1.method.wrap_method", mock_wrap): + options = client_options.ClientOptions() + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('{{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join(".") }}.services.{{ service.name|snake_case }}.transports.{{ service.name }}Transport._prep_wrapped_messages') as prep: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.{{ service.name }}Transport(client_options=options) + + # Mock the kind property to return a value + with mock.patch.object(type(transport), "kind", new_callable=mock.PropertyMock) as mock_kind: + mock_kind.return_value = "grpc" + + # Test modern google-api-core with tracing support + transport._wrap_with_tracing = True + func = mock.Mock() + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert mock_wrap.call_args.kwargs.get("kind") == "grpc" + + # Test older google-api-core without tracing support + mock_wrap.reset_mock() + transport._wrap_with_tracing = False + transport._wrap_method(func, client_options=options, kind="grpc") + assert "client_options" not in mock_wrap.call_args.kwargs + assert "kind" not in mock_wrap.call_args.kwargs + + # Test without kind (e.g. abstract base transport) + mock_wrap.reset_mock() + mock_kind.side_effect = NotImplementedError + transport._wrap_with_tracing = True + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert "kind" not in mock_wrap.call_args.kwargs + + def test_{{ service.name|snake_case }}_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, 'default', autospec=True) as adc: diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py index d284544892cf..1e65b025584f 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -28,10 +28,13 @@ from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +# The _observability module was introduced in google-api-core 2.36.0+. +# On older versions of google-api-core or when type-checking against them, +# mypy may flag attr-defined or assignment errors when fallback to None occurs. try: - from google.api_core import _observability + from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER - _observability = None + _observability = None # type: ignore[assignment] import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py index e40f13e5dd1b..18b00d94d0b6 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py @@ -17458,6 +17458,41 @@ def test_asset_service_base_transport_with_adc(): adc.assert_called_once() +def test_asset_service_base_transport_wrap_method(): + mock_wrap = mock.Mock() + with mock.patch("google.api_core.gapic_v1.method.wrap_method", mock_wrap): + options = client_options.ClientOptions() + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.asset_v1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as prep: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport(client_options=options) + + # Mock the kind property to return a value + with mock.patch.object(type(transport), "kind", new_callable=mock.PropertyMock) as mock_kind: + mock_kind.return_value = "grpc" + + # Test modern google-api-core with tracing support + transport._wrap_with_tracing = True + func = mock.Mock() + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert mock_wrap.call_args.kwargs.get("kind") == "grpc" + + # Test older google-api-core without tracing support + mock_wrap.reset_mock() + transport._wrap_with_tracing = False + transport._wrap_method(func, client_options=options, kind="grpc") + assert "client_options" not in mock_wrap.call_args.kwargs + assert "kind" not in mock_wrap.call_args.kwargs + + # Test without kind (e.g. abstract base transport) + mock_wrap.reset_mock() + mock_kind.side_effect = NotImplementedError + transport._wrap_with_tracing = True + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert "kind" not in mock_wrap.call_args.kwargs + + def test_asset_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, 'default', autospec=True) as adc: diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py index 2cafce86ffa2..eda1d3b9cd6d 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py @@ -27,10 +27,13 @@ from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +# The _observability module was introduced in google-api-core 2.36.0+. +# On older versions of google-api-core or when type-checking against them, +# mypy may flag attr-defined or assignment errors when fallback to None occurs. try: - from google.api_core import _observability + from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER - _observability = None + _observability = None # type: ignore[assignment] import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py index 978a42823245..43f23fd0a8e3 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py @@ -3872,6 +3872,41 @@ def test_iam_credentials_base_transport_with_adc(): adc.assert_called_once() +def test_iam_credentials_base_transport_wrap_method(): + mock_wrap = mock.Mock() + with mock.patch("google.api_core.gapic_v1.method.wrap_method", mock_wrap): + options = client_options.ClientOptions() + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport._prep_wrapped_messages') as prep: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IAMCredentialsTransport(client_options=options) + + # Mock the kind property to return a value + with mock.patch.object(type(transport), "kind", new_callable=mock.PropertyMock) as mock_kind: + mock_kind.return_value = "grpc" + + # Test modern google-api-core with tracing support + transport._wrap_with_tracing = True + func = mock.Mock() + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert mock_wrap.call_args.kwargs.get("kind") == "grpc" + + # Test older google-api-core without tracing support + mock_wrap.reset_mock() + transport._wrap_with_tracing = False + transport._wrap_method(func, client_options=options, kind="grpc") + assert "client_options" not in mock_wrap.call_args.kwargs + assert "kind" not in mock_wrap.call_args.kwargs + + # Test without kind (e.g. abstract base transport) + mock_wrap.reset_mock() + mock_kind.side_effect = NotImplementedError + transport._wrap_with_tracing = True + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert "kind" not in mock_wrap.call_args.kwargs + + def test_iam_credentials_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, 'default', autospec=True) as adc: diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py index 3bd3e6f759de..30a2bb344f02 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py @@ -28,10 +28,13 @@ from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +# The _observability module was introduced in google-api-core 2.36.0+. +# On older versions of google-api-core or when type-checking against them, +# mypy may flag attr-defined or assignment errors when fallback to None occurs. try: - from google.api_core import _observability + from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER - _observability = None + _observability = None # type: ignore[assignment] import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py index 32d94476b8ab..8c98fc924a80 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py @@ -30899,6 +30899,41 @@ def test_eventarc_base_transport_with_adc(): adc.assert_called_once() +def test_eventarc_base_transport_wrap_method(): + mock_wrap = mock.Mock() + with mock.patch("google.api_core.gapic_v1.method.wrap_method", mock_wrap): + options = client_options.ClientOptions() + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.eventarc_v1.services.eventarc.transports.EventarcTransport._prep_wrapped_messages') as prep: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EventarcTransport(client_options=options) + + # Mock the kind property to return a value + with mock.patch.object(type(transport), "kind", new_callable=mock.PropertyMock) as mock_kind: + mock_kind.return_value = "grpc" + + # Test modern google-api-core with tracing support + transport._wrap_with_tracing = True + func = mock.Mock() + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert mock_wrap.call_args.kwargs.get("kind") == "grpc" + + # Test older google-api-core without tracing support + mock_wrap.reset_mock() + transport._wrap_with_tracing = False + transport._wrap_method(func, client_options=options, kind="grpc") + assert "client_options" not in mock_wrap.call_args.kwargs + assert "kind" not in mock_wrap.call_args.kwargs + + # Test without kind (e.g. abstract base transport) + mock_wrap.reset_mock() + mock_kind.side_effect = NotImplementedError + transport._wrap_with_tracing = True + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert "kind" not in mock_wrap.call_args.kwargs + + def test_eventarc_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, 'default', autospec=True) as adc: diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index 565161546fb6..9c62d0b16de8 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -28,10 +28,13 @@ from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +# The _observability module was introduced in google-api-core 2.36.0+. +# On older versions of google-api-core or when type-checking against them, +# mypy may flag attr-defined or assignment errors when fallback to None occurs. try: - from google.api_core import _observability + from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER - _observability = None + _observability = None # type: ignore[assignment] import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index 260c3fdb13cd..5df5fb7d48e1 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -27,10 +27,13 @@ from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +# The _observability module was introduced in google-api-core 2.36.0+. +# On older versions of google-api-core or when type-checking against them, +# mypy may flag attr-defined or assignment errors when fallback to None occurs. try: - from google.api_core import _observability + from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER - _observability = None + _observability = None # type: ignore[assignment] import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index c3c51258daa6..358403b0f13a 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -27,10 +27,13 @@ from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +# The _observability module was introduced in google-api-core 2.36.0+. +# On older versions of google-api-core or when type-checking against them, +# mypy may flag attr-defined or assignment errors when fallback to None occurs. try: - from google.api_core import _observability + from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER - _observability = None + _observability = None # type: ignore[assignment] import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py index 2e5a7859329b..ede2b0c4869a 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -12816,6 +12816,41 @@ def test_config_service_v2_base_transport_with_adc(): adc.assert_called_once() +def test_config_service_v2_base_transport_wrap_method(): + mock_wrap = mock.Mock() + with mock.patch("google.api_core.gapic_v1.method.wrap_method", mock_wrap): + options = client_options.ClientOptions() + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.logging_v2.services.config_service_v2.transports.ConfigServiceV2Transport._prep_wrapped_messages') as prep: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConfigServiceV2Transport(client_options=options) + + # Mock the kind property to return a value + with mock.patch.object(type(transport), "kind", new_callable=mock.PropertyMock) as mock_kind: + mock_kind.return_value = "grpc" + + # Test modern google-api-core with tracing support + transport._wrap_with_tracing = True + func = mock.Mock() + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert mock_wrap.call_args.kwargs.get("kind") == "grpc" + + # Test older google-api-core without tracing support + mock_wrap.reset_mock() + transport._wrap_with_tracing = False + transport._wrap_method(func, client_options=options, kind="grpc") + assert "client_options" not in mock_wrap.call_args.kwargs + assert "kind" not in mock_wrap.call_args.kwargs + + # Test without kind (e.g. abstract base transport) + mock_wrap.reset_mock() + mock_kind.side_effect = NotImplementedError + transport._wrap_with_tracing = True + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert "kind" not in mock_wrap.call_args.kwargs + + def test_config_service_v2_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, 'default', autospec=True) as adc: diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py index d6e92d8f7d01..2d447e1bc2a4 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -3408,6 +3408,41 @@ def test_logging_service_v2_base_transport_with_adc(): adc.assert_called_once() +def test_logging_service_v2_base_transport_wrap_method(): + mock_wrap = mock.Mock() + with mock.patch("google.api_core.gapic_v1.method.wrap_method", mock_wrap): + options = client_options.ClientOptions() + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.logging_v2.services.logging_service_v2.transports.LoggingServiceV2Transport._prep_wrapped_messages') as prep: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LoggingServiceV2Transport(client_options=options) + + # Mock the kind property to return a value + with mock.patch.object(type(transport), "kind", new_callable=mock.PropertyMock) as mock_kind: + mock_kind.return_value = "grpc" + + # Test modern google-api-core with tracing support + transport._wrap_with_tracing = True + func = mock.Mock() + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert mock_wrap.call_args.kwargs.get("kind") == "grpc" + + # Test older google-api-core without tracing support + mock_wrap.reset_mock() + transport._wrap_with_tracing = False + transport._wrap_method(func, client_options=options, kind="grpc") + assert "client_options" not in mock_wrap.call_args.kwargs + assert "kind" not in mock_wrap.call_args.kwargs + + # Test without kind (e.g. abstract base transport) + mock_wrap.reset_mock() + mock_kind.side_effect = NotImplementedError + transport._wrap_with_tracing = True + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert "kind" not in mock_wrap.call_args.kwargs + + def test_logging_service_v2_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, 'default', autospec=True) as adc: diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index 63edef5214b7..ec5ed23aae67 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -3208,6 +3208,41 @@ def test_metrics_service_v2_base_transport_with_adc(): adc.assert_called_once() +def test_metrics_service_v2_base_transport_wrap_method(): + mock_wrap = mock.Mock() + with mock.patch("google.api_core.gapic_v1.method.wrap_method", mock_wrap): + options = client_options.ClientOptions() + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.logging_v2.services.metrics_service_v2.transports.MetricsServiceV2Transport._prep_wrapped_messages') as prep: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.MetricsServiceV2Transport(client_options=options) + + # Mock the kind property to return a value + with mock.patch.object(type(transport), "kind", new_callable=mock.PropertyMock) as mock_kind: + mock_kind.return_value = "grpc" + + # Test modern google-api-core with tracing support + transport._wrap_with_tracing = True + func = mock.Mock() + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert mock_wrap.call_args.kwargs.get("kind") == "grpc" + + # Test older google-api-core without tracing support + mock_wrap.reset_mock() + transport._wrap_with_tracing = False + transport._wrap_method(func, client_options=options, kind="grpc") + assert "client_options" not in mock_wrap.call_args.kwargs + assert "kind" not in mock_wrap.call_args.kwargs + + # Test without kind (e.g. abstract base transport) + mock_wrap.reset_mock() + mock_kind.side_effect = NotImplementedError + transport._wrap_with_tracing = True + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert "kind" not in mock_wrap.call_args.kwargs + + def test_metrics_service_v2_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, 'default', autospec=True) as adc: diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index 565161546fb6..9c62d0b16de8 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -28,10 +28,13 @@ from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +# The _observability module was introduced in google-api-core 2.36.0+. +# On older versions of google-api-core or when type-checking against them, +# mypy may flag attr-defined or assignment errors when fallback to None occurs. try: - from google.api_core import _observability + from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER - _observability = None + _observability = None # type: ignore[assignment] import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index 260c3fdb13cd..5df5fb7d48e1 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -27,10 +27,13 @@ from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +# The _observability module was introduced in google-api-core 2.36.0+. +# On older versions of google-api-core or when type-checking against them, +# mypy may flag attr-defined or assignment errors when fallback to None occurs. try: - from google.api_core import _observability + from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER - _observability = None + _observability = None # type: ignore[assignment] import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index c3c51258daa6..358403b0f13a 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -27,10 +27,13 @@ from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +# The _observability module was introduced in google-api-core 2.36.0+. +# On older versions of google-api-core or when type-checking against them, +# mypy may flag attr-defined or assignment errors when fallback to None occurs. try: - from google.api_core import _observability + from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER - _observability = None + _observability = None # type: ignore[assignment] import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py index 4f0b7e4ab632..138d75fbc96a 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -12816,6 +12816,41 @@ def test_config_service_v2_base_transport_with_adc(): adc.assert_called_once() +def test_config_service_v2_base_transport_wrap_method(): + mock_wrap = mock.Mock() + with mock.patch("google.api_core.gapic_v1.method.wrap_method", mock_wrap): + options = client_options.ClientOptions() + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.logging_v2.services.config_service_v2.transports.ConfigServiceV2Transport._prep_wrapped_messages') as prep: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConfigServiceV2Transport(client_options=options) + + # Mock the kind property to return a value + with mock.patch.object(type(transport), "kind", new_callable=mock.PropertyMock) as mock_kind: + mock_kind.return_value = "grpc" + + # Test modern google-api-core with tracing support + transport._wrap_with_tracing = True + func = mock.Mock() + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert mock_wrap.call_args.kwargs.get("kind") == "grpc" + + # Test older google-api-core without tracing support + mock_wrap.reset_mock() + transport._wrap_with_tracing = False + transport._wrap_method(func, client_options=options, kind="grpc") + assert "client_options" not in mock_wrap.call_args.kwargs + assert "kind" not in mock_wrap.call_args.kwargs + + # Test without kind (e.g. abstract base transport) + mock_wrap.reset_mock() + mock_kind.side_effect = NotImplementedError + transport._wrap_with_tracing = True + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert "kind" not in mock_wrap.call_args.kwargs + + def test_config_service_v2_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, 'default', autospec=True) as adc: diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py index d6e92d8f7d01..2d447e1bc2a4 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -3408,6 +3408,41 @@ def test_logging_service_v2_base_transport_with_adc(): adc.assert_called_once() +def test_logging_service_v2_base_transport_wrap_method(): + mock_wrap = mock.Mock() + with mock.patch("google.api_core.gapic_v1.method.wrap_method", mock_wrap): + options = client_options.ClientOptions() + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.logging_v2.services.logging_service_v2.transports.LoggingServiceV2Transport._prep_wrapped_messages') as prep: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LoggingServiceV2Transport(client_options=options) + + # Mock the kind property to return a value + with mock.patch.object(type(transport), "kind", new_callable=mock.PropertyMock) as mock_kind: + mock_kind.return_value = "grpc" + + # Test modern google-api-core with tracing support + transport._wrap_with_tracing = True + func = mock.Mock() + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert mock_wrap.call_args.kwargs.get("kind") == "grpc" + + # Test older google-api-core without tracing support + mock_wrap.reset_mock() + transport._wrap_with_tracing = False + transport._wrap_method(func, client_options=options, kind="grpc") + assert "client_options" not in mock_wrap.call_args.kwargs + assert "kind" not in mock_wrap.call_args.kwargs + + # Test without kind (e.g. abstract base transport) + mock_wrap.reset_mock() + mock_kind.side_effect = NotImplementedError + transport._wrap_with_tracing = True + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert "kind" not in mock_wrap.call_args.kwargs + + def test_logging_service_v2_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, 'default', autospec=True) as adc: diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index c9733a911372..650bf5813089 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -3208,6 +3208,41 @@ def test_metrics_service_v2_base_transport_with_adc(): adc.assert_called_once() +def test_metrics_service_v2_base_transport_wrap_method(): + mock_wrap = mock.Mock() + with mock.patch("google.api_core.gapic_v1.method.wrap_method", mock_wrap): + options = client_options.ClientOptions() + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.logging_v2.services.metrics_service_v2.transports.MetricsServiceV2Transport._prep_wrapped_messages') as prep: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.MetricsServiceV2Transport(client_options=options) + + # Mock the kind property to return a value + with mock.patch.object(type(transport), "kind", new_callable=mock.PropertyMock) as mock_kind: + mock_kind.return_value = "grpc" + + # Test modern google-api-core with tracing support + transport._wrap_with_tracing = True + func = mock.Mock() + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert mock_wrap.call_args.kwargs.get("kind") == "grpc" + + # Test older google-api-core without tracing support + mock_wrap.reset_mock() + transport._wrap_with_tracing = False + transport._wrap_method(func, client_options=options, kind="grpc") + assert "client_options" not in mock_wrap.call_args.kwargs + assert "kind" not in mock_wrap.call_args.kwargs + + # Test without kind (e.g. abstract base transport) + mock_wrap.reset_mock() + mock_kind.side_effect = NotImplementedError + transport._wrap_with_tracing = True + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert "kind" not in mock_wrap.call_args.kwargs + + def test_metrics_service_v2_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, 'default', autospec=True) as adc: diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index 015ac807c15b..0fe6a61d9116 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -28,10 +28,13 @@ from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +# The _observability module was introduced in google-api-core 2.36.0+. +# On older versions of google-api-core or when type-checking against them, +# mypy may flag attr-defined or assignment errors when fallback to None occurs. try: - from google.api_core import _observability + from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER - _observability = None + _observability = None # type: ignore[assignment] import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py index 2319eb5eaf30..22ef991acbe8 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -11478,6 +11478,41 @@ def test_cloud_redis_base_transport_with_adc(): adc.assert_called_once() +def test_cloud_redis_base_transport_wrap_method(): + mock_wrap = mock.Mock() + with mock.patch("google.api_core.gapic_v1.method.wrap_method", mock_wrap): + options = client_options.ClientOptions() + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.redis_v1.services.cloud_redis.transports.CloudRedisTransport._prep_wrapped_messages') as prep: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudRedisTransport(client_options=options) + + # Mock the kind property to return a value + with mock.patch.object(type(transport), "kind", new_callable=mock.PropertyMock) as mock_kind: + mock_kind.return_value = "grpc" + + # Test modern google-api-core with tracing support + transport._wrap_with_tracing = True + func = mock.Mock() + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert mock_wrap.call_args.kwargs.get("kind") == "grpc" + + # Test older google-api-core without tracing support + mock_wrap.reset_mock() + transport._wrap_with_tracing = False + transport._wrap_method(func, client_options=options, kind="grpc") + assert "client_options" not in mock_wrap.call_args.kwargs + assert "kind" not in mock_wrap.call_args.kwargs + + # Test without kind (e.g. abstract base transport) + mock_wrap.reset_mock() + mock_kind.side_effect = NotImplementedError + transport._wrap_with_tracing = True + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert "kind" not in mock_wrap.call_args.kwargs + + def test_cloud_redis_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, 'default', autospec=True) as adc: diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index 21dbcdda42f4..17812fecc84d 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -28,10 +28,13 @@ from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +# The _observability module was introduced in google-api-core 2.36.0+. +# On older versions of google-api-core or when type-checking against them, +# mypy may flag attr-defined or assignment errors when fallback to None occurs. try: - from google.api_core import _observability + from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER - _observability = None + _observability = None # type: ignore[assignment] import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py index 7b968b378489..c2afe10ec2d1 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -6716,6 +6716,41 @@ def test_cloud_redis_base_transport_with_adc(): adc.assert_called_once() +def test_cloud_redis_base_transport_wrap_method(): + mock_wrap = mock.Mock() + with mock.patch("google.api_core.gapic_v1.method.wrap_method", mock_wrap): + options = client_options.ClientOptions() + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.redis_v1.services.cloud_redis.transports.CloudRedisTransport._prep_wrapped_messages') as prep: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudRedisTransport(client_options=options) + + # Mock the kind property to return a value + with mock.patch.object(type(transport), "kind", new_callable=mock.PropertyMock) as mock_kind: + mock_kind.return_value = "grpc" + + # Test modern google-api-core with tracing support + transport._wrap_with_tracing = True + func = mock.Mock() + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert mock_wrap.call_args.kwargs.get("kind") == "grpc" + + # Test older google-api-core without tracing support + mock_wrap.reset_mock() + transport._wrap_with_tracing = False + transport._wrap_method(func, client_options=options, kind="grpc") + assert "client_options" not in mock_wrap.call_args.kwargs + assert "kind" not in mock_wrap.call_args.kwargs + + # Test without kind (e.g. abstract base transport) + mock_wrap.reset_mock() + mock_kind.side_effect = NotImplementedError + transport._wrap_with_tracing = True + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert "kind" not in mock_wrap.call_args.kwargs + + def test_cloud_redis_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, 'default', autospec=True) as adc: diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py index 4b6b673b0db2..bf4260682085 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py @@ -28,10 +28,13 @@ from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 +# The _observability module was introduced in google-api-core 2.36.0+. +# On older versions of google-api-core or when type-checking against them, +# mypy may flag attr-defined or assignment errors when fallback to None occurs. try: - from google.api_core import _observability + from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER - _observability = None + _observability = None # type: ignore[assignment] import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py index 80bc6cb76525..3699dc2dbf80 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py @@ -6781,6 +6781,41 @@ def test_storage_batch_operations_base_transport_with_adc(): adc.assert_called_once() +def test_storage_batch_operations_base_transport_wrap_method(): + mock_wrap = mock.Mock() + with mock.patch("google.api_core.gapic_v1.method.wrap_method", mock_wrap): + options = client_options.ClientOptions() + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.storagebatchoperations_v1.services.storage_batch_operations.transports.StorageBatchOperationsTransport._prep_wrapped_messages') as prep: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StorageBatchOperationsTransport(client_options=options) + + # Mock the kind property to return a value + with mock.patch.object(type(transport), "kind", new_callable=mock.PropertyMock) as mock_kind: + mock_kind.return_value = "grpc" + + # Test modern google-api-core with tracing support + transport._wrap_with_tracing = True + func = mock.Mock() + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert mock_wrap.call_args.kwargs.get("kind") == "grpc" + + # Test older google-api-core without tracing support + mock_wrap.reset_mock() + transport._wrap_with_tracing = False + transport._wrap_method(func, client_options=options, kind="grpc") + assert "client_options" not in mock_wrap.call_args.kwargs + assert "kind" not in mock_wrap.call_args.kwargs + + # Test without kind (e.g. abstract base transport) + mock_wrap.reset_mock() + mock_kind.side_effect = NotImplementedError + transport._wrap_with_tracing = True + transport._wrap_method(func) + assert mock_wrap.call_args.kwargs.get("client_options") == options + assert "kind" not in mock_wrap.call_args.kwargs + + def test_storage_batch_operations_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, 'default', autospec=True) as adc: From 880f5b986819c5e1d2041dddea99cefdf6077238 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 16 Sep 2026 10:27:15 -0400 Subject: [PATCH 32/43] feat(observability): add fallback status code and exception mapping for error.type in method tracing --- .../google/api_core/gapic_v1/method.py | 5 +++ .../tests/unit/gapic/test_method.py | 35 +++++++++++-------- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/method.py b/packages/google-api-core/google/api_core/gapic_v1/method.py index 9b10b0392acf..72e564b2e9bb 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/method.py +++ b/packages/google-api-core/google/api_core/gapic_v1/method.py @@ -216,6 +216,11 @@ def _extract_error_attributes(exc: Optional[Exception]) -> dict[str, Any]: reason = getattr(source, "reason", None) if reason: attrs["error.type"] = reason + elif target_exc is not None: + # Fallback per OpenTelemetry Semantic Conventions: every failed span should record + # a low-cardinality error.type. Use canonical status code name or exception class name. + status_code = _extract_status_code(target_exc) + attrs["error.type"] = status_code or target_exc.__class__.__name__ metadata = getattr(source, "metadata", None) if metadata: for k, v in metadata.items(): diff --git a/packages/google-api-core/tests/unit/gapic/test_method.py b/packages/google-api-core/tests/unit/gapic/test_method.py index a8d2197b0d6a..1a265e183077 100644 --- a/packages/google-api-core/tests/unit/gapic/test_method.py +++ b/packages/google-api-core/tests/unit/gapic/test_method.py @@ -525,9 +525,10 @@ def test_wrap_method_otel_tracing_enabled_error(mock_otel): wrapped() mock_target.assert_called_once() - mock_otel.span.set_attribute.assert_called_with( + mock_otel.span.set_attribute.assert_any_call( "rpc.response.status_code", "RuntimeError" ) + mock_otel.span.set_attribute.assert_any_call("error.type", "RuntimeError") @pytest.mark.parametrize( @@ -547,7 +548,7 @@ def test_wrap_method_otel_tracing_enabled_error(mock_otel): def test_wrap_method_otel_tracing_error_status_code_mapping( mock_otel, exc, expected_status ): - """Proves that exceptions are cleanly mapped to canonical rpc.response.status_code names.""" + """Proves that exceptions are cleanly mapped to canonical rpc.response.status_code and error.type names.""" mock_target = mock.Mock(side_effect=exc) wrapped = google.api_core.gapic_v1.method.wrap_method( @@ -557,9 +558,10 @@ def test_wrap_method_otel_tracing_error_status_code_mapping( with pytest.raises(type(exc)): wrapped() - mock_otel.span.set_attribute.assert_called_with( + mock_otel.span.set_attribute.assert_any_call( "rpc.response.status_code", expected_status ) + mock_otel.span.set_attribute.assert_any_call("error.type", expected_status) def test_wrap_method_otel_tracing_import_error(monkeypatch): @@ -687,11 +689,13 @@ def test_wrap_method_otel_tracing_attributes_no_service(mock_otel): def test_extract_error_attributes_standard_exception(): - """Proves that _extract_error_attributes returns empty dict for standard exceptions without ErrorInfo.""" - assert ( - google.api_core.gapic_v1.method._extract_error_attributes(ValueError("fail")) - == {} - ) + """Proves that _extract_error_attributes returns fallback error.type for exceptions without ErrorInfo.""" + assert google.api_core.gapic_v1.method._extract_error_attributes( + ValueError("fail") + ) == {"error.type": "ValueError"} + assert google.api_core.gapic_v1.method._extract_error_attributes( + exceptions.InvalidArgument("invalid argument") + ) == {"error.type": "INVALID_ARGUMENT"} assert google.api_core.gapic_v1.method._extract_error_attributes(None) == {} @@ -838,12 +842,14 @@ def test_extract_error_attributes_variations(): "google.api_core.exceptions._parse_grpc_error_details", side_effect=ValueError("bad proto"), ): - assert _extract_error_attributes(exc_with_resp) == {} + assert _extract_error_attributes(exc_with_resp) == { + "error.type": "SimpleNamespace" + } # 4. error_info with empty domain, empty reason, empty metadata error_info_empty = types.SimpleNamespace(domain="", reason="", metadata=None) exc_empty = types.SimpleNamespace(error_info=error_info_empty) - assert _extract_error_attributes(exc_empty) == {} + assert _extract_error_attributes(exc_empty) == {"error.type": "SimpleNamespace"} # 5. else fallback where target_exc directly has domain, reason, and metadata exc_fallback = types.SimpleNamespace( @@ -863,7 +869,9 @@ def test_extract_error_attributes_variations(): reason="", metadata={}, ) - assert _extract_error_attributes(exc_fallback_empty) == {} + assert _extract_error_attributes(exc_fallback_empty) == { + "error.type": "SimpleNamespace" + } def test_wrap_method_otel_tracing_partial_span_capabilities(mock_otel): @@ -881,9 +889,8 @@ def test_wrap_method_otel_tracing_partial_span_capabilities(mock_otel): ) with pytest.raises(ValueError): wrapped1() - mock_span1.set_attribute.assert_called_with( - "rpc.response.status_code", "ValueError" - ) + mock_span1.set_attribute.assert_any_call("rpc.response.status_code", "ValueError") + mock_span1.set_attribute.assert_any_call("error.type", "ValueError") # Test span without set_attribute (e.g. mock or stub lacking set_attribute) mock_span2 = mock.Mock(spec=[]) From 9bb33051db05faf4d4a6572e0d004a01d33b4083 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 16 Sep 2026 10:27:34 -0400 Subject: [PATCH 33/43] test(gapic): harmonize showcase system tracing tests with env gating and client options --- .../gapic-generator/tests/system/conftest.py | 17 +- .../tests/system/test_tracing.py | 242 ++++++++++-------- 2 files changed, 144 insertions(+), 115 deletions(-) diff --git a/packages/gapic-generator/tests/system/conftest.py b/packages/gapic-generator/tests/system/conftest.py index 6d331f7a295e..d001b135b8e1 100644 --- a/packages/gapic-generator/tests/system/conftest.py +++ b/packages/gapic-generator/tests/system/conftest.py @@ -178,16 +178,13 @@ def construct_client( if transport_name in ["grpc", "grpc_asyncio"]: # TODO(gapic-generator-python/issues/1914): Need to test grpc transports without a channel_creator assert channel_creator - interceptors = [] - if _observability is not None and transport_name == "grpc": - otel_interceptor = _observability.get_otel_interceptor(client_options) - if otel_interceptor is not None: - interceptors.append(otel_interceptor) - transport = transport_cls( - credentials=credentials, - channel=channel_creator(transport_endpoint), - interceptors=interceptors if interceptors else None, - ) + transport_kwargs = { + "credentials": credentials, + "channel": channel_creator(transport_endpoint), + } + if transport_name == "grpc": + transport_kwargs["client_options"] = client_options + transport = transport_cls(**transport_kwargs) elif transport_name in ["rest", "rest_asyncio"]: # The custom host explicitly bypasses https. transport = transport_cls( diff --git a/packages/gapic-generator/tests/system/test_tracing.py b/packages/gapic-generator/tests/system/test_tracing.py index 8906b8666cd4..9eec44955d6a 100644 --- a/packages/gapic-generator/tests/system/test_tracing.py +++ b/packages/gapic-generator/tests/system/test_tracing.py @@ -36,6 +36,7 @@ from google import showcase from google.api_core import exceptions from google.api_core import retry as retries +from google.api_core._feature_gating_helpers import FeatureGatingError from google.api_core.client_options import ClientOptions from google.auth import credentials as ga_credentials from google.rpc import code_pb2 @@ -65,115 +66,140 @@ def otel_echo_client(span_exporter, use_mtls): """Constructs an EchoClient wired with an in-memory TracerProvider.""" exporter, provider = span_exporter options = ClientOptions( - tracing_enabled=True, tracer_provider=provider, ) - client = construct_client( - EchoClient, - use_mtls, - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) - return client, exporter + with mock.patch.dict( + os.environ, {"GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED": "true"} + ): + client = construct_client( + EchoClient, + use_mtls, + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + yield client, exporter def test_sync_unary_tracing(otel_echo_client): - """Verifies that a synchronous unary RPC generates a trace span with expected attributes.""" + """Verifies that a synchronous unary RPC generates trace spans with expected attributes.""" client, exporter = otel_echo_client - response = client.echo(showcase.EchoRequest(content="hello world")) - assert response.content == "hello world" + with mock.patch.dict( + os.environ, {"GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED": "true"} + ): + response = client.echo(showcase.EchoRequest(content="hello world")) + assert response.content == "hello world" spans = exporter.get_finished_spans() - assert len(spans) == 1 + # Synchronous unary calls generate both a Tier 2 method span and a Tier 4 wire span + assert len(spans) == 2 + + for span in spans: + assert span.name == "google.showcase.v1beta1.Echo/Echo" + assert span.attributes.get("rpc.system.name") == "grpc" + assert span.attributes.get("rpc.method") == "google.showcase.v1beta1.Echo/Echo" + assert span.attributes.get("rpc.response.status_code") == "OK" + assert span.kind == trace.SpanKind.CLIENT - span = spans[0] - assert span.name == "google.showcase.v1beta1.Echo/Echo" - assert span.attributes.get("rpc.system.name") == "grpc" - assert span.attributes.get("rpc.method") == "google.showcase.v1beta1.Echo/Echo" - assert span.attributes.get("rpc.response.status_code") == "OK" - assert span.attributes.get("url.domain") == "googleapis.com" - assert span.kind == trace.SpanKind.CLIENT + # Verify that the transport wire span captures url.domain + wire_spans = [s for s in spans if "url.domain" in s.attributes] + assert len(wire_spans) == 1 + assert wire_spans[0].attributes["url.domain"] == "googleapis.com" def test_unary_retries_tracing(span_exporter, use_mtls): """Verifies that each attempt of a retried RPC generates a separate span.""" exporter, provider = span_exporter options = ClientOptions( - tracing_enabled=True, tracer_provider=provider, ) - client = construct_client( - EchoClient, - use_mtls, - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) + with mock.patch.dict( + os.environ, {"GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED": "true"} + ): + client = construct_client( + EchoClient, + use_mtls, + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) - # Configure a custom retry policy with 2 attempts on DeadlineExceeded - custom_retry = retries.Retry( - predicate=retries.if_exception_type(exceptions.DeadlineExceeded), - initial=0.05, - maximum=0.1, - multiplier=1.0, - deadline=0.3, - ) + # Configure a custom retry policy with 2 attempts on DeadlineExceeded + custom_retry = retries.Retry( + predicate=retries.if_exception_type(exceptions.DeadlineExceeded), + initial=0.05, + maximum=0.1, + multiplier=1.0, + deadline=0.3, + ) - with pytest.raises((exceptions.DeadlineExceeded, exceptions.RetryError)): - client.echo( - { - "error": { - "code": code_pb2.Code.Value("DEADLINE_EXCEEDED"), - "message": "Simulated deadline exceeded error for retry testing.", + with pytest.raises((exceptions.DeadlineExceeded, exceptions.RetryError)): + client.echo( + { + "error": { + "code": code_pb2.Code.Value("DEADLINE_EXCEEDED"), + "message": "Simulated deadline exceeded error for retry testing.", + }, }, - }, - retry=custom_retry, - ) + retry=custom_retry, + ) - spans = exporter.get_finished_spans() - # At least two attempts should have been made and recorded - assert len(spans) >= 2 - for span in spans: - assert span.name == "google.showcase.v1beta1.Echo/Echo" - assert span.attributes.get("rpc.system.name") == "grpc" - assert span.attributes.get("rpc.method") == "google.showcase.v1beta1.Echo/Echo" - # Non-successful attempt should not have rpc.response.status_code == "OK" - assert span.attributes.get("rpc.response.status_code") != "OK" + spans = exporter.get_finished_spans() + # At least two attempts should have been made and recorded + assert len(spans) >= 2 + for span in spans: + assert span.name == "google.showcase.v1beta1.Echo/Echo" + assert span.attributes.get("rpc.system.name") == "grpc" + assert ( + span.attributes.get("rpc.method") == "google.showcase.v1beta1.Echo/Echo" + ) + # Non-successful attempt should not have rpc.response.status_code == "OK" + assert span.attributes.get("rpc.response.status_code") != "OK" def test_tracing_disabled_default(use_mtls): """Verifies that default client options emit zero spans (zero overhead guarantee). - Ensures that configuring a `TracerProvider` in `ClientOptions` without explicitly - enabling tracing (via `tracing_enabled=True` or the environment variable - `GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED`) records zero spans and incurs - no tracing overhead. - - An active `TracerProvider` with an in-memory exporter is passed to the client. - The test executes an actual unary RPC and asserts that no finished spans are - recorded. + Ensures that without setting GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED=true, + even if an ambient TracerProvider is active, zero spans are recorded and no + tracing overhead is incurred. Also verifies that passing tracer_provider without + the environment variable fails fast by raising FeatureGatingError. """ exporter = InMemorySpanExporter() provider = TracerProvider() provider.add_span_processor(SimpleSpanProcessor(exporter)) - # Provide the provider, but leave tracing_enabled=False / unset - options = ClientOptions( - tracing_enabled=False, + # Providing a tracer_provider without enabling the experimental env var fails fast + options_with_provider = ClientOptions( tracer_provider=provider, ) - client = construct_client( - EchoClient, - use_mtls, - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) + with mock.patch.dict( + os.environ, {"GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED": "false"} + ): + with pytest.raises(FeatureGatingError): + construct_client( + EchoClient, + use_mtls, + client_options=options_with_provider, + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Default client options emit zero spans + options = ClientOptions() + with mock.patch.dict( + os.environ, {"GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED": "false"} + ): + client = construct_client( + EchoClient, + use_mtls, + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) - response = client.echo(showcase.EchoRequest(content="no tracing")) - assert response.content == "no tracing" + response = client.echo(showcase.EchoRequest(content="no tracing")) + assert response.content == "no tracing" - # Zero spans must be emitted when tracing is disabled - assert len(exporter.get_finished_spans()) == 0 + # Zero spans must be emitted when tracing is disabled + assert len(exporter.get_finished_spans()) == 0 def test_custom_tracer_provider(use_mtls): @@ -201,21 +227,23 @@ def test_custom_tracer_provider(use_mtls): trace.set_tracer_provider(global_provider) try: options = ClientOptions( - tracing_enabled=True, tracer_provider=custom_provider, ) - client = construct_client( - EchoClient, - use_mtls, - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) - - response = client.echo(showcase.EchoRequest(content="isolated trace")) - assert response.content == "isolated trace" - - assert len(custom_exporter.get_finished_spans()) == 1 - assert len(global_exporter.get_finished_spans()) == 0 + with mock.patch.dict( + os.environ, {"GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED": "true"} + ): + client = construct_client( + EchoClient, + use_mtls, + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + + response = client.echo(showcase.EchoRequest(content="isolated trace")) + assert response.content == "isolated trace" + + assert len(custom_exporter.get_finished_spans()) == 2 + assert len(global_exporter.get_finished_spans()) == 0 finally: trace.set_tracer_provider(original_provider) @@ -235,27 +263,30 @@ def test_direct_client_initialization_tracing(span_exporter): """ exporter, provider = span_exporter options = ClientOptions( - tracing_enabled=True, tracer_provider=provider, ) - with mock.patch.object( - EchoClient.get_transport_class("grpc"), - "create_channel", - side_effect=lambda host, **kwargs: grpc.insecure_channel("localhost:7469"), + with mock.patch.dict( + os.environ, {"GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED": "true"} ): - # Client constructs the transport and wires interceptors itself - client = EchoClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) - response = client.echo(showcase.EchoRequest(content="direct client wiring")) - assert response.content == "direct client wiring" - - spans = exporter.get_finished_spans() - assert len(spans) == 1 - assert spans[0].name == "google.showcase.v1beta1.Echo/Echo" - assert spans[0].attributes.get("rpc.system.name") == "grpc" + with mock.patch.object( + EchoClient.get_transport_class("grpc"), + "create_channel", + side_effect=lambda host, **kwargs: grpc.insecure_channel("localhost:7469"), + ): + # Client constructs the transport and wires interceptors itself + client = EchoClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + response = client.echo(showcase.EchoRequest(content="direct client wiring")) + assert response.content == "direct client wiring" + + spans = exporter.get_finished_spans() + assert len(spans) == 2 + for span in spans: + assert span.name == "google.showcase.v1beta1.Echo/Echo" + assert span.attributes.get("rpc.system.name") == "grpc" def test_env_var_opt_in(span_exporter, use_mtls): @@ -280,5 +311,6 @@ def test_env_var_opt_in(span_exporter, use_mtls): assert response.content == "env opt in" spans = exporter.get_finished_spans() - assert len(spans) == 1 - assert spans[0].name == "google.showcase.v1beta1.Echo/Echo" + assert len(spans) == 2 + for span in spans: + assert span.name == "google.showcase.v1beta1.Echo/Echo" From af22028365b1b1de6e204e698f9aa30af75ea0a0 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 16 Sep 2026 14:04:40 -0400 Subject: [PATCH 34/43] fix(observability): ensure 100% branch coverage in error attribute extraction --- packages/google-api-core/google/api_core/gapic_v1/method.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/method.py b/packages/google-api-core/google/api_core/gapic_v1/method.py index 72e564b2e9bb..2484831ec07a 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/method.py +++ b/packages/google-api-core/google/api_core/gapic_v1/method.py @@ -216,7 +216,7 @@ def _extract_error_attributes(exc: Optional[Exception]) -> dict[str, Any]: reason = getattr(source, "reason", None) if reason: attrs["error.type"] = reason - elif target_exc is not None: + else: # Fallback per OpenTelemetry Semantic Conventions: every failed span should record # a low-cardinality error.type. Use canonical status code name or exception class name. status_code = _extract_status_code(target_exc) From d073f2bea4ab033e19f48fd5d2f8b5f5dda9646f Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 16 Sep 2026 14:56:27 -0400 Subject: [PATCH 35/43] perf(generator): cache wrap_method tracing check at module level --- .../services/%service/transports/base.py.j2 | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 index 602695caa1b2..164e0bb52739 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 @@ -55,6 +55,13 @@ from {{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + ser DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +# Check once at module load time whether google-api-core's wrap_method supports +# OpenTelemetry tracing arguments (client_options, method_name, is_streaming, kind) +# to avoid recurring inspect.signature latency during client instantiation. +_WRAP_METHOD_SUPPORTS_TRACING = ( + "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters +) + class {{ service.name }}Transport(abc.ABC): """Abstract transport class for {{ service.name }}.""" @@ -152,10 +159,7 @@ class {{ service.name }}Transport(abc.ABC): self._host = host self._client_options = client_options - # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments - # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility - # with older versions of google-api-core. - self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrap_with_tracing = _WRAP_METHOD_SUPPORTS_TRACING self._wrapped_methods: Dict[Callable, Callable] = {} @@ -168,15 +172,19 @@ class {{ service.name }}Transport(abc.ABC): kwargs["client_options"] = self._client_options try: kwargs["kind"] = self.kind - # Base transport raises NotImplementedError for abstract kind property. - # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + # The abstract BaseTransport class raises NotImplementedError for the kind property. + # Concrete transport subclasses (gRPC, REST) override kind, so this exception handler + # is unreachable during normal execution. Excluded from coverage check. except NotImplementedError: # pragma: NO COVER pass return gapic_v1.method.wrap_method(func, *args, **kwargs) - # Remove tracing-specific arguments if older google-api-core is installed - for k in ["client_options", "method_name", "is_streaming", "kind"]: - kwargs.pop(k, None) - return gapic_v1.method.wrap_method(func, *args, **kwargs) + # The fallback below strips tracing-specific arguments when an older version + # of google-api-core is installed (which does not accept client_options, etc.). + # Excluded from coverage because our CI and testing environments always install + # a modern version of google-api-core that supports tracing. + for k in ["client_options", "method_name", "is_streaming", "kind"]: # pragma: NO COVER + kwargs.pop(k, None) # pragma: NO COVER + return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. From 715f58b1f5a94e41286288ebf42f688a53bb6cb0 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 16 Sep 2026 15:41:44 -0400 Subject: [PATCH 36/43] refactor(observability): guard none span in response hook and tag interceptor --- .../google/api_core/_observability.py | 3 ++- .../tests/unit/test_observability.py | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index 2d8c50acbfa9..ae68dbe942ee 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -185,7 +185,7 @@ def _grpc_client_response_hook(span: Any, response: Any) -> None: span: The OpenTelemetry span. response: The gRPC response object or details. """ - if not span.is_recording(): + if span is None or not getattr(span, "is_recording", lambda: False)(): return # Guard against upstream async calls that invoke this hook on failures. @@ -249,6 +249,7 @@ def get_otel_interceptor( def otel_interceptor(channel: grpc.Channel) -> grpc.Channel: return otel_grpc.intercept_channel(channel, interceptor) + otel_interceptor._is_otel_interceptor = True # type: ignore[attr-defined] return otel_interceptor diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 4d7a0d283fd1..f57203520afb 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -542,3 +542,29 @@ def test_grpc_client_response_hook_error_status_value(): mock_span.status.status_code.value = 2 _observability._grpc_client_response_hook(mock_span, mock.Mock()) mock_span.set_attribute.assert_not_called() + + +def test_grpc_client_response_hook_none_span(): + """Proves that _grpc_client_response_hook gracefully handles span=None without error.""" + _observability._grpc_client_response_hook(None, mock.Mock()) + + +def test_get_otel_interceptor_sentinel_attribute(monkeypatch): + """Proves that get_otel_interceptor tags the returned closure with _is_otel_interceptor=True.""" + monkeypatch.setenv("GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED", "true") + options = ClientOptions() + + mock_otel = mock.Mock() + monkeypatch.setitem(sys.modules, "opentelemetry", mock_otel) + monkeypatch.setitem( + sys.modules, "opentelemetry.instrumentation", mock_otel.instrumentation + ) + monkeypatch.setitem( + sys.modules, + "opentelemetry.instrumentation.grpc", + mock_otel.instrumentation.grpc, + ) + + interceptor = _observability.get_otel_interceptor(client_options=options) + assert callable(interceptor) + assert getattr(interceptor, "_is_otel_interceptor", None) is True From c13f97af1c66617e0d868527c22d01750ed38e5c Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 16 Sep 2026 15:42:11 -0400 Subject: [PATCH 37/43] feat(gapic): harden otel interceptor deduplication and options checking in templates --- .../%name_%version/%sub/services/%service/client.py.j2 | 2 +- .../%name_%version/%sub/services/%service/transports/grpc.py.j2 | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 index 0d3cd51c33c4..55bf60b8955a 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 @@ -563,7 +563,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"client_options": client_options} if client_options else {}), + **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 index fc8b3e6ffb9e..77b36589ba8c 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2 @@ -285,6 +285,7 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport): _observability is not None and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None and otel_interceptor not in channel_interceptors + and not any(getattr(i, "_is_otel_interceptor", None) is True for i in channel_interceptors) ): channel_interceptors.append(otel_interceptor) From b1b7ce48f6e936b56bfecbed3e9a6a32a41af448 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 16 Sep 2026 15:42:52 -0400 Subject: [PATCH 38/43] test(gapic): update bazel integration goldens for interceptor hardening --- .../asset_v1/services/asset_service/client.py | 1061 +++++---- .../services/asset_service/transports/base.py | 445 ++-- .../services/asset_service/transports/grpc.py | 511 +++-- .../services/iam_credentials/client.py | 420 ++-- .../iam_credentials/transports/base.py | 177 +- .../iam_credentials/transports/grpc.py | 180 +- .../eventarc_v1/services/eventarc/client.py | 1966 ++++++++++------- .../services/eventarc/transports/base.py | 676 +++--- .../services/eventarc/transports/grpc.py | 766 ++++--- .../services/config_service_v2/client.py | 1242 ++++++----- .../config_service_v2/transports/base.py | 539 ++--- .../config_service_v2/transports/grpc.py | 600 ++--- .../services/logging_service_v2/client.py | 471 ++-- .../logging_service_v2/transports/base.py | 219 +- .../logging_service_v2/transports/grpc.py | 234 +- .../services/metrics_service_v2/client.py | 471 ++-- .../metrics_service_v2/transports/base.py | 202 +- .../metrics_service_v2/transports/grpc.py | 215 +- .../services/config_service_v2/client.py | 1242 ++++++----- .../config_service_v2/transports/base.py | 539 ++--- .../config_service_v2/transports/grpc.py | 600 ++--- .../services/logging_service_v2/client.py | 471 ++-- .../logging_service_v2/transports/base.py | 219 +- .../logging_service_v2/transports/grpc.py | 234 +- .../services/metrics_service_v2/client.py | 471 ++-- .../metrics_service_v2/transports/base.py | 202 +- .../metrics_service_v2/transports/grpc.py | 215 +- .../redis_v1/services/cloud_redis/client.py | 724 +++--- .../services/cloud_redis/transports/base.py | 284 +-- .../services/cloud_redis/transports/grpc.py | 320 +-- .../redis_v1/services/cloud_redis/client.py | 522 +++-- .../services/cloud_redis/transports/base.py | 210 +- .../services/cloud_redis/transports/grpc.py | 234 +- .../storage_batch_operations/client.py | 631 ++++-- .../transports/base.py | 254 ++- .../transports/grpc.py | 279 ++- 36 files changed, 10504 insertions(+), 7542 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py index cc1089e93d63..1fdf9ebd494c 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py @@ -13,29 +13,46 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import inspect import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.asset_v1 import gapic_version as package_version - +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.asset_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.asset_v1 import gapic_version as package_version +from google.cloud.asset_v1._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -44,6 +61,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -57,17 +75,17 @@ _LOGGER = std_logging.getLogger(__name__) -from google.cloud.asset_v1.services.asset_service import pagers -from google.cloud.asset_v1.types import asset_service -from google.cloud.asset_v1.types import assets -from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.rpc.status_pb2 as status_pb2 # type: ignore import google.type.expr_pb2 as expr_pb2 # type: ignore -from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from google.cloud.asset_v1.services.asset_service import pagers +from google.cloud.asset_v1.types import asset_service, assets +from google.longrunning import operations_pb2 # type: ignore + +from .transports.base import DEFAULT_CLIENT_INFO, AssetServiceTransport from .transports.grpc import AssetServiceGrpcTransport from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport from .transports.rest import AssetServiceRestTransport @@ -80,14 +98,16 @@ class AssetServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] _transport_registry["grpc"] = AssetServiceGrpcTransport _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport _transport_registry["rest"] = AssetServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AssetServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AssetServiceTransport]: """Returns an appropriate transport class. Args: @@ -147,8 +167,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetServiceClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -165,23 +184,36 @@ def transport(self) -> AssetServiceTransport: return self._transport @staticmethod - def access_level_path(access_policy: str,access_level: str,) -> str: + def access_level_path( + access_policy: str, + access_level: str, + ) -> str: """Returns a fully-qualified access_level string.""" - return "accessPolicies/{access_policy}/accessLevels/{access_level}".format(access_policy=access_policy, access_level=access_level, ) + return "accessPolicies/{access_policy}/accessLevels/{access_level}".format( + access_policy=access_policy, + access_level=access_level, + ) @staticmethod - def parse_access_level_path(path: str) -> Dict[str,str]: + def parse_access_level_path(path: str) -> Dict[str, str]: """Parses a access_level path into its component segments.""" - m = re.match(r"^accessPolicies/(?P.+?)/accessLevels/(?P.+?)$", path) + m = re.match( + r"^accessPolicies/(?P.+?)/accessLevels/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def access_policy_path(access_policy: str,) -> str: + def access_policy_path( + access_policy: str, + ) -> str: """Returns a fully-qualified access_policy string.""" - return "accessPolicies/{access_policy}".format(access_policy=access_policy, ) + return "accessPolicies/{access_policy}".format( + access_policy=access_policy, + ) @staticmethod - def parse_access_policy_path(path: str) -> Dict[str,str]: + def parse_access_policy_path(path: str) -> Dict[str, str]: """Parses a access_policy path into its component segments.""" m = re.match(r"^accessPolicies/(?P.+?)$", path) return m.groupdict() if m else {} @@ -192,112 +224,170 @@ def asset_path() -> str: return "*".format() @staticmethod - def parse_asset_path(path: str) -> Dict[str,str]: + def parse_asset_path(path: str) -> Dict[str, str]: """Parses a asset path into its component segments.""" m = re.match(r"^.*$", path) return m.groupdict() if m else {} @staticmethod - def feed_path(project: str,feed: str,) -> str: + def feed_path( + project: str, + feed: str, + ) -> str: """Returns a fully-qualified feed string.""" - return "projects/{project}/feeds/{feed}".format(project=project, feed=feed, ) + return "projects/{project}/feeds/{feed}".format( + project=project, + feed=feed, + ) @staticmethod - def parse_feed_path(path: str) -> Dict[str,str]: + def parse_feed_path(path: str) -> Dict[str, str]: """Parses a feed path into its component segments.""" m = re.match(r"^projects/(?P.+?)/feeds/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def inventory_path(project: str,location: str,instance: str,) -> str: + def inventory_path( + project: str, + location: str, + instance: str, + ) -> str: """Returns a fully-qualified inventory string.""" - return "projects/{project}/locations/{location}/instances/{instance}/inventory".format(project=project, location=location, instance=instance, ) + return "projects/{project}/locations/{location}/instances/{instance}/inventory".format( + project=project, + location=location, + instance=instance, + ) @staticmethod - def parse_inventory_path(path: str) -> Dict[str,str]: + def parse_inventory_path(path: str) -> Dict[str, str]: """Parses a inventory path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/inventory$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/inventory$", + path, + ) return m.groupdict() if m else {} @staticmethod - def saved_query_path(project: str,saved_query: str,) -> str: + def saved_query_path( + project: str, + saved_query: str, + ) -> str: """Returns a fully-qualified saved_query string.""" - return "projects/{project}/savedQueries/{saved_query}".format(project=project, saved_query=saved_query, ) + return "projects/{project}/savedQueries/{saved_query}".format( + project=project, + saved_query=saved_query, + ) @staticmethod - def parse_saved_query_path(path: str) -> Dict[str,str]: + def parse_saved_query_path(path: str) -> Dict[str, str]: """Parses a saved_query path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/savedQueries/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/savedQueries/(?P.+?)$", path + ) return m.groupdict() if m else {} @staticmethod - def service_perimeter_path(access_policy: str,service_perimeter: str,) -> str: + def service_perimeter_path( + access_policy: str, + service_perimeter: str, + ) -> str: """Returns a fully-qualified service_perimeter string.""" - return "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format(access_policy=access_policy, service_perimeter=service_perimeter, ) + return "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format( + access_policy=access_policy, + service_perimeter=service_perimeter, + ) @staticmethod - def parse_service_perimeter_path(path: str) -> Dict[str,str]: + def parse_service_perimeter_path(path: str) -> Dict[str, str]: """Parses a service_perimeter path into its component segments.""" - m = re.match(r"^accessPolicies/(?P.+?)/servicePerimeters/(?P.+?)$", path) + m = re.match( + r"^accessPolicies/(?P.+?)/servicePerimeters/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -329,14 +419,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -349,8 +443,10 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -389,15 +485,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -430,12 +529,16 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AssetServiceTransport, Callable[..., AssetServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, AssetServiceTransport, Callable[..., AssetServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the asset service client. Args: @@ -493,13 +596,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = AssetServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=AssetServiceClient._DEFAULT_UNIVERSE) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = AssetServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=AssetServiceClient._DEFAULT_UNIVERSE, + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -511,7 +624,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -520,35 +635,40 @@ def __init__(self, *, if transport_provided: # transport is a AssetServiceTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." + "When providing a transport instance, provide its scopes directly." ) self._transport = cast(AssetServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=AssetServiceClient._DEFAULT_UNIVERSE, - default_mtls_endpoint=AssetServiceClient.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=AssetServiceClient._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" or ( - self._use_mtls_endpoint == "auto" and self._client_cert_source - ), - )) + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=AssetServiceClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=AssetServiceClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=AssetServiceClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[AssetServiceTransport], Callable[..., AssetServiceTransport]] = ( + transport_init: Union[ + Type[AssetServiceTransport], Callable[..., AssetServiceTransport] + ] = ( AssetServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., AssetServiceTransport], transport) @@ -577,32 +697,45 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"client_options": client_options} if client_options else {}), + **( + {"client_options": client_options} + if client_options is not None + else {} + ), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.asset_v1.AssetServiceClient`.", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.cloud.asset.v1.AssetService", "credentialsType": None, - } + }, ) - def export_assets(self, - request: Optional[Union[asset_service.ExportAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def export_assets( + self, + request: Optional[Union[asset_service.ExportAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Exports assets with time and resource types to a given Cloud Storage location/BigQuery table. For Cloud Storage location destinations, the output format is newline-delimited JSON. Each @@ -686,9 +819,7 @@ def sample_export_assets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -713,14 +844,15 @@ def sample_export_assets(): # Done; return the response. return response - def list_assets(self, - request: Optional[Union[asset_service.ListAssetsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAssetsPager: + def list_assets( + self, + request: Optional[Union[asset_service.ListAssetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAssetsPager: r"""Lists assets with time and resource types and returns paged results in response. @@ -787,10 +919,14 @@ def sample_list_assets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -808,9 +944,7 @@ def sample_list_assets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -838,13 +972,16 @@ def sample_list_assets(): # Done; return the response. return response - def batch_get_assets_history(self, - request: Optional[Union[asset_service.BatchGetAssetsHistoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.BatchGetAssetsHistoryResponse: + def batch_get_assets_history( + self, + request: Optional[ + Union[asset_service.BatchGetAssetsHistoryRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.BatchGetAssetsHistoryResponse: r"""Batch gets the update history of assets that overlap a time window. For IAM_POLICY content, this API outputs history when the asset and its attached IAM POLICY both exist. This can @@ -907,9 +1044,7 @@ def sample_batch_get_assets_history(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -926,14 +1061,15 @@ def sample_batch_get_assets_history(): # Done; return the response. return response - def create_feed(self, - request: Optional[Union[asset_service.CreateFeedRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.Feed: + def create_feed( + self, + request: Optional[Union[asset_service.CreateFeedRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Creates a feed in a parent project/folder/organization to listen to its asset updates. @@ -1010,10 +1146,14 @@ def sample_create_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1031,9 +1171,7 @@ def sample_create_feed(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1050,14 +1188,15 @@ def sample_create_feed(): # Done; return the response. return response - def get_feed(self, - request: Optional[Union[asset_service.GetFeedRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.Feed: + def get_feed( + self, + request: Optional[Union[asset_service.GetFeedRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Gets details about an asset feed. .. code-block:: python @@ -1122,10 +1261,14 @@ def sample_get_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1143,9 +1286,7 @@ def sample_get_feed(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1162,14 +1303,15 @@ def sample_get_feed(): # Done; return the response. return response - def list_feeds(self, - request: Optional[Union[asset_service.ListFeedsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.ListFeedsResponse: + def list_feeds( + self, + request: Optional[Union[asset_service.ListFeedsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.ListFeedsResponse: r"""Lists all asset feeds in a parent project/folder/organization. @@ -1229,10 +1371,14 @@ def sample_list_feeds(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1250,9 +1396,7 @@ def sample_list_feeds(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1269,14 +1413,15 @@ def sample_list_feeds(): # Done; return the response. return response - def update_feed(self, - request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, - *, - feed: Optional[asset_service.Feed] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.Feed: + def update_feed( + self, + request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, + *, + feed: Optional[asset_service.Feed] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Updates an asset feed configuration. .. code-block:: python @@ -1345,10 +1490,14 @@ def sample_update_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [feed] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1366,9 +1515,9 @@ def sample_update_feed(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("feed.name", request.feed.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("feed.name", request.feed.name),) + ), ) # Validate the universe domain. @@ -1385,14 +1534,15 @@ def sample_update_feed(): # Done; return the response. return response - def delete_feed(self, - request: Optional[Union[asset_service.DeleteFeedRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_feed( + self, + request: Optional[Union[asset_service.DeleteFeedRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes an asset feed. .. code-block:: python @@ -1442,10 +1592,14 @@ def sample_delete_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1463,9 +1617,7 @@ def sample_delete_feed(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1479,16 +1631,17 @@ def sample_delete_feed(): metadata=metadata, ) - def search_all_resources(self, - request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - asset_types: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.SearchAllResourcesPager: + def search_all_resources( + self, + request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + asset_types: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchAllResourcesPager: r"""Searches all Google Cloud resources within the specified scope, such as a project, folder, or organization. The caller must be granted the ``cloudasset.assets.searchAllResources`` permission @@ -1691,10 +1844,14 @@ def sample_search_all_resources(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, query, asset_types] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1716,9 +1873,7 @@ def sample_search_all_resources(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -1746,15 +1901,18 @@ def sample_search_all_resources(): # Done; return the response. return response - def search_all_iam_policies(self, - request: Optional[Union[asset_service.SearchAllIamPoliciesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.SearchAllIamPoliciesPager: + def search_all_iam_policies( + self, + request: Optional[ + Union[asset_service.SearchAllIamPoliciesRequest, dict] + ] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchAllIamPoliciesPager: r"""Searches all IAM policies within the specified scope, such as a project, folder, or organization. The caller must be granted the ``cloudasset.assets.searchAllIamPolicies`` permission on the @@ -1884,10 +2042,14 @@ def sample_search_all_iam_policies(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, query] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1907,9 +2069,7 @@ def sample_search_all_iam_policies(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -1937,13 +2097,14 @@ def sample_search_all_iam_policies(): # Done; return the response. return response - def analyze_iam_policy(self, - request: Optional[Union[asset_service.AnalyzeIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.AnalyzeIamPolicyResponse: + def analyze_iam_policy( + self, + request: Optional[Union[asset_service.AnalyzeIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.AnalyzeIamPolicyResponse: r"""Analyzes IAM policies to answer which identities have what accesses on which resources. @@ -2007,9 +2168,9 @@ def sample_analyze_iam_policy(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("analysis_query.scope", request.analysis_query.scope), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("analysis_query.scope", request.analysis_query.scope),) + ), ) # Validate the universe domain. @@ -2026,13 +2187,16 @@ def sample_analyze_iam_policy(): # Done; return the response. return response - def analyze_iam_policy_longrunning(self, - request: Optional[Union[asset_service.AnalyzeIamPolicyLongrunningRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def analyze_iam_policy_longrunning( + self, + request: Optional[ + Union[asset_service.AnalyzeIamPolicyLongrunningRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Analyzes IAM policies asynchronously to answer which identities have what accesses on which resources, and writes the analysis results to a Google Cloud Storage or a BigQuery destination. For @@ -2111,14 +2275,16 @@ def sample_analyze_iam_policy_longrunning(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_iam_policy_longrunning] + rpc = self._transport._wrapped_methods[ + self._transport.analyze_iam_policy_longrunning + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("analysis_query.scope", request.analysis_query.scope), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("analysis_query.scope", request.analysis_query.scope),) + ), ) # Validate the universe domain. @@ -2143,13 +2309,14 @@ def sample_analyze_iam_policy_longrunning(): # Done; return the response. return response - def analyze_move(self, - request: Optional[Union[asset_service.AnalyzeMoveRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.AnalyzeMoveResponse: + def analyze_move( + self, + request: Optional[Union[asset_service.AnalyzeMoveRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.AnalyzeMoveResponse: r"""Analyze moving a resource to a specified destination without kicking off the actual move. The analysis is best effort depending on the user's permissions of @@ -2216,9 +2383,7 @@ def sample_analyze_move(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -2235,13 +2400,14 @@ def sample_analyze_move(): # Done; return the response. return response - def query_assets(self, - request: Optional[Union[asset_service.QueryAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.QueryAssetsResponse: + def query_assets( + self, + request: Optional[Union[asset_service.QueryAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.QueryAssetsResponse: r"""Issue a job that queries assets using a SQL statement compatible with `BigQuery SQL `__. @@ -2314,9 +2480,7 @@ def sample_query_assets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2333,16 +2497,17 @@ def sample_query_assets(): # Done; return the response. return response - def create_saved_query(self, - request: Optional[Union[asset_service.CreateSavedQueryRequest, dict]] = None, - *, - parent: Optional[str] = None, - saved_query: Optional[asset_service.SavedQuery] = None, - saved_query_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.SavedQuery: + def create_saved_query( + self, + request: Optional[Union[asset_service.CreateSavedQueryRequest, dict]] = None, + *, + parent: Optional[str] = None, + saved_query: Optional[asset_service.SavedQuery] = None, + saved_query_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Creates a saved query in a parent project/folder/organization. @@ -2428,10 +2593,14 @@ def sample_create_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, saved_query, saved_query_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2453,9 +2622,7 @@ def sample_create_saved_query(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2472,14 +2639,15 @@ def sample_create_saved_query(): # Done; return the response. return response - def get_saved_query(self, - request: Optional[Union[asset_service.GetSavedQueryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.SavedQuery: + def get_saved_query( + self, + request: Optional[Union[asset_service.GetSavedQueryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Gets details about a saved query. .. code-block:: python @@ -2540,10 +2708,14 @@ def sample_get_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2561,9 +2733,7 @@ def sample_get_saved_query(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2580,14 +2750,15 @@ def sample_get_saved_query(): # Done; return the response. return response - def list_saved_queries(self, - request: Optional[Union[asset_service.ListSavedQueriesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListSavedQueriesPager: + def list_saved_queries( + self, + request: Optional[Union[asset_service.ListSavedQueriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSavedQueriesPager: r"""Lists all saved queries in a parent project/folder/organization. @@ -2654,10 +2825,14 @@ def sample_list_saved_queries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2675,9 +2850,7 @@ def sample_list_saved_queries(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2705,15 +2878,16 @@ def sample_list_saved_queries(): # Done; return the response. return response - def update_saved_query(self, - request: Optional[Union[asset_service.UpdateSavedQueryRequest, dict]] = None, - *, - saved_query: Optional[asset_service.SavedQuery] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.SavedQuery: + def update_saved_query( + self, + request: Optional[Union[asset_service.UpdateSavedQueryRequest, dict]] = None, + *, + saved_query: Optional[asset_service.SavedQuery] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Updates a saved query. .. code-block:: python @@ -2782,10 +2956,14 @@ def sample_update_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [saved_query, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2805,9 +2983,9 @@ def sample_update_saved_query(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("saved_query.name", request.saved_query.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("saved_query.name", request.saved_query.name),) + ), ) # Validate the universe domain. @@ -2824,14 +3002,15 @@ def sample_update_saved_query(): # Done; return the response. return response - def delete_saved_query(self, - request: Optional[Union[asset_service.DeleteSavedQueryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_saved_query( + self, + request: Optional[Union[asset_service.DeleteSavedQueryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a saved query. .. code-block:: python @@ -2883,10 +3062,14 @@ def sample_delete_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2904,9 +3087,7 @@ def sample_delete_saved_query(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2920,13 +3101,16 @@ def sample_delete_saved_query(): metadata=metadata, ) - def batch_get_effective_iam_policies(self, - request: Optional[Union[asset_service.BatchGetEffectiveIamPoliciesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: + def batch_get_effective_iam_policies( + self, + request: Optional[ + Union[asset_service.BatchGetEffectiveIamPoliciesRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: r"""Gets effective IAM policies for a batch of resources. .. code-block:: python @@ -2982,14 +3166,14 @@ def sample_batch_get_effective_iam_policies(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_get_effective_iam_policies] + rpc = self._transport._wrapped_methods[ + self._transport.batch_get_effective_iam_policies + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -3006,16 +3190,17 @@ def sample_batch_get_effective_iam_policies(): # Done; return the response. return response - def analyze_org_policies(self, - request: Optional[Union[asset_service.AnalyzeOrgPoliciesRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.AnalyzeOrgPoliciesPager: + def analyze_org_policies( + self, + request: Optional[Union[asset_service.AnalyzeOrgPoliciesRequest, dict]] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AnalyzeOrgPoliciesPager: r"""Analyzes organization policies under a scope. .. code-block:: python @@ -3109,10 +3294,14 @@ def sample_analyze_org_policies(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, constraint, filter] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3134,9 +3323,7 @@ def sample_analyze_org_policies(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -3164,16 +3351,19 @@ def sample_analyze_org_policies(): # Done; return the response. return response - def analyze_org_policy_governed_containers(self, - request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.AnalyzeOrgPolicyGovernedContainersPager: + def analyze_org_policy_governed_containers( + self, + request: Optional[ + Union[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, dict] + ] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AnalyzeOrgPolicyGovernedContainersPager: r"""Analyzes organization policies governed containers (projects, folders or organization) under a scope. @@ -3268,14 +3458,20 @@ def sample_analyze_org_policy_governed_containers(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, constraint, filter] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, asset_service.AnalyzeOrgPolicyGovernedContainersRequest): + if not isinstance( + request, asset_service.AnalyzeOrgPolicyGovernedContainersRequest + ): request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -3288,14 +3484,14 @@ def sample_analyze_org_policy_governed_containers(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_org_policy_governed_containers] + rpc = self._transport._wrapped_methods[ + self._transport.analyze_org_policy_governed_containers + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -3323,16 +3519,19 @@ def sample_analyze_org_policy_governed_containers(): # Done; return the response. return response - def analyze_org_policy_governed_assets(self, - request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.AnalyzeOrgPolicyGovernedAssetsPager: + def analyze_org_policy_governed_assets( + self, + request: Optional[ + Union[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, dict] + ] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AnalyzeOrgPolicyGovernedAssetsPager: r"""Analyzes organization policies governed assets (Google Cloud resources or policies) under a scope. This RPC supports custom constraints and the following canned constraints: @@ -3498,10 +3697,14 @@ def sample_analyze_org_policy_governed_assets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, constraint, filter] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3518,14 +3721,14 @@ def sample_analyze_org_policy_governed_assets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_org_policy_governed_assets] + rpc = self._transport._wrapped_methods[ + self._transport.analyze_org_policy_governed_assets + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -3608,8 +3811,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -3618,7 +3820,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -3627,16 +3833,9 @@ def get_operation( raise e - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "AssetServiceClient", -) +__all__ = ("AssetServiceClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py index 23fd770b2c5a..8fba875bffb2 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py @@ -17,49 +17,54 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.asset_v1 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.cloud.asset_v1 import gapic_version as package_version from google.cloud.asset_v1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +# Check once at module load time whether google-api-core's wrap_method supports +# OpenTelemetry tracing arguments (client_options, method_name, is_streaming, kind) +# to avoid recurring inspect.signature latency during client instantiation. +_WRAP_METHOD_SUPPORTS_TRACING = ( + "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters +) + class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'cloudasset.googleapis.com' + DEFAULT_HOST: str = "cloudasset.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -101,38 +106,47 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._client_options = client_options - # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments - # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility - # with older versions of google-api-core. - self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrap_with_tracing = _WRAP_METHOD_SUPPORTS_TRACING self._wrapped_methods: Dict[Callable, Callable] = {} @@ -145,15 +159,24 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["client_options"] = self._client_options try: kwargs["kind"] = self.kind - # Base transport raises NotImplementedError for abstract kind property. - # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + # The abstract BaseTransport class raises NotImplementedError for the kind property. + # Concrete transport subclasses (gRPC, REST) override kind, so this exception handler + # is unreachable during normal execution. Excluded from coverage check. except NotImplementedError: # pragma: NO COVER pass return gapic_v1.method.wrap_method(func, *args, **kwargs) - # Remove tracing-specific arguments if older google-api-core is installed - for k in ["client_options", "method_name", "is_streaming", "kind"]: - kwargs.pop(k, None) - return gapic_v1.method.wrap_method(func, *args, **kwargs) + # The fallback below strips tracing-specific arguments when an older version + # of google-api-core is installed (which does not accept client_options, etc.). + # Excluded from coverage because our CI and testing environments always install + # a modern version of google-api-core that supports tracing. + for k in [ + "client_options", + "method_name", + "is_streaming", + "kind", + ]: # pragma: NO COVER + kwargs.pop(k, None) # pragma: NO COVER + return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -370,14 +393,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -387,210 +410,248 @@ def operations_client(self): raise NotImplementedError() @property - def export_assets(self) -> Callable[ - [asset_service.ExportAssetsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def export_assets( + self, + ) -> Callable[ + [asset_service.ExportAssetsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def list_assets(self) -> Callable[ - [asset_service.ListAssetsRequest], - Union[ - asset_service.ListAssetsResponse, - Awaitable[asset_service.ListAssetsResponse] - ]]: + def list_assets( + self, + ) -> Callable[ + [asset_service.ListAssetsRequest], + Union[ + asset_service.ListAssetsResponse, + Awaitable[asset_service.ListAssetsResponse], + ], + ]: raise NotImplementedError() @property - def batch_get_assets_history(self) -> Callable[ - [asset_service.BatchGetAssetsHistoryRequest], - Union[ - asset_service.BatchGetAssetsHistoryResponse, - Awaitable[asset_service.BatchGetAssetsHistoryResponse] - ]]: + def batch_get_assets_history( + self, + ) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + Union[ + asset_service.BatchGetAssetsHistoryResponse, + Awaitable[asset_service.BatchGetAssetsHistoryResponse], + ], + ]: raise NotImplementedError() @property - def create_feed(self) -> Callable[ - [asset_service.CreateFeedRequest], - Union[ - asset_service.Feed, - Awaitable[asset_service.Feed] - ]]: + def create_feed( + self, + ) -> Callable[ + [asset_service.CreateFeedRequest], + Union[asset_service.Feed, Awaitable[asset_service.Feed]], + ]: raise NotImplementedError() @property - def get_feed(self) -> Callable[ - [asset_service.GetFeedRequest], - Union[ - asset_service.Feed, - Awaitable[asset_service.Feed] - ]]: + def get_feed( + self, + ) -> Callable[ + [asset_service.GetFeedRequest], + Union[asset_service.Feed, Awaitable[asset_service.Feed]], + ]: raise NotImplementedError() @property - def list_feeds(self) -> Callable[ - [asset_service.ListFeedsRequest], - Union[ - asset_service.ListFeedsResponse, - Awaitable[asset_service.ListFeedsResponse] - ]]: + def list_feeds( + self, + ) -> Callable[ + [asset_service.ListFeedsRequest], + Union[ + asset_service.ListFeedsResponse, Awaitable[asset_service.ListFeedsResponse] + ], + ]: raise NotImplementedError() @property - def update_feed(self) -> Callable[ - [asset_service.UpdateFeedRequest], - Union[ - asset_service.Feed, - Awaitable[asset_service.Feed] - ]]: + def update_feed( + self, + ) -> Callable[ + [asset_service.UpdateFeedRequest], + Union[asset_service.Feed, Awaitable[asset_service.Feed]], + ]: raise NotImplementedError() @property - def delete_feed(self) -> Callable[ - [asset_service.DeleteFeedRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_feed( + self, + ) -> Callable[ + [asset_service.DeleteFeedRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def search_all_resources(self) -> Callable[ - [asset_service.SearchAllResourcesRequest], - Union[ - asset_service.SearchAllResourcesResponse, - Awaitable[asset_service.SearchAllResourcesResponse] - ]]: + def search_all_resources( + self, + ) -> Callable[ + [asset_service.SearchAllResourcesRequest], + Union[ + asset_service.SearchAllResourcesResponse, + Awaitable[asset_service.SearchAllResourcesResponse], + ], + ]: raise NotImplementedError() @property - def search_all_iam_policies(self) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - Union[ - asset_service.SearchAllIamPoliciesResponse, - Awaitable[asset_service.SearchAllIamPoliciesResponse] - ]]: + def search_all_iam_policies( + self, + ) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + Union[ + asset_service.SearchAllIamPoliciesResponse, + Awaitable[asset_service.SearchAllIamPoliciesResponse], + ], + ]: raise NotImplementedError() @property - def analyze_iam_policy(self) -> Callable[ - [asset_service.AnalyzeIamPolicyRequest], - Union[ - asset_service.AnalyzeIamPolicyResponse, - Awaitable[asset_service.AnalyzeIamPolicyResponse] - ]]: + def analyze_iam_policy( + self, + ) -> Callable[ + [asset_service.AnalyzeIamPolicyRequest], + Union[ + asset_service.AnalyzeIamPolicyResponse, + Awaitable[asset_service.AnalyzeIamPolicyResponse], + ], + ]: raise NotImplementedError() @property - def analyze_iam_policy_longrunning(self) -> Callable[ - [asset_service.AnalyzeIamPolicyLongrunningRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def analyze_iam_policy_longrunning( + self, + ) -> Callable[ + [asset_service.AnalyzeIamPolicyLongrunningRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def analyze_move(self) -> Callable[ - [asset_service.AnalyzeMoveRequest], - Union[ - asset_service.AnalyzeMoveResponse, - Awaitable[asset_service.AnalyzeMoveResponse] - ]]: + def analyze_move( + self, + ) -> Callable[ + [asset_service.AnalyzeMoveRequest], + Union[ + asset_service.AnalyzeMoveResponse, + Awaitable[asset_service.AnalyzeMoveResponse], + ], + ]: raise NotImplementedError() @property - def query_assets(self) -> Callable[ - [asset_service.QueryAssetsRequest], - Union[ - asset_service.QueryAssetsResponse, - Awaitable[asset_service.QueryAssetsResponse] - ]]: + def query_assets( + self, + ) -> Callable[ + [asset_service.QueryAssetsRequest], + Union[ + asset_service.QueryAssetsResponse, + Awaitable[asset_service.QueryAssetsResponse], + ], + ]: raise NotImplementedError() @property - def create_saved_query(self) -> Callable[ - [asset_service.CreateSavedQueryRequest], - Union[ - asset_service.SavedQuery, - Awaitable[asset_service.SavedQuery] - ]]: + def create_saved_query( + self, + ) -> Callable[ + [asset_service.CreateSavedQueryRequest], + Union[asset_service.SavedQuery, Awaitable[asset_service.SavedQuery]], + ]: raise NotImplementedError() @property - def get_saved_query(self) -> Callable[ - [asset_service.GetSavedQueryRequest], - Union[ - asset_service.SavedQuery, - Awaitable[asset_service.SavedQuery] - ]]: + def get_saved_query( + self, + ) -> Callable[ + [asset_service.GetSavedQueryRequest], + Union[asset_service.SavedQuery, Awaitable[asset_service.SavedQuery]], + ]: raise NotImplementedError() @property - def list_saved_queries(self) -> Callable[ - [asset_service.ListSavedQueriesRequest], - Union[ - asset_service.ListSavedQueriesResponse, - Awaitable[asset_service.ListSavedQueriesResponse] - ]]: + def list_saved_queries( + self, + ) -> Callable[ + [asset_service.ListSavedQueriesRequest], + Union[ + asset_service.ListSavedQueriesResponse, + Awaitable[asset_service.ListSavedQueriesResponse], + ], + ]: raise NotImplementedError() @property - def update_saved_query(self) -> Callable[ - [asset_service.UpdateSavedQueryRequest], - Union[ - asset_service.SavedQuery, - Awaitable[asset_service.SavedQuery] - ]]: + def update_saved_query( + self, + ) -> Callable[ + [asset_service.UpdateSavedQueryRequest], + Union[asset_service.SavedQuery, Awaitable[asset_service.SavedQuery]], + ]: raise NotImplementedError() @property - def delete_saved_query(self) -> Callable[ - [asset_service.DeleteSavedQueryRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_saved_query( + self, + ) -> Callable[ + [asset_service.DeleteSavedQueryRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def batch_get_effective_iam_policies(self) -> Callable[ - [asset_service.BatchGetEffectiveIamPoliciesRequest], - Union[ - asset_service.BatchGetEffectiveIamPoliciesResponse, - Awaitable[asset_service.BatchGetEffectiveIamPoliciesResponse] - ]]: + def batch_get_effective_iam_policies( + self, + ) -> Callable[ + [asset_service.BatchGetEffectiveIamPoliciesRequest], + Union[ + asset_service.BatchGetEffectiveIamPoliciesResponse, + Awaitable[asset_service.BatchGetEffectiveIamPoliciesResponse], + ], + ]: raise NotImplementedError() @property - def analyze_org_policies(self) -> Callable[ - [asset_service.AnalyzeOrgPoliciesRequest], - Union[ - asset_service.AnalyzeOrgPoliciesResponse, - Awaitable[asset_service.AnalyzeOrgPoliciesResponse] - ]]: + def analyze_org_policies( + self, + ) -> Callable[ + [asset_service.AnalyzeOrgPoliciesRequest], + Union[ + asset_service.AnalyzeOrgPoliciesResponse, + Awaitable[asset_service.AnalyzeOrgPoliciesResponse], + ], + ]: raise NotImplementedError() @property - def analyze_org_policy_governed_containers(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], - Union[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse, - Awaitable[asset_service.AnalyzeOrgPolicyGovernedContainersResponse] - ]]: + def analyze_org_policy_governed_containers( + self, + ) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], + Union[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse, + Awaitable[asset_service.AnalyzeOrgPolicyGovernedContainersResponse], + ], + ]: raise NotImplementedError() @property - def analyze_org_policy_governed_assets(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], - Union[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, - Awaitable[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse] - ]]: + def analyze_org_policy_governed_assets( + self, + ) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], + Union[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, + Awaitable[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse], + ], + ]: raise NotImplementedError() @property @@ -607,6 +668,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'AssetServiceTransport', -) +__all__ = ("AssetServiceTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py index 1e65b025584f..ea3a12319655 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -17,17 +17,19 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -from google.api_core import operations_v1 + from google.api_core.grpc_helpers import ( + ClientInterceptor, # type: ignore[attr-defined] + ) from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 + # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -35,21 +37,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import proto # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.asset_v1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson -import google.protobuf.message -import proto # type: ignore - -from google.cloud.asset_v1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, AssetServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -59,7 +61,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -80,7 +84,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -91,7 +95,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -106,7 +114,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": client_call_details.method, "response": grpc_response, @@ -128,32 +136,35 @@ class AssetServiceGrpcTransport(AssetServiceTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'cloudasset.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], - ] + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -290,8 +301,17 @@ def __init__(self, *, channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None and otel_interceptor not in channel_interceptors + and not any( + getattr(i, "_is_otel_interceptor", None) is True + for i in channel_interceptors + ) ): channel_interceptors.append(otel_interceptor) @@ -300,22 +320,28 @@ def __init__(self, *, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) + self._grpc_channel = apply_interceptors( + self._grpc_channel, channel_interceptors + ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'cloudasset.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "cloudasset.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -351,13 +377,12 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property @@ -377,9 +402,9 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def export_assets(self) -> Callable[ - [asset_service.ExportAssetsRequest], - operations_pb2.Operation]: + def export_assets( + self, + ) -> Callable[[asset_service.ExportAssetsRequest], operations_pb2.Operation]: r"""Return a callable for the export assets method over gRPC. Exports assets with time and resource types to a given Cloud @@ -406,18 +431,18 @@ def export_assets(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'export_assets' not in self._stubs: - self._stubs['export_assets'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/ExportAssets', + if "export_assets" not in self._stubs: + self._stubs["export_assets"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/ExportAssets", request_serializer=asset_service.ExportAssetsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['export_assets'] + return self._stubs["export_assets"] @property - def list_assets(self) -> Callable[ - [asset_service.ListAssetsRequest], - asset_service.ListAssetsResponse]: + def list_assets( + self, + ) -> Callable[[asset_service.ListAssetsRequest], asset_service.ListAssetsResponse]: r"""Return a callable for the list assets method over gRPC. Lists assets with time and resource types and returns @@ -433,18 +458,21 @@ def list_assets(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_assets' not in self._stubs: - self._stubs['list_assets'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/ListAssets', + if "list_assets" not in self._stubs: + self._stubs["list_assets"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/ListAssets", request_serializer=asset_service.ListAssetsRequest.serialize, response_deserializer=asset_service.ListAssetsResponse.deserialize, ) - return self._stubs['list_assets'] + return self._stubs["list_assets"] @property - def batch_get_assets_history(self) -> Callable[ - [asset_service.BatchGetAssetsHistoryRequest], - asset_service.BatchGetAssetsHistoryResponse]: + def batch_get_assets_history( + self, + ) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + asset_service.BatchGetAssetsHistoryResponse, + ]: r"""Return a callable for the batch get assets history method over gRPC. Batch gets the update history of assets that overlap a time @@ -465,18 +493,18 @@ def batch_get_assets_history(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'batch_get_assets_history' not in self._stubs: - self._stubs['batch_get_assets_history'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/BatchGetAssetsHistory', + if "batch_get_assets_history" not in self._stubs: + self._stubs["batch_get_assets_history"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/BatchGetAssetsHistory", request_serializer=asset_service.BatchGetAssetsHistoryRequest.serialize, response_deserializer=asset_service.BatchGetAssetsHistoryResponse.deserialize, ) - return self._stubs['batch_get_assets_history'] + return self._stubs["batch_get_assets_history"] @property - def create_feed(self) -> Callable[ - [asset_service.CreateFeedRequest], - asset_service.Feed]: + def create_feed( + self, + ) -> Callable[[asset_service.CreateFeedRequest], asset_service.Feed]: r"""Return a callable for the create feed method over gRPC. Creates a feed in a parent @@ -493,18 +521,16 @@ def create_feed(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_feed' not in self._stubs: - self._stubs['create_feed'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/CreateFeed', + if "create_feed" not in self._stubs: + self._stubs["create_feed"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/CreateFeed", request_serializer=asset_service.CreateFeedRequest.serialize, response_deserializer=asset_service.Feed.deserialize, ) - return self._stubs['create_feed'] + return self._stubs["create_feed"] @property - def get_feed(self) -> Callable[ - [asset_service.GetFeedRequest], - asset_service.Feed]: + def get_feed(self) -> Callable[[asset_service.GetFeedRequest], asset_service.Feed]: r"""Return a callable for the get feed method over gRPC. Gets details about an asset feed. @@ -519,18 +545,18 @@ def get_feed(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_feed' not in self._stubs: - self._stubs['get_feed'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/GetFeed', + if "get_feed" not in self._stubs: + self._stubs["get_feed"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/GetFeed", request_serializer=asset_service.GetFeedRequest.serialize, response_deserializer=asset_service.Feed.deserialize, ) - return self._stubs['get_feed'] + return self._stubs["get_feed"] @property - def list_feeds(self) -> Callable[ - [asset_service.ListFeedsRequest], - asset_service.ListFeedsResponse]: + def list_feeds( + self, + ) -> Callable[[asset_service.ListFeedsRequest], asset_service.ListFeedsResponse]: r"""Return a callable for the list feeds method over gRPC. Lists all asset feeds in a parent @@ -546,18 +572,18 @@ def list_feeds(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_feeds' not in self._stubs: - self._stubs['list_feeds'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/ListFeeds', + if "list_feeds" not in self._stubs: + self._stubs["list_feeds"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/ListFeeds", request_serializer=asset_service.ListFeedsRequest.serialize, response_deserializer=asset_service.ListFeedsResponse.deserialize, ) - return self._stubs['list_feeds'] + return self._stubs["list_feeds"] @property - def update_feed(self) -> Callable[ - [asset_service.UpdateFeedRequest], - asset_service.Feed]: + def update_feed( + self, + ) -> Callable[[asset_service.UpdateFeedRequest], asset_service.Feed]: r"""Return a callable for the update feed method over gRPC. Updates an asset feed configuration. @@ -572,18 +598,18 @@ def update_feed(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_feed' not in self._stubs: - self._stubs['update_feed'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/UpdateFeed', + if "update_feed" not in self._stubs: + self._stubs["update_feed"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/UpdateFeed", request_serializer=asset_service.UpdateFeedRequest.serialize, response_deserializer=asset_service.Feed.deserialize, ) - return self._stubs['update_feed'] + return self._stubs["update_feed"] @property - def delete_feed(self) -> Callable[ - [asset_service.DeleteFeedRequest], - empty_pb2.Empty]: + def delete_feed( + self, + ) -> Callable[[asset_service.DeleteFeedRequest], empty_pb2.Empty]: r"""Return a callable for the delete feed method over gRPC. Deletes an asset feed. @@ -598,18 +624,21 @@ def delete_feed(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_feed' not in self._stubs: - self._stubs['delete_feed'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/DeleteFeed', + if "delete_feed" not in self._stubs: + self._stubs["delete_feed"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/DeleteFeed", request_serializer=asset_service.DeleteFeedRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_feed'] + return self._stubs["delete_feed"] @property - def search_all_resources(self) -> Callable[ - [asset_service.SearchAllResourcesRequest], - asset_service.SearchAllResourcesResponse]: + def search_all_resources( + self, + ) -> Callable[ + [asset_service.SearchAllResourcesRequest], + asset_service.SearchAllResourcesResponse, + ]: r"""Return a callable for the search all resources method over gRPC. Searches all Google Cloud resources within the specified scope, @@ -627,18 +656,21 @@ def search_all_resources(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'search_all_resources' not in self._stubs: - self._stubs['search_all_resources'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/SearchAllResources', + if "search_all_resources" not in self._stubs: + self._stubs["search_all_resources"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/SearchAllResources", request_serializer=asset_service.SearchAllResourcesRequest.serialize, response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, ) - return self._stubs['search_all_resources'] + return self._stubs["search_all_resources"] @property - def search_all_iam_policies(self) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - asset_service.SearchAllIamPoliciesResponse]: + def search_all_iam_policies( + self, + ) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + asset_service.SearchAllIamPoliciesResponse, + ]: r"""Return a callable for the search all iam policies method over gRPC. Searches all IAM policies within the specified scope, such as a @@ -656,18 +688,20 @@ def search_all_iam_policies(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'search_all_iam_policies' not in self._stubs: - self._stubs['search_all_iam_policies'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/SearchAllIamPolicies', + if "search_all_iam_policies" not in self._stubs: + self._stubs["search_all_iam_policies"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/SearchAllIamPolicies", request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, ) - return self._stubs['search_all_iam_policies'] + return self._stubs["search_all_iam_policies"] @property - def analyze_iam_policy(self) -> Callable[ - [asset_service.AnalyzeIamPolicyRequest], - asset_service.AnalyzeIamPolicyResponse]: + def analyze_iam_policy( + self, + ) -> Callable[ + [asset_service.AnalyzeIamPolicyRequest], asset_service.AnalyzeIamPolicyResponse + ]: r"""Return a callable for the analyze iam policy method over gRPC. Analyzes IAM policies to answer which identities have @@ -683,18 +717,20 @@ def analyze_iam_policy(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'analyze_iam_policy' not in self._stubs: - self._stubs['analyze_iam_policy'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeIamPolicy', + if "analyze_iam_policy" not in self._stubs: + self._stubs["analyze_iam_policy"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/AnalyzeIamPolicy", request_serializer=asset_service.AnalyzeIamPolicyRequest.serialize, response_deserializer=asset_service.AnalyzeIamPolicyResponse.deserialize, ) - return self._stubs['analyze_iam_policy'] + return self._stubs["analyze_iam_policy"] @property - def analyze_iam_policy_longrunning(self) -> Callable[ - [asset_service.AnalyzeIamPolicyLongrunningRequest], - operations_pb2.Operation]: + def analyze_iam_policy_longrunning( + self, + ) -> Callable[ + [asset_service.AnalyzeIamPolicyLongrunningRequest], operations_pb2.Operation + ]: r"""Return a callable for the analyze iam policy longrunning method over gRPC. Analyzes IAM policies asynchronously to answer which identities @@ -720,18 +756,22 @@ def analyze_iam_policy_longrunning(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'analyze_iam_policy_longrunning' not in self._stubs: - self._stubs['analyze_iam_policy_longrunning'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeIamPolicyLongrunning', - request_serializer=asset_service.AnalyzeIamPolicyLongrunningRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + if "analyze_iam_policy_longrunning" not in self._stubs: + self._stubs["analyze_iam_policy_longrunning"] = ( + self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/AnalyzeIamPolicyLongrunning", + request_serializer=asset_service.AnalyzeIamPolicyLongrunningRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) ) - return self._stubs['analyze_iam_policy_longrunning'] + return self._stubs["analyze_iam_policy_longrunning"] @property - def analyze_move(self) -> Callable[ - [asset_service.AnalyzeMoveRequest], - asset_service.AnalyzeMoveResponse]: + def analyze_move( + self, + ) -> Callable[ + [asset_service.AnalyzeMoveRequest], asset_service.AnalyzeMoveResponse + ]: r"""Return a callable for the analyze move method over gRPC. Analyze moving a resource to a specified destination @@ -752,18 +792,20 @@ def analyze_move(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'analyze_move' not in self._stubs: - self._stubs['analyze_move'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeMove', + if "analyze_move" not in self._stubs: + self._stubs["analyze_move"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/AnalyzeMove", request_serializer=asset_service.AnalyzeMoveRequest.serialize, response_deserializer=asset_service.AnalyzeMoveResponse.deserialize, ) - return self._stubs['analyze_move'] + return self._stubs["analyze_move"] @property - def query_assets(self) -> Callable[ - [asset_service.QueryAssetsRequest], - asset_service.QueryAssetsResponse]: + def query_assets( + self, + ) -> Callable[ + [asset_service.QueryAssetsRequest], asset_service.QueryAssetsResponse + ]: r"""Return a callable for the query assets method over gRPC. Issue a job that queries assets using a SQL statement compatible @@ -793,18 +835,18 @@ def query_assets(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'query_assets' not in self._stubs: - self._stubs['query_assets'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/QueryAssets', + if "query_assets" not in self._stubs: + self._stubs["query_assets"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/QueryAssets", request_serializer=asset_service.QueryAssetsRequest.serialize, response_deserializer=asset_service.QueryAssetsResponse.deserialize, ) - return self._stubs['query_assets'] + return self._stubs["query_assets"] @property - def create_saved_query(self) -> Callable[ - [asset_service.CreateSavedQueryRequest], - asset_service.SavedQuery]: + def create_saved_query( + self, + ) -> Callable[[asset_service.CreateSavedQueryRequest], asset_service.SavedQuery]: r"""Return a callable for the create saved query method over gRPC. Creates a saved query in a parent @@ -820,18 +862,18 @@ def create_saved_query(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_saved_query' not in self._stubs: - self._stubs['create_saved_query'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/CreateSavedQuery', + if "create_saved_query" not in self._stubs: + self._stubs["create_saved_query"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/CreateSavedQuery", request_serializer=asset_service.CreateSavedQueryRequest.serialize, response_deserializer=asset_service.SavedQuery.deserialize, ) - return self._stubs['create_saved_query'] + return self._stubs["create_saved_query"] @property - def get_saved_query(self) -> Callable[ - [asset_service.GetSavedQueryRequest], - asset_service.SavedQuery]: + def get_saved_query( + self, + ) -> Callable[[asset_service.GetSavedQueryRequest], asset_service.SavedQuery]: r"""Return a callable for the get saved query method over gRPC. Gets details about a saved query. @@ -846,18 +888,20 @@ def get_saved_query(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_saved_query' not in self._stubs: - self._stubs['get_saved_query'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/GetSavedQuery', + if "get_saved_query" not in self._stubs: + self._stubs["get_saved_query"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/GetSavedQuery", request_serializer=asset_service.GetSavedQueryRequest.serialize, response_deserializer=asset_service.SavedQuery.deserialize, ) - return self._stubs['get_saved_query'] + return self._stubs["get_saved_query"] @property - def list_saved_queries(self) -> Callable[ - [asset_service.ListSavedQueriesRequest], - asset_service.ListSavedQueriesResponse]: + def list_saved_queries( + self, + ) -> Callable[ + [asset_service.ListSavedQueriesRequest], asset_service.ListSavedQueriesResponse + ]: r"""Return a callable for the list saved queries method over gRPC. Lists all saved queries in a parent @@ -873,18 +917,18 @@ def list_saved_queries(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_saved_queries' not in self._stubs: - self._stubs['list_saved_queries'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/ListSavedQueries', + if "list_saved_queries" not in self._stubs: + self._stubs["list_saved_queries"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/ListSavedQueries", request_serializer=asset_service.ListSavedQueriesRequest.serialize, response_deserializer=asset_service.ListSavedQueriesResponse.deserialize, ) - return self._stubs['list_saved_queries'] + return self._stubs["list_saved_queries"] @property - def update_saved_query(self) -> Callable[ - [asset_service.UpdateSavedQueryRequest], - asset_service.SavedQuery]: + def update_saved_query( + self, + ) -> Callable[[asset_service.UpdateSavedQueryRequest], asset_service.SavedQuery]: r"""Return a callable for the update saved query method over gRPC. Updates a saved query. @@ -899,18 +943,18 @@ def update_saved_query(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_saved_query' not in self._stubs: - self._stubs['update_saved_query'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/UpdateSavedQuery', + if "update_saved_query" not in self._stubs: + self._stubs["update_saved_query"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/UpdateSavedQuery", request_serializer=asset_service.UpdateSavedQueryRequest.serialize, response_deserializer=asset_service.SavedQuery.deserialize, ) - return self._stubs['update_saved_query'] + return self._stubs["update_saved_query"] @property - def delete_saved_query(self) -> Callable[ - [asset_service.DeleteSavedQueryRequest], - empty_pb2.Empty]: + def delete_saved_query( + self, + ) -> Callable[[asset_service.DeleteSavedQueryRequest], empty_pb2.Empty]: r"""Return a callable for the delete saved query method over gRPC. Deletes a saved query. @@ -925,18 +969,21 @@ def delete_saved_query(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_saved_query' not in self._stubs: - self._stubs['delete_saved_query'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/DeleteSavedQuery', + if "delete_saved_query" not in self._stubs: + self._stubs["delete_saved_query"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/DeleteSavedQuery", request_serializer=asset_service.DeleteSavedQueryRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_saved_query'] + return self._stubs["delete_saved_query"] @property - def batch_get_effective_iam_policies(self) -> Callable[ - [asset_service.BatchGetEffectiveIamPoliciesRequest], - asset_service.BatchGetEffectiveIamPoliciesResponse]: + def batch_get_effective_iam_policies( + self, + ) -> Callable[ + [asset_service.BatchGetEffectiveIamPoliciesRequest], + asset_service.BatchGetEffectiveIamPoliciesResponse, + ]: r"""Return a callable for the batch get effective iam policies method over gRPC. @@ -952,18 +999,23 @@ def batch_get_effective_iam_policies(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'batch_get_effective_iam_policies' not in self._stubs: - self._stubs['batch_get_effective_iam_policies'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/BatchGetEffectiveIamPolicies', - request_serializer=asset_service.BatchGetEffectiveIamPoliciesRequest.serialize, - response_deserializer=asset_service.BatchGetEffectiveIamPoliciesResponse.deserialize, + if "batch_get_effective_iam_policies" not in self._stubs: + self._stubs["batch_get_effective_iam_policies"] = ( + self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/BatchGetEffectiveIamPolicies", + request_serializer=asset_service.BatchGetEffectiveIamPoliciesRequest.serialize, + response_deserializer=asset_service.BatchGetEffectiveIamPoliciesResponse.deserialize, + ) ) - return self._stubs['batch_get_effective_iam_policies'] + return self._stubs["batch_get_effective_iam_policies"] @property - def analyze_org_policies(self) -> Callable[ - [asset_service.AnalyzeOrgPoliciesRequest], - asset_service.AnalyzeOrgPoliciesResponse]: + def analyze_org_policies( + self, + ) -> Callable[ + [asset_service.AnalyzeOrgPoliciesRequest], + asset_service.AnalyzeOrgPoliciesResponse, + ]: r"""Return a callable for the analyze org policies method over gRPC. Analyzes organization policies under a scope. @@ -978,18 +1030,21 @@ def analyze_org_policies(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'analyze_org_policies' not in self._stubs: - self._stubs['analyze_org_policies'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicies', + if "analyze_org_policies" not in self._stubs: + self._stubs["analyze_org_policies"] = self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicies", request_serializer=asset_service.AnalyzeOrgPoliciesRequest.serialize, response_deserializer=asset_service.AnalyzeOrgPoliciesResponse.deserialize, ) - return self._stubs['analyze_org_policies'] + return self._stubs["analyze_org_policies"] @property - def analyze_org_policy_governed_containers(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], - asset_service.AnalyzeOrgPolicyGovernedContainersResponse]: + def analyze_org_policy_governed_containers( + self, + ) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], + asset_service.AnalyzeOrgPolicyGovernedContainersResponse, + ]: r"""Return a callable for the analyze org policy governed containers method over gRPC. @@ -1006,18 +1061,23 @@ def analyze_org_policy_governed_containers(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'analyze_org_policy_governed_containers' not in self._stubs: - self._stubs['analyze_org_policy_governed_containers'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedContainers', - request_serializer=asset_service.AnalyzeOrgPolicyGovernedContainersRequest.serialize, - response_deserializer=asset_service.AnalyzeOrgPolicyGovernedContainersResponse.deserialize, + if "analyze_org_policy_governed_containers" not in self._stubs: + self._stubs["analyze_org_policy_governed_containers"] = ( + self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedContainers", + request_serializer=asset_service.AnalyzeOrgPolicyGovernedContainersRequest.serialize, + response_deserializer=asset_service.AnalyzeOrgPolicyGovernedContainersResponse.deserialize, + ) ) - return self._stubs['analyze_org_policy_governed_containers'] + return self._stubs["analyze_org_policy_governed_containers"] @property - def analyze_org_policy_governed_assets(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]: + def analyze_org_policy_governed_assets( + self, + ) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, + ]: r"""Return a callable for the analyze org policy governed assets method over gRPC. @@ -1082,13 +1142,15 @@ def analyze_org_policy_governed_assets(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'analyze_org_policy_governed_assets' not in self._stubs: - self._stubs['analyze_org_policy_governed_assets'] = self._logged_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedAssets', - request_serializer=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest.serialize, - response_deserializer=asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.deserialize, + if "analyze_org_policy_governed_assets" not in self._stubs: + self._stubs["analyze_org_policy_governed_assets"] = ( + self._logged_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedAssets", + request_serializer=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest.serialize, + response_deserializer=asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.deserialize, + ) ) - return self._stubs['analyze_org_policy_governed_assets'] + return self._stubs["analyze_org_policy_governed_assets"] def close(self): self._logged_channel.close() @@ -1097,8 +1159,7 @@ def close(self): def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1116,6 +1177,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'AssetServiceGrpcTransport', -) +__all__ = ("AssetServiceGrpcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index 301e04b7f19d..28da012086f2 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -13,29 +13,46 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import inspect import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.iam.credentials_v1 import gapic_version as package_version - +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.iam.credentials_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.credentials_v1 import gapic_version as package_version +from google.iam.credentials_v1._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -44,6 +61,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -57,10 +75,11 @@ _LOGGER = std_logging.getLogger(__name__) -from google.iam.credentials_v1.types import common import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO +from google.iam.credentials_v1.types import common + +from .transports.base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport from .transports.grpc import IAMCredentialsGrpcTransport from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport from .transports.rest import IAMCredentialsRestTransport @@ -73,14 +92,16 @@ class IAMCredentialsClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[IAMCredentialsTransport]] _transport_registry["grpc"] = IAMCredentialsGrpcTransport _transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport _transport_registry["rest"] = IAMCredentialsRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[IAMCredentialsTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[IAMCredentialsTransport]: """Returns an appropriate transport class. Args: @@ -150,8 +171,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: IAMCredentialsClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -168,73 +188,106 @@ def transport(self) -> IAMCredentialsTransport: return self._transport @staticmethod - def service_account_path(project: str,service_account: str,) -> str: + def service_account_path( + project: str, + service_account: str, + ) -> str: """Returns a fully-qualified service_account string.""" - return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) + return "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) @staticmethod - def parse_service_account_path(path: str) -> Dict[str,str]: + def parse_service_account_path(path: str) -> Dict[str, str]: """Parses a service_account path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -266,14 +319,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -286,8 +343,10 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -326,15 +385,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -367,12 +429,16 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the iam credentials client. Args: @@ -430,13 +496,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = IAMCredentialsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=IAMCredentialsClient._DEFAULT_UNIVERSE) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = IAMCredentialsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=IAMCredentialsClient._DEFAULT_UNIVERSE, + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -448,7 +524,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -457,35 +535,40 @@ def __init__(self, *, if transport_provided: # transport is a IAMCredentialsTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." + "When providing a transport instance, provide its scopes directly." ) self._transport = cast(IAMCredentialsTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=IAMCredentialsClient._DEFAULT_UNIVERSE, - default_mtls_endpoint=IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" or ( - self._use_mtls_endpoint == "auto" and self._client_cert_source - ), - )) + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=IAMCredentialsClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[IAMCredentialsTransport], Callable[..., IAMCredentialsTransport]] = ( + transport_init: Union[ + Type[IAMCredentialsTransport], Callable[..., IAMCredentialsTransport] + ] = ( IAMCredentialsClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., IAMCredentialsTransport], transport) @@ -514,36 +597,49 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"client_options": client_options} if client_options else {}), + **( + {"client_options": client_options} + if client_options is not None + else {} + ), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.iam.credentials_v1.IAMCredentialsClient`.", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.iam.credentials.v1.IAMCredentials", "credentialsType": None, - } + }, ) - def generate_access_token(self, - request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - scope: Optional[MutableSequence[str]] = None, - lifetime: Optional[duration_pb2.Duration] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateAccessTokenResponse: + def generate_access_token( + self, + request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + scope: Optional[MutableSequence[str]] = None, + lifetime: Optional[duration_pb2.Duration] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateAccessTokenResponse: r"""Generates an OAuth 2.0 access token for a service account. @@ -644,10 +740,14 @@ def sample_generate_access_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, scope, lifetime] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -671,9 +771,7 @@ def sample_generate_access_token(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -690,17 +788,18 @@ def sample_generate_access_token(): # Done; return the response. return response - def generate_id_token(self, - request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - audience: Optional[str] = None, - include_email: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateIdTokenResponse: + def generate_id_token( + self, + request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + audience: Optional[str] = None, + include_email: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateIdTokenResponse: r"""Generates an OpenID Connect ID token for a service account. @@ -795,10 +894,14 @@ def sample_generate_id_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, audience, include_email] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -822,9 +925,7 @@ def sample_generate_id_token(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -841,16 +942,17 @@ def sample_generate_id_token(): # Done; return the response. return response - def sign_blob(self, - request: Optional[Union[common.SignBlobRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignBlobResponse: + def sign_blob( + self, + request: Optional[Union[common.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignBlobResponse: r"""Signs a blob using a service account's system-managed private key. @@ -934,10 +1036,14 @@ def sample_sign_blob(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -959,9 +1065,7 @@ def sample_sign_blob(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -978,16 +1082,17 @@ def sample_sign_blob(): # Done; return the response. return response - def sign_jwt(self, - request: Optional[Union[common.SignJwtRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignJwtResponse: + def sign_jwt( + self, + request: Optional[Union[common.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignJwtResponse: r"""Signs a JWT using a service account's system-managed private key. @@ -1074,10 +1179,14 @@ def sample_sign_jwt(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1099,9 +1208,7 @@ def sample_sign_jwt(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1132,14 +1239,9 @@ def __exit__(self, type, value, traceback): self.transport.close() - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "IAMCredentialsClient", -) +__all__ = ("IAMCredentialsClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py index dcbb46130e2e..a00063e535d0 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py @@ -17,46 +17,52 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.iam.credentials_v1 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core +import google.auth # type: ignore +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.iam.credentials_v1 import gapic_version as package_version from google.iam.credentials_v1.types import common +from google.oauth2 import service_account # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +# Check once at module load time whether google-api-core's wrap_method supports +# OpenTelemetry tracing arguments (client_options, method_name, is_streaming, kind) +# to avoid recurring inspect.signature latency during client instantiation. +_WRAP_METHOD_SUPPORTS_TRACING = ( + "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters +) + class IAMCredentialsTransport(abc.ABC): """Abstract transport class for IAMCredentials.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'iamcredentials.googleapis.com' + DEFAULT_HOST: str = "iamcredentials.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -98,38 +104,47 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._client_options = client_options - # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments - # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility - # with older versions of google-api-core. - self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrap_with_tracing = _WRAP_METHOD_SUPPORTS_TRACING self._wrapped_methods: Dict[Callable, Callable] = {} @@ -142,15 +157,24 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["client_options"] = self._client_options try: kwargs["kind"] = self.kind - # Base transport raises NotImplementedError for abstract kind property. - # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + # The abstract BaseTransport class raises NotImplementedError for the kind property. + # Concrete transport subclasses (gRPC, REST) override kind, so this exception handler + # is unreachable during normal execution. Excluded from coverage check. except NotImplementedError: # pragma: NO COVER pass return gapic_v1.method.wrap_method(func, *args, **kwargs) - # Remove tracing-specific arguments if older google-api-core is installed - for k in ["client_options", "method_name", "is_streaming", "kind"]: - kwargs.pop(k, None) - return gapic_v1.method.wrap_method(func, *args, **kwargs) + # The fallback below strips tracing-specific arguments when an older version + # of google-api-core is installed (which does not accept client_options, etc.). + # Excluded from coverage because our CI and testing environments always install + # a modern version of google-api-core that supports tracing. + for k in [ + "client_options", + "method_name", + "is_streaming", + "kind", + ]: # pragma: NO COVER + kwargs.pop(k, None) # pragma: NO COVER + return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -219,51 +243,56 @@ def _prep_wrapped_messages(self, client_info): client_info=client_info, method_name="google.iam.credentials.v1.IAMCredentials/SignJwt", ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def generate_access_token(self) -> Callable[ - [common.GenerateAccessTokenRequest], - Union[ - common.GenerateAccessTokenResponse, - Awaitable[common.GenerateAccessTokenResponse] - ]]: + def generate_access_token( + self, + ) -> Callable[ + [common.GenerateAccessTokenRequest], + Union[ + common.GenerateAccessTokenResponse, + Awaitable[common.GenerateAccessTokenResponse], + ], + ]: raise NotImplementedError() @property - def generate_id_token(self) -> Callable[ - [common.GenerateIdTokenRequest], - Union[ - common.GenerateIdTokenResponse, - Awaitable[common.GenerateIdTokenResponse] - ]]: + def generate_id_token( + self, + ) -> Callable[ + [common.GenerateIdTokenRequest], + Union[ + common.GenerateIdTokenResponse, Awaitable[common.GenerateIdTokenResponse] + ], + ]: raise NotImplementedError() @property - def sign_blob(self) -> Callable[ - [common.SignBlobRequest], - Union[ - common.SignBlobResponse, - Awaitable[common.SignBlobResponse] - ]]: + def sign_blob( + self, + ) -> Callable[ + [common.SignBlobRequest], + Union[common.SignBlobResponse, Awaitable[common.SignBlobResponse]], + ]: raise NotImplementedError() @property - def sign_jwt(self) -> Callable[ - [common.SignJwtRequest], - Union[ - common.SignJwtResponse, - Awaitable[common.SignJwtResponse] - ]]: + def sign_jwt( + self, + ) -> Callable[ + [common.SignJwtRequest], + Union[common.SignJwtResponse, Awaitable[common.SignJwtResponse]], + ]: raise NotImplementedError() @property @@ -271,6 +300,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'IAMCredentialsTransport', -) +__all__ = ("IAMCredentialsTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py index eda1d3b9cd6d..7c4b7421ee56 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py @@ -17,16 +17,19 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] + from google.api_core.grpc_helpers import ( + ClientInterceptor, # type: ignore[attr-defined] + ) from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 + # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -34,19 +37,19 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore +import google.auth # type: ignore +import google.protobuf.message +import proto # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.credentials_v1.types import common from google.protobuf.json_format import MessageToJson -import google.protobuf.message -import proto # type: ignore - -from google.iam.credentials_v1.types import common -from .base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -56,7 +59,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -77,7 +82,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -88,7 +93,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -103,7 +112,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": client_call_details.method, "response": grpc_response, @@ -134,32 +143,35 @@ class IAMCredentialsGrpcTransport(IAMCredentialsTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'iamcredentials.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], - ] + def __init__( + self, + *, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -295,8 +307,17 @@ def __init__(self, *, channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None and otel_interceptor not in channel_interceptors + and not any( + getattr(i, "_is_otel_interceptor", None) is True + for i in channel_interceptors + ) ): channel_interceptors.append(otel_interceptor) @@ -305,22 +326,28 @@ def __init__(self, *, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) + self._grpc_channel = apply_interceptors( + self._grpc_channel, channel_interceptors + ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'iamcredentials.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -356,19 +383,20 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property - def generate_access_token(self) -> Callable[ - [common.GenerateAccessTokenRequest], - common.GenerateAccessTokenResponse]: + def generate_access_token( + self, + ) -> Callable[ + [common.GenerateAccessTokenRequest], common.GenerateAccessTokenResponse + ]: r"""Return a callable for the generate access token method over gRPC. Generates an OAuth 2.0 access token for a service @@ -384,18 +412,18 @@ def generate_access_token(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'generate_access_token' not in self._stubs: - self._stubs['generate_access_token'] = self._logged_channel.unary_unary( - '/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken', + if "generate_access_token" not in self._stubs: + self._stubs["generate_access_token"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken", request_serializer=common.GenerateAccessTokenRequest.serialize, response_deserializer=common.GenerateAccessTokenResponse.deserialize, ) - return self._stubs['generate_access_token'] + return self._stubs["generate_access_token"] @property - def generate_id_token(self) -> Callable[ - [common.GenerateIdTokenRequest], - common.GenerateIdTokenResponse]: + def generate_id_token( + self, + ) -> Callable[[common.GenerateIdTokenRequest], common.GenerateIdTokenResponse]: r"""Return a callable for the generate id token method over gRPC. Generates an OpenID Connect ID token for a service @@ -411,18 +439,16 @@ def generate_id_token(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'generate_id_token' not in self._stubs: - self._stubs['generate_id_token'] = self._logged_channel.unary_unary( - '/google.iam.credentials.v1.IAMCredentials/GenerateIdToken', + if "generate_id_token" not in self._stubs: + self._stubs["generate_id_token"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/GenerateIdToken", request_serializer=common.GenerateIdTokenRequest.serialize, response_deserializer=common.GenerateIdTokenResponse.deserialize, ) - return self._stubs['generate_id_token'] + return self._stubs["generate_id_token"] @property - def sign_blob(self) -> Callable[ - [common.SignBlobRequest], - common.SignBlobResponse]: + def sign_blob(self) -> Callable[[common.SignBlobRequest], common.SignBlobResponse]: r"""Return a callable for the sign blob method over gRPC. Signs a blob using a service account's system-managed @@ -438,18 +464,16 @@ def sign_blob(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'sign_blob' not in self._stubs: - self._stubs['sign_blob'] = self._logged_channel.unary_unary( - '/google.iam.credentials.v1.IAMCredentials/SignBlob', + if "sign_blob" not in self._stubs: + self._stubs["sign_blob"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/SignBlob", request_serializer=common.SignBlobRequest.serialize, response_deserializer=common.SignBlobResponse.deserialize, ) - return self._stubs['sign_blob'] + return self._stubs["sign_blob"] @property - def sign_jwt(self) -> Callable[ - [common.SignJwtRequest], - common.SignJwtResponse]: + def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]: r"""Return a callable for the sign jwt method over gRPC. Signs a JWT using a service account's system-managed @@ -465,13 +489,13 @@ def sign_jwt(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'sign_jwt' not in self._stubs: - self._stubs['sign_jwt'] = self._logged_channel.unary_unary( - '/google.iam.credentials.v1.IAMCredentials/SignJwt', + if "sign_jwt" not in self._stubs: + self._stubs["sign_jwt"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/SignJwt", request_serializer=common.SignJwtRequest.serialize, response_deserializer=common.SignJwtResponse.deserialize, ) - return self._stubs['sign_jwt'] + return self._stubs["sign_jwt"] def close(self): self._logged_channel.close() @@ -481,6 +505,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'IAMCredentialsGrpcTransport', -) +__all__ = ("IAMCredentialsGrpcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index 08327225cefa..eb1371fa8494 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -13,29 +13,46 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import inspect import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.eventarc_v1 import gapic_version as package_version - +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.eventarc_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.eventarc_v1 import gapic_version as package_version +from google.cloud.eventarc_v1._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -44,6 +61,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -57,35 +75,42 @@ _LOGGER = std_logging.getLogger(__name__) +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.eventarc_v1.services.eventarc import pagers -from google.cloud.eventarc_v1.types import channel +from google.cloud.eventarc_v1.types import ( + channel, + channel_connection, + discovery, + enrollment, + eventarc, + google_api_source, + google_channel_config, + logging_config, + message_bus, + pipeline, + trigger, +) from google.cloud.eventarc_v1.types import channel as gce_channel -from google.cloud.eventarc_v1.types import channel_connection from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection -from google.cloud.eventarc_v1.types import discovery -from google.cloud.eventarc_v1.types import enrollment from google.cloud.eventarc_v1.types import enrollment as gce_enrollment -from google.cloud.eventarc_v1.types import eventarc -from google.cloud.eventarc_v1.types import google_api_source from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source -from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config -from google.cloud.eventarc_v1.types import logging_config -from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import ( + google_channel_config as gce_google_channel_config, +) from google.cloud.eventarc_v1.types import message_bus as gce_message_bus -from google.cloud.eventarc_v1.types import pipeline from google.cloud.eventarc_v1.types import pipeline as gce_pipeline -from google.cloud.eventarc_v1.types import trigger from google.cloud.eventarc_v1.types import trigger as gce_trigger -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -import google.api_core.operation as operation # type: ignore -import google.api_core.operation_async as operation_async # type: ignore -import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import EventarcTransport, DEFAULT_CLIENT_INFO +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore + +from .transports.base import DEFAULT_CLIENT_INFO, EventarcTransport from .transports.grpc import EventarcGrpcTransport from .transports.grpc_asyncio import EventarcGrpcAsyncIOTransport from .transports.rest import EventarcRestTransport @@ -98,14 +123,16 @@ class EventarcClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[EventarcTransport]] _transport_registry["grpc"] = EventarcGrpcTransport _transport_registry["grpc_asyncio"] = EventarcGrpcAsyncIOTransport _transport_registry["rest"] = EventarcRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EventarcTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[EventarcTransport]: """Returns an appropriate transport class. Args: @@ -168,8 +195,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: EventarcClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -186,124 +212,249 @@ def transport(self) -> EventarcTransport: return self._transport @staticmethod - def channel_path(project: str,location: str,channel: str,) -> str: + def channel_path( + project: str, + location: str, + channel: str, + ) -> str: """Returns a fully-qualified channel string.""" - return "projects/{project}/locations/{location}/channels/{channel}".format(project=project, location=location, channel=channel, ) + return "projects/{project}/locations/{location}/channels/{channel}".format( + project=project, + location=location, + channel=channel, + ) @staticmethod - def parse_channel_path(path: str) -> Dict[str,str]: + def parse_channel_path(path: str) -> Dict[str, str]: """Parses a channel path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/channels/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/channels/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def channel_connection_path(project: str,location: str,channel_connection: str,) -> str: + def channel_connection_path( + project: str, + location: str, + channel_connection: str, + ) -> str: """Returns a fully-qualified channel_connection string.""" - return "projects/{project}/locations/{location}/channelConnections/{channel_connection}".format(project=project, location=location, channel_connection=channel_connection, ) + return "projects/{project}/locations/{location}/channelConnections/{channel_connection}".format( + project=project, + location=location, + channel_connection=channel_connection, + ) @staticmethod - def parse_channel_connection_path(path: str) -> Dict[str,str]: + def parse_channel_connection_path(path: str) -> Dict[str, str]: """Parses a channel_connection path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/channelConnections/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/channelConnections/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def cloud_function_path(project: str,location: str,function: str,) -> str: + def cloud_function_path( + project: str, + location: str, + function: str, + ) -> str: """Returns a fully-qualified cloud_function string.""" - return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + return "projects/{project}/locations/{location}/functions/{function}".format( + project=project, + location=location, + function=function, + ) @staticmethod - def parse_cloud_function_path(path: str) -> Dict[str,str]: + def parse_cloud_function_path(path: str) -> Dict[str, str]: """Parses a cloud_function path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: + def crypto_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + ) -> str: """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str,str]: + def parse_crypto_key_path(path: str) -> Dict[str, str]: """Parses a crypto_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def enrollment_path(project: str,location: str,enrollment: str,) -> str: + def enrollment_path( + project: str, + location: str, + enrollment: str, + ) -> str: """Returns a fully-qualified enrollment string.""" - return "projects/{project}/locations/{location}/enrollments/{enrollment}".format(project=project, location=location, enrollment=enrollment, ) + return ( + "projects/{project}/locations/{location}/enrollments/{enrollment}".format( + project=project, + location=location, + enrollment=enrollment, + ) + ) @staticmethod - def parse_enrollment_path(path: str) -> Dict[str,str]: + def parse_enrollment_path(path: str) -> Dict[str, str]: """Parses a enrollment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/enrollments/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/enrollments/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def google_api_source_path(project: str,location: str,google_api_source: str,) -> str: + def google_api_source_path( + project: str, + location: str, + google_api_source: str, + ) -> str: """Returns a fully-qualified google_api_source string.""" - return "projects/{project}/locations/{location}/googleApiSources/{google_api_source}".format(project=project, location=location, google_api_source=google_api_source, ) + return "projects/{project}/locations/{location}/googleApiSources/{google_api_source}".format( + project=project, + location=location, + google_api_source=google_api_source, + ) @staticmethod - def parse_google_api_source_path(path: str) -> Dict[str,str]: + def parse_google_api_source_path(path: str) -> Dict[str, str]: """Parses a google_api_source path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/googleApiSources/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/googleApiSources/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def google_channel_config_path(project: str,location: str,) -> str: + def google_channel_config_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified google_channel_config string.""" - return "projects/{project}/locations/{location}/googleChannelConfig".format(project=project, location=location, ) + return "projects/{project}/locations/{location}/googleChannelConfig".format( + project=project, + location=location, + ) @staticmethod - def parse_google_channel_config_path(path: str) -> Dict[str,str]: + def parse_google_channel_config_path(path: str) -> Dict[str, str]: """Parses a google_channel_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/googleChannelConfig$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/googleChannelConfig$", + path, + ) return m.groupdict() if m else {} @staticmethod - def message_bus_path(project: str,location: str,message_bus: str,) -> str: + def message_bus_path( + project: str, + location: str, + message_bus: str, + ) -> str: """Returns a fully-qualified message_bus string.""" - return "projects/{project}/locations/{location}/messageBuses/{message_bus}".format(project=project, location=location, message_bus=message_bus, ) + return ( + "projects/{project}/locations/{location}/messageBuses/{message_bus}".format( + project=project, + location=location, + message_bus=message_bus, + ) + ) @staticmethod - def parse_message_bus_path(path: str) -> Dict[str,str]: + def parse_message_bus_path(path: str) -> Dict[str, str]: """Parses a message_bus path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/messageBuses/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/messageBuses/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def network_attachment_path(project: str,region: str,networkattachment: str,) -> str: + def network_attachment_path( + project: str, + region: str, + networkattachment: str, + ) -> str: """Returns a fully-qualified network_attachment string.""" - return "projects/{project}/regions/{region}/networkAttachments/{networkattachment}".format(project=project, region=region, networkattachment=networkattachment, ) + return "projects/{project}/regions/{region}/networkAttachments/{networkattachment}".format( + project=project, + region=region, + networkattachment=networkattachment, + ) @staticmethod - def parse_network_attachment_path(path: str) -> Dict[str,str]: + def parse_network_attachment_path(path: str) -> Dict[str, str]: """Parses a network_attachment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/regions/(?P.+?)/networkAttachments/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/regions/(?P.+?)/networkAttachments/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def pipeline_path(project: str,location: str,pipeline: str,) -> str: + def pipeline_path( + project: str, + location: str, + pipeline: str, + ) -> str: """Returns a fully-qualified pipeline string.""" - return "projects/{project}/locations/{location}/pipelines/{pipeline}".format(project=project, location=location, pipeline=pipeline, ) + return "projects/{project}/locations/{location}/pipelines/{pipeline}".format( + project=project, + location=location, + pipeline=pipeline, + ) @staticmethod - def parse_pipeline_path(path: str) -> Dict[str,str]: + def parse_pipeline_path(path: str) -> Dict[str, str]: """Parses a pipeline path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/pipelines/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/pipelines/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def provider_path(project: str,location: str,provider: str,) -> str: + def provider_path( + project: str, + location: str, + provider: str, + ) -> str: """Returns a fully-qualified provider string.""" - return "projects/{project}/locations/{location}/providers/{provider}".format(project=project, location=location, provider=provider, ) + return "projects/{project}/locations/{location}/providers/{provider}".format( + project=project, + location=location, + provider=provider, + ) @staticmethod - def parse_provider_path(path: str) -> Dict[str,str]: + def parse_provider_path(path: str) -> Dict[str, str]: """Parses a provider path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/providers/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/providers/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod @@ -312,112 +463,173 @@ def service_path() -> str: return "*".format() @staticmethod - def parse_service_path(path: str) -> Dict[str,str]: + def parse_service_path(path: str) -> Dict[str, str]: """Parses a service path into its component segments.""" m = re.match(r"^.*$", path) return m.groupdict() if m else {} @staticmethod - def service_account_path(project: str,service_account: str,) -> str: + def service_account_path( + project: str, + service_account: str, + ) -> str: """Returns a fully-qualified service_account string.""" - return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) + return "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) @staticmethod - def parse_service_account_path(path: str) -> Dict[str,str]: + def parse_service_account_path(path: str) -> Dict[str, str]: """Parses a service_account path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def topic_path(project: str,topic: str,) -> str: + def topic_path( + project: str, + topic: str, + ) -> str: """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + return "projects/{project}/topics/{topic}".format( + project=project, + topic=topic, + ) @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: + def parse_topic_path(path: str) -> Dict[str, str]: """Parses a topic path into its component segments.""" m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def trigger_path(project: str,location: str,trigger: str,) -> str: + def trigger_path( + project: str, + location: str, + trigger: str, + ) -> str: """Returns a fully-qualified trigger string.""" - return "projects/{project}/locations/{location}/triggers/{trigger}".format(project=project, location=location, trigger=trigger, ) + return "projects/{project}/locations/{location}/triggers/{trigger}".format( + project=project, + location=location, + trigger=trigger, + ) @staticmethod - def parse_trigger_path(path: str) -> Dict[str,str]: + def parse_trigger_path(path: str) -> Dict[str, str]: """Parses a trigger path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/triggers/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/triggers/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def workflow_path(project: str,location: str,workflow: str,) -> str: + def workflow_path( + project: str, + location: str, + workflow: str, + ) -> str: """Returns a fully-qualified workflow string.""" - return "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) + return "projects/{project}/locations/{location}/workflows/{workflow}".format( + project=project, + location=location, + workflow=workflow, + ) @staticmethod - def parse_workflow_path(path: str) -> Dict[str,str]: + def parse_workflow_path(path: str) -> Dict[str, str]: """Parses a workflow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -449,14 +661,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -469,8 +685,10 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -509,15 +727,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -550,12 +771,16 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EventarcTransport, Callable[..., EventarcTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, EventarcTransport, Callable[..., EventarcTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the eventarc client. Args: @@ -613,13 +838,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = EventarcClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=EventarcClient._DEFAULT_UNIVERSE) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = EventarcClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=EventarcClient._DEFAULT_UNIVERSE, + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -631,7 +866,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -640,35 +877,40 @@ def __init__(self, *, if transport_provided: # transport is a EventarcTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." + "When providing a transport instance, provide its scopes directly." ) self._transport = cast(EventarcTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=EventarcClient._DEFAULT_UNIVERSE, - default_mtls_endpoint=EventarcClient.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=EventarcClient._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" or ( - self._use_mtls_endpoint == "auto" and self._client_cert_source - ), - )) + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=EventarcClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=EventarcClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=EventarcClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[EventarcTransport], Callable[..., EventarcTransport]] = ( + transport_init: Union[ + Type[EventarcTransport], Callable[..., EventarcTransport] + ] = ( EventarcClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., EventarcTransport], transport) @@ -697,33 +939,46 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"client_options": client_options} if client_options else {}), + **( + {"client_options": client_options} + if client_options is not None + else {} + ), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.eventarc_v1.EventarcClient`.", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.cloud.eventarc.v1.Eventarc", "credentialsType": None, - } + }, ) - def get_trigger(self, - request: Optional[Union[eventarc.GetTriggerRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> trigger.Trigger: + def get_trigger( + self, + request: Optional[Union[eventarc.GetTriggerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> trigger.Trigger: r"""Get a single trigger. .. code-block:: python @@ -781,10 +1036,14 @@ def sample_get_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -802,9 +1061,7 @@ def sample_get_trigger(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -821,14 +1078,15 @@ def sample_get_trigger(): # Done; return the response. return response - def list_triggers(self, - request: Optional[Union[eventarc.ListTriggersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListTriggersPager: + def list_triggers( + self, + request: Optional[Union[eventarc.ListTriggersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTriggersPager: r"""List triggers. .. code-block:: python @@ -889,10 +1147,14 @@ def sample_list_triggers(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -910,9 +1172,7 @@ def sample_list_triggers(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -940,16 +1200,17 @@ def sample_list_triggers(): # Done; return the response. return response - def create_trigger(self, - request: Optional[Union[eventarc.CreateTriggerRequest, dict]] = None, - *, - parent: Optional[str] = None, - trigger: Optional[gce_trigger.Trigger] = None, - trigger_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_trigger( + self, + request: Optional[Union[eventarc.CreateTriggerRequest, dict]] = None, + *, + parent: Optional[str] = None, + trigger: Optional[gce_trigger.Trigger] = None, + trigger_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new trigger in a particular project and location. @@ -1036,10 +1297,14 @@ def sample_create_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, trigger, trigger_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1061,9 +1326,7 @@ def sample_create_trigger(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1088,16 +1351,17 @@ def sample_create_trigger(): # Done; return the response. return response - def update_trigger(self, - request: Optional[Union[eventarc.UpdateTriggerRequest, dict]] = None, - *, - trigger: Optional[gce_trigger.Trigger] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - allow_missing: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_trigger( + self, + request: Optional[Union[eventarc.UpdateTriggerRequest, dict]] = None, + *, + trigger: Optional[gce_trigger.Trigger] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + allow_missing: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single trigger. .. code-block:: python @@ -1176,10 +1440,14 @@ def sample_update_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [trigger, update_mask, allow_missing] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1201,9 +1469,9 @@ def sample_update_trigger(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("trigger.name", request.trigger.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("trigger.name", request.trigger.name),) + ), ) # Validate the universe domain. @@ -1228,15 +1496,16 @@ def sample_update_trigger(): # Done; return the response. return response - def delete_trigger(self, - request: Optional[Union[eventarc.DeleteTriggerRequest, dict]] = None, - *, - name: Optional[str] = None, - allow_missing: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_trigger( + self, + request: Optional[Union[eventarc.DeleteTriggerRequest, dict]] = None, + *, + name: Optional[str] = None, + allow_missing: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single trigger. .. code-block:: python @@ -1309,10 +1578,14 @@ def sample_delete_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, allow_missing] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1332,9 +1605,7 @@ def sample_delete_trigger(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1359,14 +1630,15 @@ def sample_delete_trigger(): # Done; return the response. return response - def get_channel(self, - request: Optional[Union[eventarc.GetChannelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> channel.Channel: + def get_channel( + self, + request: Optional[Union[eventarc.GetChannelRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> channel.Channel: r"""Get a single Channel. .. code-block:: python @@ -1430,10 +1702,14 @@ def sample_get_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1451,9 +1727,7 @@ def sample_get_channel(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1470,14 +1744,15 @@ def sample_get_channel(): # Done; return the response. return response - def list_channels(self, - request: Optional[Union[eventarc.ListChannelsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListChannelsPager: + def list_channels( + self, + request: Optional[Union[eventarc.ListChannelsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListChannelsPager: r"""List channels. .. code-block:: python @@ -1538,10 +1813,14 @@ def sample_list_channels(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1559,9 +1838,7 @@ def sample_list_channels(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1589,16 +1866,17 @@ def sample_list_channels(): # Done; return the response. return response - def create_channel(self, - request: Optional[Union[eventarc.CreateChannelRequest, dict]] = None, - *, - parent: Optional[str] = None, - channel: Optional[gce_channel.Channel] = None, - channel_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_channel( + self, + request: Optional[Union[eventarc.CreateChannelRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel: Optional[gce_channel.Channel] = None, + channel_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new channel in a particular project and location. @@ -1685,10 +1963,14 @@ def sample_create_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, channel, channel_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1710,9 +1992,7 @@ def sample_create_channel(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1737,15 +2017,16 @@ def sample_create_channel(): # Done; return the response. return response - def update_channel(self, - request: Optional[Union[eventarc.UpdateChannelRequest, dict]] = None, - *, - channel: Optional[gce_channel.Channel] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_channel( + self, + request: Optional[Union[eventarc.UpdateChannelRequest, dict]] = None, + *, + channel: Optional[gce_channel.Channel] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single channel. .. code-block:: python @@ -1819,10 +2100,14 @@ def sample_update_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [channel, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1842,9 +2127,9 @@ def sample_update_channel(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("channel.name", request.channel.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("channel.name", request.channel.name),) + ), ) # Validate the universe domain. @@ -1869,14 +2154,15 @@ def sample_update_channel(): # Done; return the response. return response - def delete_channel(self, - request: Optional[Union[eventarc.DeleteChannelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_channel( + self, + request: Optional[Union[eventarc.DeleteChannelRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single channel. .. code-block:: python @@ -1944,10 +2230,14 @@ def sample_delete_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1965,9 +2255,7 @@ def sample_delete_channel(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1992,14 +2280,15 @@ def sample_delete_channel(): # Done; return the response. return response - def get_provider(self, - request: Optional[Union[eventarc.GetProviderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> discovery.Provider: + def get_provider( + self, + request: Optional[Union[eventarc.GetProviderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> discovery.Provider: r"""Get a single Provider. .. code-block:: python @@ -2057,10 +2346,14 @@ def sample_get_provider(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2078,9 +2371,7 @@ def sample_get_provider(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2097,14 +2388,15 @@ def sample_get_provider(): # Done; return the response. return response - def list_providers(self, - request: Optional[Union[eventarc.ListProvidersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProvidersPager: + def list_providers( + self, + request: Optional[Union[eventarc.ListProvidersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProvidersPager: r"""List providers. .. code-block:: python @@ -2165,10 +2457,14 @@ def sample_list_providers(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2186,9 +2482,7 @@ def sample_list_providers(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2216,14 +2510,15 @@ def sample_list_providers(): # Done; return the response. return response - def get_channel_connection(self, - request: Optional[Union[eventarc.GetChannelConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> channel_connection.ChannelConnection: + def get_channel_connection( + self, + request: Optional[Union[eventarc.GetChannelConnectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> channel_connection.ChannelConnection: r"""Get a single ChannelConnection. .. code-block:: python @@ -2286,10 +2581,14 @@ def sample_get_channel_connection(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2307,9 +2606,7 @@ def sample_get_channel_connection(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2326,14 +2623,15 @@ def sample_get_channel_connection(): # Done; return the response. return response - def list_channel_connections(self, - request: Optional[Union[eventarc.ListChannelConnectionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListChannelConnectionsPager: + def list_channel_connections( + self, + request: Optional[Union[eventarc.ListChannelConnectionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListChannelConnectionsPager: r"""List channel connections. .. code-block:: python @@ -2395,10 +2693,14 @@ def sample_list_channel_connections(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2416,9 +2718,7 @@ def sample_list_channel_connections(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2446,16 +2746,17 @@ def sample_list_channel_connections(): # Done; return the response. return response - def create_channel_connection(self, - request: Optional[Union[eventarc.CreateChannelConnectionRequest, dict]] = None, - *, - parent: Optional[str] = None, - channel_connection: Optional[gce_channel_connection.ChannelConnection] = None, - channel_connection_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_channel_connection( + self, + request: Optional[Union[eventarc.CreateChannelConnectionRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel_connection: Optional[gce_channel_connection.ChannelConnection] = None, + channel_connection_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new ChannelConnection in a particular project and location. @@ -2543,10 +2844,14 @@ def sample_create_channel_connection(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, channel_connection, channel_connection_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2563,14 +2868,14 @@ def sample_create_channel_connection(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_channel_connection] + rpc = self._transport._wrapped_methods[ + self._transport.create_channel_connection + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2595,14 +2900,15 @@ def sample_create_channel_connection(): # Done; return the response. return response - def delete_channel_connection(self, - request: Optional[Union[eventarc.DeleteChannelConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_channel_connection( + self, + request: Optional[Union[eventarc.DeleteChannelConnectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single ChannelConnection. .. code-block:: python @@ -2669,10 +2975,14 @@ def sample_delete_channel_connection(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2685,14 +2995,14 @@ def sample_delete_channel_connection(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_channel_connection] + rpc = self._transport._wrapped_methods[ + self._transport.delete_channel_connection + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2717,14 +3027,15 @@ def sample_delete_channel_connection(): # Done; return the response. return response - def get_google_channel_config(self, - request: Optional[Union[eventarc.GetGoogleChannelConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> google_channel_config.GoogleChannelConfig: + def get_google_channel_config( + self, + request: Optional[Union[eventarc.GetGoogleChannelConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> google_channel_config.GoogleChannelConfig: r"""Get a GoogleChannelConfig. The name of the GoogleChannelConfig in the response is ALWAYS coded with projectID. @@ -2790,10 +3101,14 @@ def sample_get_google_channel_config(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2806,14 +3121,14 @@ def sample_get_google_channel_config(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_google_channel_config] + rpc = self._transport._wrapped_methods[ + self._transport.get_google_channel_config + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2830,15 +3145,20 @@ def sample_get_google_channel_config(): # Done; return the response. return response - def update_google_channel_config(self, - request: Optional[Union[eventarc.UpdateGoogleChannelConfigRequest, dict]] = None, - *, - google_channel_config: Optional[gce_google_channel_config.GoogleChannelConfig] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gce_google_channel_config.GoogleChannelConfig: + def update_google_channel_config( + self, + request: Optional[ + Union[eventarc.UpdateGoogleChannelConfigRequest, dict] + ] = None, + *, + google_channel_config: Optional[ + gce_google_channel_config.GoogleChannelConfig + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gce_google_channel_config.GoogleChannelConfig: r"""Update a single GoogleChannelConfig .. code-block:: python @@ -2912,10 +3232,14 @@ def sample_update_google_channel_config(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [google_channel_config, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2930,14 +3254,16 @@ def sample_update_google_channel_config(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_google_channel_config] + rpc = self._transport._wrapped_methods[ + self._transport.update_google_channel_config + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("google_channel_config.name", request.google_channel_config.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("google_channel_config.name", request.google_channel_config.name),) + ), ) # Validate the universe domain. @@ -2954,14 +3280,15 @@ def sample_update_google_channel_config(): # Done; return the response. return response - def get_message_bus(self, - request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> message_bus.MessageBus: + def get_message_bus( + self, + request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> message_bus.MessageBus: r"""Get a single MessageBus. .. code-block:: python @@ -3025,10 +3352,14 @@ def sample_get_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3046,9 +3377,7 @@ def sample_get_message_bus(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3065,14 +3394,15 @@ def sample_get_message_bus(): # Done; return the response. return response - def list_message_buses(self, - request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMessageBusesPager: + def list_message_buses( + self, + request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMessageBusesPager: r"""List message buses. .. code-block:: python @@ -3133,10 +3463,14 @@ def sample_list_message_buses(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3154,9 +3488,7 @@ def sample_list_message_buses(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3184,14 +3516,17 @@ def sample_list_message_buses(): # Done; return the response. return response - def list_message_bus_enrollments(self, - request: Optional[Union[eventarc.ListMessageBusEnrollmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMessageBusEnrollmentsPager: + def list_message_bus_enrollments( + self, + request: Optional[ + Union[eventarc.ListMessageBusEnrollmentsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMessageBusEnrollmentsPager: r"""List message bus enrollments. .. code-block:: python @@ -3253,10 +3588,14 @@ def sample_list_message_bus_enrollments(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3269,14 +3608,14 @@ def sample_list_message_bus_enrollments(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_message_bus_enrollments] + rpc = self._transport._wrapped_methods[ + self._transport.list_message_bus_enrollments + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3304,16 +3643,17 @@ def sample_list_message_bus_enrollments(): # Done; return the response. return response - def create_message_bus(self, - request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, - *, - parent: Optional[str] = None, - message_bus: Optional[gce_message_bus.MessageBus] = None, - message_bus_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_message_bus( + self, + request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, + *, + parent: Optional[str] = None, + message_bus: Optional[gce_message_bus.MessageBus] = None, + message_bus_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new MessageBus in a particular project and location. @@ -3395,10 +3735,14 @@ def sample_create_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, message_bus, message_bus_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3420,9 +3764,7 @@ def sample_create_message_bus(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3447,15 +3789,16 @@ def sample_create_message_bus(): # Done; return the response. return response - def update_message_bus(self, - request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, - *, - message_bus: Optional[gce_message_bus.MessageBus] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_message_bus( + self, + request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, + *, + message_bus: Optional[gce_message_bus.MessageBus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single message bus. .. code-block:: python @@ -3531,10 +3874,14 @@ def sample_update_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [message_bus, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3554,9 +3901,9 @@ def sample_update_message_bus(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("message_bus.name", request.message_bus.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("message_bus.name", request.message_bus.name),) + ), ) # Validate the universe domain. @@ -3581,15 +3928,16 @@ def sample_update_message_bus(): # Done; return the response. return response - def delete_message_bus(self, - request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_message_bus( + self, + request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single message bus. .. code-block:: python @@ -3664,10 +4012,14 @@ def sample_delete_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3687,9 +4039,7 @@ def sample_delete_message_bus(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3714,14 +4064,15 @@ def sample_delete_message_bus(): # Done; return the response. return response - def get_enrollment(self, - request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> enrollment.Enrollment: + def get_enrollment( + self, + request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> enrollment.Enrollment: r"""Get a single Enrollment. .. code-block:: python @@ -3783,10 +4134,14 @@ def sample_get_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3804,9 +4159,7 @@ def sample_get_enrollment(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3823,14 +4176,15 @@ def sample_get_enrollment(): # Done; return the response. return response - def list_enrollments(self, - request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListEnrollmentsPager: + def list_enrollments( + self, + request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEnrollmentsPager: r"""List Enrollments. .. code-block:: python @@ -3891,10 +4245,14 @@ def sample_list_enrollments(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3912,9 +4270,7 @@ def sample_list_enrollments(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3942,16 +4298,17 @@ def sample_list_enrollments(): # Done; return the response. return response - def create_enrollment(self, - request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, - *, - parent: Optional[str] = None, - enrollment: Optional[gce_enrollment.Enrollment] = None, - enrollment_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_enrollment( + self, + request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + enrollment: Optional[gce_enrollment.Enrollment] = None, + enrollment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new Enrollment in a particular project and location. @@ -4038,10 +4395,14 @@ def sample_create_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, enrollment, enrollment_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4063,9 +4424,7 @@ def sample_create_enrollment(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -4090,15 +4449,16 @@ def sample_create_enrollment(): # Done; return the response. return response - def update_enrollment(self, - request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, - *, - enrollment: Optional[gce_enrollment.Enrollment] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_enrollment( + self, + request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, + *, + enrollment: Optional[gce_enrollment.Enrollment] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single Enrollment. .. code-block:: python @@ -4179,10 +4539,14 @@ def sample_update_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [enrollment, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4202,9 +4566,9 @@ def sample_update_enrollment(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("enrollment.name", request.enrollment.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("enrollment.name", request.enrollment.name),) + ), ) # Validate the universe domain. @@ -4229,15 +4593,16 @@ def sample_update_enrollment(): # Done; return the response. return response - def delete_enrollment(self, - request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_enrollment( + self, + request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single Enrollment. .. code-block:: python @@ -4311,10 +4676,14 @@ def sample_delete_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4334,9 +4703,7 @@ def sample_delete_enrollment(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4361,14 +4728,15 @@ def sample_delete_enrollment(): # Done; return the response. return response - def get_pipeline(self, - request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pipeline.Pipeline: + def get_pipeline( + self, + request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pipeline.Pipeline: r"""Get a single Pipeline. .. code-block:: python @@ -4426,10 +4794,14 @@ def sample_get_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4447,9 +4819,7 @@ def sample_get_pipeline(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4466,14 +4836,15 @@ def sample_get_pipeline(): # Done; return the response. return response - def list_pipelines(self, - request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListPipelinesPager: + def list_pipelines( + self, + request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPipelinesPager: r"""List pipelines. .. code-block:: python @@ -4535,10 +4906,14 @@ def sample_list_pipelines(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4556,9 +4931,7 @@ def sample_list_pipelines(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -4586,16 +4959,17 @@ def sample_list_pipelines(): # Done; return the response. return response - def create_pipeline(self, - request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, - *, - parent: Optional[str] = None, - pipeline: Optional[gce_pipeline.Pipeline] = None, - pipeline_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_pipeline( + self, + request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, + *, + parent: Optional[str] = None, + pipeline: Optional[gce_pipeline.Pipeline] = None, + pipeline_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new Pipeline in a particular project and location. @@ -4679,10 +5053,14 @@ def sample_create_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, pipeline, pipeline_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4704,9 +5082,7 @@ def sample_create_pipeline(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -4731,15 +5107,16 @@ def sample_create_pipeline(): # Done; return the response. return response - def update_pipeline(self, - request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, - *, - pipeline: Optional[gce_pipeline.Pipeline] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_pipeline( + self, + request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, + *, + pipeline: Optional[gce_pipeline.Pipeline] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single pipeline. .. code-block:: python @@ -4815,10 +5192,14 @@ def sample_update_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [pipeline, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4838,9 +5219,9 @@ def sample_update_pipeline(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("pipeline.name", request.pipeline.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("pipeline.name", request.pipeline.name),) + ), ) # Validate the universe domain. @@ -4865,15 +5246,16 @@ def sample_update_pipeline(): # Done; return the response. return response - def delete_pipeline(self, - request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_pipeline( + self, + request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single pipeline. .. code-block:: python @@ -4946,10 +5328,14 @@ def sample_delete_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4969,9 +5355,7 @@ def sample_delete_pipeline(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4996,14 +5380,15 @@ def sample_delete_pipeline(): # Done; return the response. return response - def get_google_api_source(self, - request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> google_api_source.GoogleApiSource: + def get_google_api_source( + self, + request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> google_api_source.GoogleApiSource: r"""Get a single GoogleApiSource. .. code-block:: python @@ -5062,10 +5447,14 @@ def sample_get_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5083,9 +5472,7 @@ def sample_get_google_api_source(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -5102,14 +5489,15 @@ def sample_get_google_api_source(): # Done; return the response. return response - def list_google_api_sources(self, - request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListGoogleApiSourcesPager: + def list_google_api_sources( + self, + request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListGoogleApiSourcesPager: r"""List GoogleApiSources. .. code-block:: python @@ -5171,10 +5559,14 @@ def sample_list_google_api_sources(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5192,9 +5584,7 @@ def sample_list_google_api_sources(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -5222,16 +5612,17 @@ def sample_list_google_api_sources(): # Done; return the response. return response - def create_google_api_source(self, - request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, - google_api_source_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_google_api_source( + self, + request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + google_api_source_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new GoogleApiSource in a particular project and location. @@ -5319,10 +5710,14 @@ def sample_create_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, google_api_source, google_api_source_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5344,9 +5739,7 @@ def sample_create_google_api_source(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -5371,15 +5764,16 @@ def sample_create_google_api_source(): # Done; return the response. return response - def update_google_api_source(self, - request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, - *, - google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_google_api_source( + self, + request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, + *, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single GoogleApiSource. .. code-block:: python @@ -5459,10 +5853,14 @@ def sample_update_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [google_api_source, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5482,9 +5880,9 @@ def sample_update_google_api_source(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("google_api_source.name", request.google_api_source.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("google_api_source.name", request.google_api_source.name),) + ), ) # Validate the universe domain. @@ -5509,15 +5907,16 @@ def sample_update_google_api_source(): # Done; return the response. return response - def delete_google_api_source(self, - request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_google_api_source( + self, + request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single GoogleApiSource. .. code-block:: python @@ -5591,10 +5990,14 @@ def sample_delete_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5614,9 +6017,7 @@ def sample_delete_google_api_source(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -5696,8 +6097,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -5706,7 +6106,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -5756,8 +6160,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -5766,7 +6169,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -5820,15 +6227,19 @@ def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def cancel_operation( self, @@ -5875,15 +6286,19 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def set_iam_policy( self, @@ -5994,7 +6409,8 @@ def set_iam_policy( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request_pb.resource),)), + (("resource", request_pb.resource),) + ), ) # Validate the universe domain. @@ -6003,7 +6419,11 @@ def set_iam_policy( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -6121,7 +6541,8 @@ def get_iam_policy( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request_pb.resource),)), + (("resource", request_pb.resource),) + ), ) # Validate the universe domain. @@ -6130,7 +6551,11 @@ def get_iam_policy( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -6186,7 +6611,8 @@ def test_iam_permissions( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request_pb.resource),)), + (("resource", request_pb.resource),) + ), ) # Validate the universe domain. @@ -6195,7 +6621,11 @@ def test_iam_permissions( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -6245,8 +6675,7 @@ def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -6255,7 +6684,11 @@ def get_location( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -6305,8 +6738,7 @@ def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -6315,7 +6747,11 @@ def list_locations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -6324,9 +6760,9 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "EventarcClient", -) +__all__ = ("EventarcClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py index d5bfd80d5de1..96fb7810b76a 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py @@ -17,61 +17,72 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.eventarc_v1 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core +import google.auth # type: ignore +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.cloud.eventarc_v1 import gapic_version as package_version +from google.cloud.eventarc_v1.types import ( + channel, + channel_connection, + discovery, + enrollment, + eventarc, + google_api_source, + google_channel_config, + message_bus, + pipeline, + trigger, +) +from google.cloud.eventarc_v1.types import ( + google_channel_config as gce_google_channel_config, +) +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore -from google.cloud.eventarc_v1.types import channel -from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import discovery -from google.cloud.eventarc_v1.types import enrollment -from google.cloud.eventarc_v1.types import eventarc -from google.cloud.eventarc_v1.types import google_api_source -from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config -from google.cloud.eventarc_v1.types import message_bus -from google.cloud.eventarc_v1.types import pipeline -from google.cloud.eventarc_v1.types import trigger -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +# Check once at module load time whether google-api-core's wrap_method supports +# OpenTelemetry tracing arguments (client_options, method_name, is_streaming, kind) +# to avoid recurring inspect.signature latency during client instantiation. +_WRAP_METHOD_SUPPORTS_TRACING = ( + "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters +) + class EventarcTransport(abc.ABC): """Abstract transport class for Eventarc.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'eventarc.googleapis.com' + DEFAULT_HOST: str = "eventarc.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -113,38 +124,47 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._client_options = client_options - # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments - # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility - # with older versions of google-api-core. - self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrap_with_tracing = _WRAP_METHOD_SUPPORTS_TRACING self._wrapped_methods: Dict[Callable, Callable] = {} @@ -157,15 +177,24 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["client_options"] = self._client_options try: kwargs["kind"] = self.kind - # Base transport raises NotImplementedError for abstract kind property. - # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + # The abstract BaseTransport class raises NotImplementedError for the kind property. + # Concrete transport subclasses (gRPC, REST) override kind, so this exception handler + # is unreachable during normal execution. Excluded from coverage check. except NotImplementedError: # pragma: NO COVER pass return gapic_v1.method.wrap_method(func, *args, **kwargs) - # Remove tracing-specific arguments if older google-api-core is installed - for k in ["client_options", "method_name", "is_streaming", "kind"]: - kwargs.pop(k, None) - return gapic_v1.method.wrap_method(func, *args, **kwargs) + # The fallback below strips tracing-specific arguments when an older version + # of google-api-core is installed (which does not accept client_options, etc.). + # Excluded from coverage because our CI and testing environments always install + # a modern version of google-api-core that supports tracing. + for k in [ + "client_options", + "method_name", + "is_streaming", + "kind", + ]: # pragma: NO COVER + kwargs.pop(k, None) # pragma: NO COVER + return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -449,14 +478,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -466,354 +495,383 @@ def operations_client(self): raise NotImplementedError() @property - def get_trigger(self) -> Callable[ - [eventarc.GetTriggerRequest], - Union[ - trigger.Trigger, - Awaitable[trigger.Trigger] - ]]: + def get_trigger( + self, + ) -> Callable[ + [eventarc.GetTriggerRequest], Union[trigger.Trigger, Awaitable[trigger.Trigger]] + ]: raise NotImplementedError() @property - def list_triggers(self) -> Callable[ - [eventarc.ListTriggersRequest], - Union[ - eventarc.ListTriggersResponse, - Awaitable[eventarc.ListTriggersResponse] - ]]: + def list_triggers( + self, + ) -> Callable[ + [eventarc.ListTriggersRequest], + Union[eventarc.ListTriggersResponse, Awaitable[eventarc.ListTriggersResponse]], + ]: raise NotImplementedError() @property - def create_trigger(self) -> Callable[ - [eventarc.CreateTriggerRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_trigger( + self, + ) -> Callable[ + [eventarc.CreateTriggerRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_trigger(self) -> Callable[ - [eventarc.UpdateTriggerRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_trigger( + self, + ) -> Callable[ + [eventarc.UpdateTriggerRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_trigger(self) -> Callable[ - [eventarc.DeleteTriggerRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_trigger( + self, + ) -> Callable[ + [eventarc.DeleteTriggerRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def get_channel(self) -> Callable[ - [eventarc.GetChannelRequest], - Union[ - channel.Channel, - Awaitable[channel.Channel] - ]]: + def get_channel( + self, + ) -> Callable[ + [eventarc.GetChannelRequest], Union[channel.Channel, Awaitable[channel.Channel]] + ]: raise NotImplementedError() @property - def list_channels(self) -> Callable[ - [eventarc.ListChannelsRequest], - Union[ - eventarc.ListChannelsResponse, - Awaitable[eventarc.ListChannelsResponse] - ]]: + def list_channels( + self, + ) -> Callable[ + [eventarc.ListChannelsRequest], + Union[eventarc.ListChannelsResponse, Awaitable[eventarc.ListChannelsResponse]], + ]: raise NotImplementedError() @property - def create_channel_(self) -> Callable[ - [eventarc.CreateChannelRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_channel_( + self, + ) -> Callable[ + [eventarc.CreateChannelRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_channel(self) -> Callable[ - [eventarc.UpdateChannelRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_channel( + self, + ) -> Callable[ + [eventarc.UpdateChannelRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_channel(self) -> Callable[ - [eventarc.DeleteChannelRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_channel( + self, + ) -> Callable[ + [eventarc.DeleteChannelRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def get_provider(self) -> Callable[ - [eventarc.GetProviderRequest], - Union[ - discovery.Provider, - Awaitable[discovery.Provider] - ]]: + def get_provider( + self, + ) -> Callable[ + [eventarc.GetProviderRequest], + Union[discovery.Provider, Awaitable[discovery.Provider]], + ]: raise NotImplementedError() @property - def list_providers(self) -> Callable[ - [eventarc.ListProvidersRequest], - Union[ - eventarc.ListProvidersResponse, - Awaitable[eventarc.ListProvidersResponse] - ]]: + def list_providers( + self, + ) -> Callable[ + [eventarc.ListProvidersRequest], + Union[ + eventarc.ListProvidersResponse, Awaitable[eventarc.ListProvidersResponse] + ], + ]: raise NotImplementedError() @property - def get_channel_connection(self) -> Callable[ - [eventarc.GetChannelConnectionRequest], - Union[ - channel_connection.ChannelConnection, - Awaitable[channel_connection.ChannelConnection] - ]]: + def get_channel_connection( + self, + ) -> Callable[ + [eventarc.GetChannelConnectionRequest], + Union[ + channel_connection.ChannelConnection, + Awaitable[channel_connection.ChannelConnection], + ], + ]: raise NotImplementedError() @property - def list_channel_connections(self) -> Callable[ - [eventarc.ListChannelConnectionsRequest], - Union[ - eventarc.ListChannelConnectionsResponse, - Awaitable[eventarc.ListChannelConnectionsResponse] - ]]: + def list_channel_connections( + self, + ) -> Callable[ + [eventarc.ListChannelConnectionsRequest], + Union[ + eventarc.ListChannelConnectionsResponse, + Awaitable[eventarc.ListChannelConnectionsResponse], + ], + ]: raise NotImplementedError() @property - def create_channel_connection(self) -> Callable[ - [eventarc.CreateChannelConnectionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_channel_connection( + self, + ) -> Callable[ + [eventarc.CreateChannelConnectionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_channel_connection(self) -> Callable[ - [eventarc.DeleteChannelConnectionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_channel_connection( + self, + ) -> Callable[ + [eventarc.DeleteChannelConnectionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def get_google_channel_config(self) -> Callable[ - [eventarc.GetGoogleChannelConfigRequest], - Union[ - google_channel_config.GoogleChannelConfig, - Awaitable[google_channel_config.GoogleChannelConfig] - ]]: + def get_google_channel_config( + self, + ) -> Callable[ + [eventarc.GetGoogleChannelConfigRequest], + Union[ + google_channel_config.GoogleChannelConfig, + Awaitable[google_channel_config.GoogleChannelConfig], + ], + ]: raise NotImplementedError() @property - def update_google_channel_config(self) -> Callable[ - [eventarc.UpdateGoogleChannelConfigRequest], - Union[ - gce_google_channel_config.GoogleChannelConfig, - Awaitable[gce_google_channel_config.GoogleChannelConfig] - ]]: + def update_google_channel_config( + self, + ) -> Callable[ + [eventarc.UpdateGoogleChannelConfigRequest], + Union[ + gce_google_channel_config.GoogleChannelConfig, + Awaitable[gce_google_channel_config.GoogleChannelConfig], + ], + ]: raise NotImplementedError() @property - def get_message_bus(self) -> Callable[ - [eventarc.GetMessageBusRequest], - Union[ - message_bus.MessageBus, - Awaitable[message_bus.MessageBus] - ]]: + def get_message_bus( + self, + ) -> Callable[ + [eventarc.GetMessageBusRequest], + Union[message_bus.MessageBus, Awaitable[message_bus.MessageBus]], + ]: raise NotImplementedError() @property - def list_message_buses(self) -> Callable[ - [eventarc.ListMessageBusesRequest], - Union[ - eventarc.ListMessageBusesResponse, - Awaitable[eventarc.ListMessageBusesResponse] - ]]: + def list_message_buses( + self, + ) -> Callable[ + [eventarc.ListMessageBusesRequest], + Union[ + eventarc.ListMessageBusesResponse, + Awaitable[eventarc.ListMessageBusesResponse], + ], + ]: raise NotImplementedError() @property - def list_message_bus_enrollments(self) -> Callable[ - [eventarc.ListMessageBusEnrollmentsRequest], - Union[ - eventarc.ListMessageBusEnrollmentsResponse, - Awaitable[eventarc.ListMessageBusEnrollmentsResponse] - ]]: + def list_message_bus_enrollments( + self, + ) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + Union[ + eventarc.ListMessageBusEnrollmentsResponse, + Awaitable[eventarc.ListMessageBusEnrollmentsResponse], + ], + ]: raise NotImplementedError() @property - def create_message_bus(self) -> Callable[ - [eventarc.CreateMessageBusRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_message_bus( + self, + ) -> Callable[ + [eventarc.CreateMessageBusRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_message_bus(self) -> Callable[ - [eventarc.UpdateMessageBusRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_message_bus( + self, + ) -> Callable[ + [eventarc.UpdateMessageBusRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_message_bus(self) -> Callable[ - [eventarc.DeleteMessageBusRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_message_bus( + self, + ) -> Callable[ + [eventarc.DeleteMessageBusRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def get_enrollment(self) -> Callable[ - [eventarc.GetEnrollmentRequest], - Union[ - enrollment.Enrollment, - Awaitable[enrollment.Enrollment] - ]]: + def get_enrollment( + self, + ) -> Callable[ + [eventarc.GetEnrollmentRequest], + Union[enrollment.Enrollment, Awaitable[enrollment.Enrollment]], + ]: raise NotImplementedError() @property - def list_enrollments(self) -> Callable[ - [eventarc.ListEnrollmentsRequest], - Union[ - eventarc.ListEnrollmentsResponse, - Awaitable[eventarc.ListEnrollmentsResponse] - ]]: + def list_enrollments( + self, + ) -> Callable[ + [eventarc.ListEnrollmentsRequest], + Union[ + eventarc.ListEnrollmentsResponse, + Awaitable[eventarc.ListEnrollmentsResponse], + ], + ]: raise NotImplementedError() @property - def create_enrollment(self) -> Callable[ - [eventarc.CreateEnrollmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_enrollment( + self, + ) -> Callable[ + [eventarc.CreateEnrollmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_enrollment(self) -> Callable[ - [eventarc.UpdateEnrollmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_enrollment( + self, + ) -> Callable[ + [eventarc.UpdateEnrollmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_enrollment(self) -> Callable[ - [eventarc.DeleteEnrollmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_enrollment( + self, + ) -> Callable[ + [eventarc.DeleteEnrollmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def get_pipeline(self) -> Callable[ - [eventarc.GetPipelineRequest], - Union[ - pipeline.Pipeline, - Awaitable[pipeline.Pipeline] - ]]: + def get_pipeline( + self, + ) -> Callable[ + [eventarc.GetPipelineRequest], + Union[pipeline.Pipeline, Awaitable[pipeline.Pipeline]], + ]: raise NotImplementedError() @property - def list_pipelines(self) -> Callable[ - [eventarc.ListPipelinesRequest], - Union[ - eventarc.ListPipelinesResponse, - Awaitable[eventarc.ListPipelinesResponse] - ]]: + def list_pipelines( + self, + ) -> Callable[ + [eventarc.ListPipelinesRequest], + Union[ + eventarc.ListPipelinesResponse, Awaitable[eventarc.ListPipelinesResponse] + ], + ]: raise NotImplementedError() @property - def create_pipeline(self) -> Callable[ - [eventarc.CreatePipelineRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_pipeline( + self, + ) -> Callable[ + [eventarc.CreatePipelineRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_pipeline(self) -> Callable[ - [eventarc.UpdatePipelineRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_pipeline( + self, + ) -> Callable[ + [eventarc.UpdatePipelineRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_pipeline(self) -> Callable[ - [eventarc.DeletePipelineRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_pipeline( + self, + ) -> Callable[ + [eventarc.DeletePipelineRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def get_google_api_source(self) -> Callable[ - [eventarc.GetGoogleApiSourceRequest], - Union[ - google_api_source.GoogleApiSource, - Awaitable[google_api_source.GoogleApiSource] - ]]: + def get_google_api_source( + self, + ) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], + Union[ + google_api_source.GoogleApiSource, + Awaitable[google_api_source.GoogleApiSource], + ], + ]: raise NotImplementedError() @property - def list_google_api_sources(self) -> Callable[ - [eventarc.ListGoogleApiSourcesRequest], - Union[ - eventarc.ListGoogleApiSourcesResponse, - Awaitable[eventarc.ListGoogleApiSourcesResponse] - ]]: + def list_google_api_sources( + self, + ) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], + Union[ + eventarc.ListGoogleApiSourcesResponse, + Awaitable[eventarc.ListGoogleApiSourcesResponse], + ], + ]: raise NotImplementedError() @property - def create_google_api_source(self) -> Callable[ - [eventarc.CreateGoogleApiSourceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_google_api_source( + self, + ) -> Callable[ + [eventarc.CreateGoogleApiSourceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_google_api_source(self) -> Callable[ - [eventarc.UpdateGoogleApiSourceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_google_api_source( + self, + ) -> Callable[ + [eventarc.UpdateGoogleApiSourceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_google_api_source(self) -> Callable[ - [eventarc.DeleteGoogleApiSourceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_google_api_source( + self, + ) -> Callable[ + [eventarc.DeleteGoogleApiSourceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property @@ -821,7 +879,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -883,7 +944,8 @@ def test_iam_permissions( raise NotImplementedError() @property - def get_location(self, + def get_location( + self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -891,10 +953,14 @@ def get_location(self, raise NotImplementedError() @property - def list_locations(self, + def list_locations( + self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], ]: raise NotImplementedError() @@ -903,6 +969,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'EventarcTransport', -) +__all__ = ("EventarcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py index 30a2bb344f02..65dc139d76d4 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py @@ -17,17 +17,19 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -from google.api_core import operations_v1 + from google.api_core.grpc_helpers import ( + ClientInterceptor, # type: ignore[attr-defined] + ) from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 + # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -35,33 +37,39 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore +import google.auth # type: ignore +import google.protobuf.message +import proto # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.eventarc_v1.types import ( + channel, + channel_connection, + discovery, + enrollment, + eventarc, + google_api_source, + google_channel_config, + message_bus, + pipeline, + trigger, +) +from google.cloud.eventarc_v1.types import ( + google_channel_config as gce_google_channel_config, +) +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import proto # type: ignore -from google.cloud.eventarc_v1.types import channel -from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import discovery -from google.cloud.eventarc_v1.types import enrollment -from google.cloud.eventarc_v1.types import eventarc -from google.cloud.eventarc_v1.types import google_api_source -from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config -from google.cloud.eventarc_v1.types import message_bus -from google.cloud.eventarc_v1.types import pipeline -from google.cloud.eventarc_v1.types import trigger -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import EventarcTransport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, EventarcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -71,7 +79,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -92,7 +102,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -103,7 +113,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -118,7 +132,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": client_call_details.method, "response": grpc_response, @@ -142,32 +156,35 @@ class EventarcGrpcTransport(EventarcTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'eventarc.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], - ] + def __init__( + self, + *, + host: str = "eventarc.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -304,8 +321,17 @@ def __init__(self, *, channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None and otel_interceptor not in channel_interceptors + and not any( + getattr(i, "_is_otel_interceptor", None) is True + for i in channel_interceptors + ) ): channel_interceptors.append(otel_interceptor) @@ -314,22 +340,28 @@ def __init__(self, *, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) + self._grpc_channel = apply_interceptors( + self._grpc_channel, channel_interceptors + ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'eventarc.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "eventarc.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -365,13 +397,12 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property @@ -391,9 +422,7 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def get_trigger(self) -> Callable[ - [eventarc.GetTriggerRequest], - trigger.Trigger]: + def get_trigger(self) -> Callable[[eventarc.GetTriggerRequest], trigger.Trigger]: r"""Return a callable for the get trigger method over gRPC. Get a single trigger. @@ -408,18 +437,18 @@ def get_trigger(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_trigger' not in self._stubs: - self._stubs['get_trigger'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetTrigger', + if "get_trigger" not in self._stubs: + self._stubs["get_trigger"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetTrigger", request_serializer=eventarc.GetTriggerRequest.serialize, response_deserializer=trigger.Trigger.deserialize, ) - return self._stubs['get_trigger'] + return self._stubs["get_trigger"] @property - def list_triggers(self) -> Callable[ - [eventarc.ListTriggersRequest], - eventarc.ListTriggersResponse]: + def list_triggers( + self, + ) -> Callable[[eventarc.ListTriggersRequest], eventarc.ListTriggersResponse]: r"""Return a callable for the list triggers method over gRPC. List triggers. @@ -434,18 +463,18 @@ def list_triggers(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_triggers' not in self._stubs: - self._stubs['list_triggers'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListTriggers', + if "list_triggers" not in self._stubs: + self._stubs["list_triggers"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListTriggers", request_serializer=eventarc.ListTriggersRequest.serialize, response_deserializer=eventarc.ListTriggersResponse.deserialize, ) - return self._stubs['list_triggers'] + return self._stubs["list_triggers"] @property - def create_trigger(self) -> Callable[ - [eventarc.CreateTriggerRequest], - operations_pb2.Operation]: + def create_trigger( + self, + ) -> Callable[[eventarc.CreateTriggerRequest], operations_pb2.Operation]: r"""Return a callable for the create trigger method over gRPC. Create a new trigger in a particular project and @@ -461,18 +490,18 @@ def create_trigger(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_trigger' not in self._stubs: - self._stubs['create_trigger'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateTrigger', + if "create_trigger" not in self._stubs: + self._stubs["create_trigger"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreateTrigger", request_serializer=eventarc.CreateTriggerRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_trigger'] + return self._stubs["create_trigger"] @property - def update_trigger(self) -> Callable[ - [eventarc.UpdateTriggerRequest], - operations_pb2.Operation]: + def update_trigger( + self, + ) -> Callable[[eventarc.UpdateTriggerRequest], operations_pb2.Operation]: r"""Return a callable for the update trigger method over gRPC. Update a single trigger. @@ -487,18 +516,18 @@ def update_trigger(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_trigger' not in self._stubs: - self._stubs['update_trigger'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateTrigger', + if "update_trigger" not in self._stubs: + self._stubs["update_trigger"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdateTrigger", request_serializer=eventarc.UpdateTriggerRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_trigger'] + return self._stubs["update_trigger"] @property - def delete_trigger(self) -> Callable[ - [eventarc.DeleteTriggerRequest], - operations_pb2.Operation]: + def delete_trigger( + self, + ) -> Callable[[eventarc.DeleteTriggerRequest], operations_pb2.Operation]: r"""Return a callable for the delete trigger method over gRPC. Delete a single trigger. @@ -513,18 +542,16 @@ def delete_trigger(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_trigger' not in self._stubs: - self._stubs['delete_trigger'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteTrigger', + if "delete_trigger" not in self._stubs: + self._stubs["delete_trigger"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeleteTrigger", request_serializer=eventarc.DeleteTriggerRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_trigger'] + return self._stubs["delete_trigger"] @property - def get_channel(self) -> Callable[ - [eventarc.GetChannelRequest], - channel.Channel]: + def get_channel(self) -> Callable[[eventarc.GetChannelRequest], channel.Channel]: r"""Return a callable for the get channel method over gRPC. Get a single Channel. @@ -539,18 +566,18 @@ def get_channel(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_channel' not in self._stubs: - self._stubs['get_channel'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetChannel', + if "get_channel" not in self._stubs: + self._stubs["get_channel"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetChannel", request_serializer=eventarc.GetChannelRequest.serialize, response_deserializer=channel.Channel.deserialize, ) - return self._stubs['get_channel'] + return self._stubs["get_channel"] @property - def list_channels(self) -> Callable[ - [eventarc.ListChannelsRequest], - eventarc.ListChannelsResponse]: + def list_channels( + self, + ) -> Callable[[eventarc.ListChannelsRequest], eventarc.ListChannelsResponse]: r"""Return a callable for the list channels method over gRPC. List channels. @@ -565,18 +592,18 @@ def list_channels(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_channels' not in self._stubs: - self._stubs['list_channels'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListChannels', + if "list_channels" not in self._stubs: + self._stubs["list_channels"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListChannels", request_serializer=eventarc.ListChannelsRequest.serialize, response_deserializer=eventarc.ListChannelsResponse.deserialize, ) - return self._stubs['list_channels'] + return self._stubs["list_channels"] @property - def create_channel_(self) -> Callable[ - [eventarc.CreateChannelRequest], - operations_pb2.Operation]: + def create_channel_( + self, + ) -> Callable[[eventarc.CreateChannelRequest], operations_pb2.Operation]: r"""Return a callable for the create channel method over gRPC. Create a new channel in a particular project and @@ -592,18 +619,18 @@ def create_channel_(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_channel_' not in self._stubs: - self._stubs['create_channel_'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateChannel', + if "create_channel_" not in self._stubs: + self._stubs["create_channel_"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreateChannel", request_serializer=eventarc.CreateChannelRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_channel_'] + return self._stubs["create_channel_"] @property - def update_channel(self) -> Callable[ - [eventarc.UpdateChannelRequest], - operations_pb2.Operation]: + def update_channel( + self, + ) -> Callable[[eventarc.UpdateChannelRequest], operations_pb2.Operation]: r"""Return a callable for the update channel method over gRPC. Update a single channel. @@ -618,18 +645,18 @@ def update_channel(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_channel' not in self._stubs: - self._stubs['update_channel'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateChannel', + if "update_channel" not in self._stubs: + self._stubs["update_channel"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdateChannel", request_serializer=eventarc.UpdateChannelRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_channel'] + return self._stubs["update_channel"] @property - def delete_channel(self) -> Callable[ - [eventarc.DeleteChannelRequest], - operations_pb2.Operation]: + def delete_channel( + self, + ) -> Callable[[eventarc.DeleteChannelRequest], operations_pb2.Operation]: r"""Return a callable for the delete channel method over gRPC. Delete a single channel. @@ -644,18 +671,18 @@ def delete_channel(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_channel' not in self._stubs: - self._stubs['delete_channel'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteChannel', + if "delete_channel" not in self._stubs: + self._stubs["delete_channel"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeleteChannel", request_serializer=eventarc.DeleteChannelRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_channel'] + return self._stubs["delete_channel"] @property - def get_provider(self) -> Callable[ - [eventarc.GetProviderRequest], - discovery.Provider]: + def get_provider( + self, + ) -> Callable[[eventarc.GetProviderRequest], discovery.Provider]: r"""Return a callable for the get provider method over gRPC. Get a single Provider. @@ -670,18 +697,18 @@ def get_provider(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_provider' not in self._stubs: - self._stubs['get_provider'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetProvider', + if "get_provider" not in self._stubs: + self._stubs["get_provider"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetProvider", request_serializer=eventarc.GetProviderRequest.serialize, response_deserializer=discovery.Provider.deserialize, ) - return self._stubs['get_provider'] + return self._stubs["get_provider"] @property - def list_providers(self) -> Callable[ - [eventarc.ListProvidersRequest], - eventarc.ListProvidersResponse]: + def list_providers( + self, + ) -> Callable[[eventarc.ListProvidersRequest], eventarc.ListProvidersResponse]: r"""Return a callable for the list providers method over gRPC. List providers. @@ -696,18 +723,20 @@ def list_providers(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_providers' not in self._stubs: - self._stubs['list_providers'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListProviders', + if "list_providers" not in self._stubs: + self._stubs["list_providers"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListProviders", request_serializer=eventarc.ListProvidersRequest.serialize, response_deserializer=eventarc.ListProvidersResponse.deserialize, ) - return self._stubs['list_providers'] + return self._stubs["list_providers"] @property - def get_channel_connection(self) -> Callable[ - [eventarc.GetChannelConnectionRequest], - channel_connection.ChannelConnection]: + def get_channel_connection( + self, + ) -> Callable[ + [eventarc.GetChannelConnectionRequest], channel_connection.ChannelConnection + ]: r"""Return a callable for the get channel connection method over gRPC. Get a single ChannelConnection. @@ -722,18 +751,21 @@ def get_channel_connection(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_channel_connection' not in self._stubs: - self._stubs['get_channel_connection'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetChannelConnection', + if "get_channel_connection" not in self._stubs: + self._stubs["get_channel_connection"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetChannelConnection", request_serializer=eventarc.GetChannelConnectionRequest.serialize, response_deserializer=channel_connection.ChannelConnection.deserialize, ) - return self._stubs['get_channel_connection'] + return self._stubs["get_channel_connection"] @property - def list_channel_connections(self) -> Callable[ - [eventarc.ListChannelConnectionsRequest], - eventarc.ListChannelConnectionsResponse]: + def list_channel_connections( + self, + ) -> Callable[ + [eventarc.ListChannelConnectionsRequest], + eventarc.ListChannelConnectionsResponse, + ]: r"""Return a callable for the list channel connections method over gRPC. List channel connections. @@ -748,18 +780,18 @@ def list_channel_connections(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_channel_connections' not in self._stubs: - self._stubs['list_channel_connections'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListChannelConnections', + if "list_channel_connections" not in self._stubs: + self._stubs["list_channel_connections"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListChannelConnections", request_serializer=eventarc.ListChannelConnectionsRequest.serialize, response_deserializer=eventarc.ListChannelConnectionsResponse.deserialize, ) - return self._stubs['list_channel_connections'] + return self._stubs["list_channel_connections"] @property - def create_channel_connection(self) -> Callable[ - [eventarc.CreateChannelConnectionRequest], - operations_pb2.Operation]: + def create_channel_connection( + self, + ) -> Callable[[eventarc.CreateChannelConnectionRequest], operations_pb2.Operation]: r"""Return a callable for the create channel connection method over gRPC. Create a new ChannelConnection in a particular @@ -775,18 +807,18 @@ def create_channel_connection(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_channel_connection' not in self._stubs: - self._stubs['create_channel_connection'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateChannelConnection', + if "create_channel_connection" not in self._stubs: + self._stubs["create_channel_connection"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreateChannelConnection", request_serializer=eventarc.CreateChannelConnectionRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_channel_connection'] + return self._stubs["create_channel_connection"] @property - def delete_channel_connection(self) -> Callable[ - [eventarc.DeleteChannelConnectionRequest], - operations_pb2.Operation]: + def delete_channel_connection( + self, + ) -> Callable[[eventarc.DeleteChannelConnectionRequest], operations_pb2.Operation]: r"""Return a callable for the delete channel connection method over gRPC. Delete a single ChannelConnection. @@ -801,18 +833,21 @@ def delete_channel_connection(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_channel_connection' not in self._stubs: - self._stubs['delete_channel_connection'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteChannelConnection', + if "delete_channel_connection" not in self._stubs: + self._stubs["delete_channel_connection"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeleteChannelConnection", request_serializer=eventarc.DeleteChannelConnectionRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_channel_connection'] + return self._stubs["delete_channel_connection"] @property - def get_google_channel_config(self) -> Callable[ - [eventarc.GetGoogleChannelConfigRequest], - google_channel_config.GoogleChannelConfig]: + def get_google_channel_config( + self, + ) -> Callable[ + [eventarc.GetGoogleChannelConfigRequest], + google_channel_config.GoogleChannelConfig, + ]: r"""Return a callable for the get google channel config method over gRPC. Get a GoogleChannelConfig. @@ -829,18 +864,21 @@ def get_google_channel_config(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_google_channel_config' not in self._stubs: - self._stubs['get_google_channel_config'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetGoogleChannelConfig', + if "get_google_channel_config" not in self._stubs: + self._stubs["get_google_channel_config"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetGoogleChannelConfig", request_serializer=eventarc.GetGoogleChannelConfigRequest.serialize, response_deserializer=google_channel_config.GoogleChannelConfig.deserialize, ) - return self._stubs['get_google_channel_config'] + return self._stubs["get_google_channel_config"] @property - def update_google_channel_config(self) -> Callable[ - [eventarc.UpdateGoogleChannelConfigRequest], - gce_google_channel_config.GoogleChannelConfig]: + def update_google_channel_config( + self, + ) -> Callable[ + [eventarc.UpdateGoogleChannelConfigRequest], + gce_google_channel_config.GoogleChannelConfig, + ]: r"""Return a callable for the update google channel config method over gRPC. Update a single GoogleChannelConfig @@ -855,18 +893,20 @@ def update_google_channel_config(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_google_channel_config' not in self._stubs: - self._stubs['update_google_channel_config'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateGoogleChannelConfig', - request_serializer=eventarc.UpdateGoogleChannelConfigRequest.serialize, - response_deserializer=gce_google_channel_config.GoogleChannelConfig.deserialize, + if "update_google_channel_config" not in self._stubs: + self._stubs["update_google_channel_config"] = ( + self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdateGoogleChannelConfig", + request_serializer=eventarc.UpdateGoogleChannelConfigRequest.serialize, + response_deserializer=gce_google_channel_config.GoogleChannelConfig.deserialize, + ) ) - return self._stubs['update_google_channel_config'] + return self._stubs["update_google_channel_config"] @property - def get_message_bus(self) -> Callable[ - [eventarc.GetMessageBusRequest], - message_bus.MessageBus]: + def get_message_bus( + self, + ) -> Callable[[eventarc.GetMessageBusRequest], message_bus.MessageBus]: r"""Return a callable for the get message bus method over gRPC. Get a single MessageBus. @@ -881,18 +921,20 @@ def get_message_bus(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_message_bus' not in self._stubs: - self._stubs['get_message_bus'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetMessageBus', + if "get_message_bus" not in self._stubs: + self._stubs["get_message_bus"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetMessageBus", request_serializer=eventarc.GetMessageBusRequest.serialize, response_deserializer=message_bus.MessageBus.deserialize, ) - return self._stubs['get_message_bus'] + return self._stubs["get_message_bus"] @property - def list_message_buses(self) -> Callable[ - [eventarc.ListMessageBusesRequest], - eventarc.ListMessageBusesResponse]: + def list_message_buses( + self, + ) -> Callable[ + [eventarc.ListMessageBusesRequest], eventarc.ListMessageBusesResponse + ]: r"""Return a callable for the list message buses method over gRPC. List message buses. @@ -907,18 +949,21 @@ def list_message_buses(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_message_buses' not in self._stubs: - self._stubs['list_message_buses'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListMessageBuses', + if "list_message_buses" not in self._stubs: + self._stubs["list_message_buses"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListMessageBuses", request_serializer=eventarc.ListMessageBusesRequest.serialize, response_deserializer=eventarc.ListMessageBusesResponse.deserialize, ) - return self._stubs['list_message_buses'] + return self._stubs["list_message_buses"] @property - def list_message_bus_enrollments(self) -> Callable[ - [eventarc.ListMessageBusEnrollmentsRequest], - eventarc.ListMessageBusEnrollmentsResponse]: + def list_message_bus_enrollments( + self, + ) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + eventarc.ListMessageBusEnrollmentsResponse, + ]: r"""Return a callable for the list message bus enrollments method over gRPC. List message bus enrollments. @@ -933,18 +978,20 @@ def list_message_bus_enrollments(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_message_bus_enrollments' not in self._stubs: - self._stubs['list_message_bus_enrollments'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListMessageBusEnrollments', - request_serializer=eventarc.ListMessageBusEnrollmentsRequest.serialize, - response_deserializer=eventarc.ListMessageBusEnrollmentsResponse.deserialize, + if "list_message_bus_enrollments" not in self._stubs: + self._stubs["list_message_bus_enrollments"] = ( + self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListMessageBusEnrollments", + request_serializer=eventarc.ListMessageBusEnrollmentsRequest.serialize, + response_deserializer=eventarc.ListMessageBusEnrollmentsResponse.deserialize, + ) ) - return self._stubs['list_message_bus_enrollments'] + return self._stubs["list_message_bus_enrollments"] @property - def create_message_bus(self) -> Callable[ - [eventarc.CreateMessageBusRequest], - operations_pb2.Operation]: + def create_message_bus( + self, + ) -> Callable[[eventarc.CreateMessageBusRequest], operations_pb2.Operation]: r"""Return a callable for the create message bus method over gRPC. Create a new MessageBus in a particular project and @@ -960,18 +1007,18 @@ def create_message_bus(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_message_bus' not in self._stubs: - self._stubs['create_message_bus'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateMessageBus', + if "create_message_bus" not in self._stubs: + self._stubs["create_message_bus"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreateMessageBus", request_serializer=eventarc.CreateMessageBusRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_message_bus'] + return self._stubs["create_message_bus"] @property - def update_message_bus(self) -> Callable[ - [eventarc.UpdateMessageBusRequest], - operations_pb2.Operation]: + def update_message_bus( + self, + ) -> Callable[[eventarc.UpdateMessageBusRequest], operations_pb2.Operation]: r"""Return a callable for the update message bus method over gRPC. Update a single message bus. @@ -986,18 +1033,18 @@ def update_message_bus(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_message_bus' not in self._stubs: - self._stubs['update_message_bus'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateMessageBus', + if "update_message_bus" not in self._stubs: + self._stubs["update_message_bus"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdateMessageBus", request_serializer=eventarc.UpdateMessageBusRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_message_bus'] + return self._stubs["update_message_bus"] @property - def delete_message_bus(self) -> Callable[ - [eventarc.DeleteMessageBusRequest], - operations_pb2.Operation]: + def delete_message_bus( + self, + ) -> Callable[[eventarc.DeleteMessageBusRequest], operations_pb2.Operation]: r"""Return a callable for the delete message bus method over gRPC. Delete a single message bus. @@ -1012,18 +1059,18 @@ def delete_message_bus(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_message_bus' not in self._stubs: - self._stubs['delete_message_bus'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteMessageBus', + if "delete_message_bus" not in self._stubs: + self._stubs["delete_message_bus"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeleteMessageBus", request_serializer=eventarc.DeleteMessageBusRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_message_bus'] + return self._stubs["delete_message_bus"] @property - def get_enrollment(self) -> Callable[ - [eventarc.GetEnrollmentRequest], - enrollment.Enrollment]: + def get_enrollment( + self, + ) -> Callable[[eventarc.GetEnrollmentRequest], enrollment.Enrollment]: r"""Return a callable for the get enrollment method over gRPC. Get a single Enrollment. @@ -1038,18 +1085,18 @@ def get_enrollment(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_enrollment' not in self._stubs: - self._stubs['get_enrollment'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetEnrollment', + if "get_enrollment" not in self._stubs: + self._stubs["get_enrollment"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetEnrollment", request_serializer=eventarc.GetEnrollmentRequest.serialize, response_deserializer=enrollment.Enrollment.deserialize, ) - return self._stubs['get_enrollment'] + return self._stubs["get_enrollment"] @property - def list_enrollments(self) -> Callable[ - [eventarc.ListEnrollmentsRequest], - eventarc.ListEnrollmentsResponse]: + def list_enrollments( + self, + ) -> Callable[[eventarc.ListEnrollmentsRequest], eventarc.ListEnrollmentsResponse]: r"""Return a callable for the list enrollments method over gRPC. List Enrollments. @@ -1064,18 +1111,18 @@ def list_enrollments(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_enrollments' not in self._stubs: - self._stubs['list_enrollments'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListEnrollments', + if "list_enrollments" not in self._stubs: + self._stubs["list_enrollments"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListEnrollments", request_serializer=eventarc.ListEnrollmentsRequest.serialize, response_deserializer=eventarc.ListEnrollmentsResponse.deserialize, ) - return self._stubs['list_enrollments'] + return self._stubs["list_enrollments"] @property - def create_enrollment(self) -> Callable[ - [eventarc.CreateEnrollmentRequest], - operations_pb2.Operation]: + def create_enrollment( + self, + ) -> Callable[[eventarc.CreateEnrollmentRequest], operations_pb2.Operation]: r"""Return a callable for the create enrollment method over gRPC. Create a new Enrollment in a particular project and @@ -1091,18 +1138,18 @@ def create_enrollment(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_enrollment' not in self._stubs: - self._stubs['create_enrollment'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateEnrollment', + if "create_enrollment" not in self._stubs: + self._stubs["create_enrollment"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreateEnrollment", request_serializer=eventarc.CreateEnrollmentRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_enrollment'] + return self._stubs["create_enrollment"] @property - def update_enrollment(self) -> Callable[ - [eventarc.UpdateEnrollmentRequest], - operations_pb2.Operation]: + def update_enrollment( + self, + ) -> Callable[[eventarc.UpdateEnrollmentRequest], operations_pb2.Operation]: r"""Return a callable for the update enrollment method over gRPC. Update a single Enrollment. @@ -1117,18 +1164,18 @@ def update_enrollment(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_enrollment' not in self._stubs: - self._stubs['update_enrollment'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateEnrollment', + if "update_enrollment" not in self._stubs: + self._stubs["update_enrollment"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdateEnrollment", request_serializer=eventarc.UpdateEnrollmentRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_enrollment'] + return self._stubs["update_enrollment"] @property - def delete_enrollment(self) -> Callable[ - [eventarc.DeleteEnrollmentRequest], - operations_pb2.Operation]: + def delete_enrollment( + self, + ) -> Callable[[eventarc.DeleteEnrollmentRequest], operations_pb2.Operation]: r"""Return a callable for the delete enrollment method over gRPC. Delete a single Enrollment. @@ -1143,18 +1190,18 @@ def delete_enrollment(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_enrollment' not in self._stubs: - self._stubs['delete_enrollment'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteEnrollment', + if "delete_enrollment" not in self._stubs: + self._stubs["delete_enrollment"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeleteEnrollment", request_serializer=eventarc.DeleteEnrollmentRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_enrollment'] + return self._stubs["delete_enrollment"] @property - def get_pipeline(self) -> Callable[ - [eventarc.GetPipelineRequest], - pipeline.Pipeline]: + def get_pipeline( + self, + ) -> Callable[[eventarc.GetPipelineRequest], pipeline.Pipeline]: r"""Return a callable for the get pipeline method over gRPC. Get a single Pipeline. @@ -1169,18 +1216,18 @@ def get_pipeline(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_pipeline' not in self._stubs: - self._stubs['get_pipeline'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetPipeline', + if "get_pipeline" not in self._stubs: + self._stubs["get_pipeline"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetPipeline", request_serializer=eventarc.GetPipelineRequest.serialize, response_deserializer=pipeline.Pipeline.deserialize, ) - return self._stubs['get_pipeline'] + return self._stubs["get_pipeline"] @property - def list_pipelines(self) -> Callable[ - [eventarc.ListPipelinesRequest], - eventarc.ListPipelinesResponse]: + def list_pipelines( + self, + ) -> Callable[[eventarc.ListPipelinesRequest], eventarc.ListPipelinesResponse]: r"""Return a callable for the list pipelines method over gRPC. List pipelines. @@ -1195,18 +1242,18 @@ def list_pipelines(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_pipelines' not in self._stubs: - self._stubs['list_pipelines'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListPipelines', + if "list_pipelines" not in self._stubs: + self._stubs["list_pipelines"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListPipelines", request_serializer=eventarc.ListPipelinesRequest.serialize, response_deserializer=eventarc.ListPipelinesResponse.deserialize, ) - return self._stubs['list_pipelines'] + return self._stubs["list_pipelines"] @property - def create_pipeline(self) -> Callable[ - [eventarc.CreatePipelineRequest], - operations_pb2.Operation]: + def create_pipeline( + self, + ) -> Callable[[eventarc.CreatePipelineRequest], operations_pb2.Operation]: r"""Return a callable for the create pipeline method over gRPC. Create a new Pipeline in a particular project and @@ -1222,18 +1269,18 @@ def create_pipeline(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_pipeline' not in self._stubs: - self._stubs['create_pipeline'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreatePipeline', + if "create_pipeline" not in self._stubs: + self._stubs["create_pipeline"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreatePipeline", request_serializer=eventarc.CreatePipelineRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_pipeline'] + return self._stubs["create_pipeline"] @property - def update_pipeline(self) -> Callable[ - [eventarc.UpdatePipelineRequest], - operations_pb2.Operation]: + def update_pipeline( + self, + ) -> Callable[[eventarc.UpdatePipelineRequest], operations_pb2.Operation]: r"""Return a callable for the update pipeline method over gRPC. Update a single pipeline. @@ -1248,18 +1295,18 @@ def update_pipeline(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_pipeline' not in self._stubs: - self._stubs['update_pipeline'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdatePipeline', + if "update_pipeline" not in self._stubs: + self._stubs["update_pipeline"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdatePipeline", request_serializer=eventarc.UpdatePipelineRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_pipeline'] + return self._stubs["update_pipeline"] @property - def delete_pipeline(self) -> Callable[ - [eventarc.DeletePipelineRequest], - operations_pb2.Operation]: + def delete_pipeline( + self, + ) -> Callable[[eventarc.DeletePipelineRequest], operations_pb2.Operation]: r"""Return a callable for the delete pipeline method over gRPC. Delete a single pipeline. @@ -1274,18 +1321,20 @@ def delete_pipeline(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_pipeline' not in self._stubs: - self._stubs['delete_pipeline'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeletePipeline', + if "delete_pipeline" not in self._stubs: + self._stubs["delete_pipeline"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeletePipeline", request_serializer=eventarc.DeletePipelineRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_pipeline'] + return self._stubs["delete_pipeline"] @property - def get_google_api_source(self) -> Callable[ - [eventarc.GetGoogleApiSourceRequest], - google_api_source.GoogleApiSource]: + def get_google_api_source( + self, + ) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], google_api_source.GoogleApiSource + ]: r"""Return a callable for the get google api source method over gRPC. Get a single GoogleApiSource. @@ -1300,18 +1349,20 @@ def get_google_api_source(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_google_api_source' not in self._stubs: - self._stubs['get_google_api_source'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/GetGoogleApiSource', + if "get_google_api_source" not in self._stubs: + self._stubs["get_google_api_source"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetGoogleApiSource", request_serializer=eventarc.GetGoogleApiSourceRequest.serialize, response_deserializer=google_api_source.GoogleApiSource.deserialize, ) - return self._stubs['get_google_api_source'] + return self._stubs["get_google_api_source"] @property - def list_google_api_sources(self) -> Callable[ - [eventarc.ListGoogleApiSourcesRequest], - eventarc.ListGoogleApiSourcesResponse]: + def list_google_api_sources( + self, + ) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], eventarc.ListGoogleApiSourcesResponse + ]: r"""Return a callable for the list google api sources method over gRPC. List GoogleApiSources. @@ -1326,18 +1377,18 @@ def list_google_api_sources(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_google_api_sources' not in self._stubs: - self._stubs['list_google_api_sources'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/ListGoogleApiSources', + if "list_google_api_sources" not in self._stubs: + self._stubs["list_google_api_sources"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListGoogleApiSources", request_serializer=eventarc.ListGoogleApiSourcesRequest.serialize, response_deserializer=eventarc.ListGoogleApiSourcesResponse.deserialize, ) - return self._stubs['list_google_api_sources'] + return self._stubs["list_google_api_sources"] @property - def create_google_api_source(self) -> Callable[ - [eventarc.CreateGoogleApiSourceRequest], - operations_pb2.Operation]: + def create_google_api_source( + self, + ) -> Callable[[eventarc.CreateGoogleApiSourceRequest], operations_pb2.Operation]: r"""Return a callable for the create google api source method over gRPC. Create a new GoogleApiSource in a particular project @@ -1353,18 +1404,18 @@ def create_google_api_source(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_google_api_source' not in self._stubs: - self._stubs['create_google_api_source'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/CreateGoogleApiSource', + if "create_google_api_source" not in self._stubs: + self._stubs["create_google_api_source"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreateGoogleApiSource", request_serializer=eventarc.CreateGoogleApiSourceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_google_api_source'] + return self._stubs["create_google_api_source"] @property - def update_google_api_source(self) -> Callable[ - [eventarc.UpdateGoogleApiSourceRequest], - operations_pb2.Operation]: + def update_google_api_source( + self, + ) -> Callable[[eventarc.UpdateGoogleApiSourceRequest], operations_pb2.Operation]: r"""Return a callable for the update google api source method over gRPC. Update a single GoogleApiSource. @@ -1379,18 +1430,18 @@ def update_google_api_source(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_google_api_source' not in self._stubs: - self._stubs['update_google_api_source'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/UpdateGoogleApiSource', + if "update_google_api_source" not in self._stubs: + self._stubs["update_google_api_source"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdateGoogleApiSource", request_serializer=eventarc.UpdateGoogleApiSourceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_google_api_source'] + return self._stubs["update_google_api_source"] @property - def delete_google_api_source(self) -> Callable[ - [eventarc.DeleteGoogleApiSourceRequest], - operations_pb2.Operation]: + def delete_google_api_source( + self, + ) -> Callable[[eventarc.DeleteGoogleApiSourceRequest], operations_pb2.Operation]: r"""Return a callable for the delete google api source method over gRPC. Delete a single GoogleApiSource. @@ -1405,13 +1456,13 @@ def delete_google_api_source(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_google_api_source' not in self._stubs: - self._stubs['delete_google_api_source'] = self._logged_channel.unary_unary( - '/google.cloud.eventarc.v1.Eventarc/DeleteGoogleApiSource', + if "delete_google_api_source" not in self._stubs: + self._stubs["delete_google_api_source"] = self._logged_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeleteGoogleApiSource", request_serializer=eventarc.DeleteGoogleApiSourceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_google_api_source'] + return self._stubs["delete_google_api_source"] def close(self): self._logged_channel.close() @@ -1420,8 +1471,7 @@ def close(self): def delete_operation( self, ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ + r"""Return a callable for the delete_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1438,8 +1488,7 @@ def delete_operation( def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1456,8 +1505,7 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1473,9 +1521,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1491,9 +1540,10 @@ def list_operations( @property def list_locations( self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1510,8 +1560,7 @@ def list_locations( def get_location( self, ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1579,7 +1628,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, ]: r"""Return a callable for the test iam permissions method over gRPC. Tests the specified permissions against the IAM access control @@ -1608,6 +1658,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'EventarcGrpcTransport', -) +__all__ = ("EventarcGrpcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py index 0f1870360427..65eb13b69934 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py @@ -13,29 +13,46 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import inspect import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.logging_v2 import gapic_version as package_version - +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.logging_v2 import gapic_version as package_version +from google.cloud.logging_v2._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -44,6 +61,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -57,15 +75,16 @@ _LOGGER = std_logging.getLogger(__name__) -from google.cloud.logging_v2.services.config_service_v2 import pagers -from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import ConfigServiceV2Transport, DEFAULT_CLIENT_INFO +from google.cloud.logging_v2.services.config_service_v2 import pagers +from google.cloud.logging_v2.types import logging_config +from google.longrunning import operations_pb2 # type: ignore + +from .transports.base import DEFAULT_CLIENT_INFO, ConfigServiceV2Transport from .transports.grpc import ConfigServiceV2GrpcTransport from .transports.grpc_asyncio import ConfigServiceV2GrpcAsyncIOTransport @@ -77,13 +96,15 @@ class ConfigServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[ConfigServiceV2Transport]] _transport_registry["grpc"] = ConfigServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = ConfigServiceV2GrpcAsyncIOTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConfigServiceV2Transport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ConfigServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -143,8 +164,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConfigServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -161,139 +181,220 @@ def transport(self) -> ConfigServiceV2Transport: return self._transport @staticmethod - def cmek_settings_path(project: str,) -> str: + def cmek_settings_path( + project: str, + ) -> str: """Returns a fully-qualified cmek_settings string.""" - return "projects/{project}/cmekSettings".format(project=project, ) + return "projects/{project}/cmekSettings".format( + project=project, + ) @staticmethod - def parse_cmek_settings_path(path: str) -> Dict[str,str]: + def parse_cmek_settings_path(path: str) -> Dict[str, str]: """Parses a cmek_settings path into its component segments.""" m = re.match(r"^projects/(?P.+?)/cmekSettings$", path) return m.groupdict() if m else {} @staticmethod - def link_path(project: str,location: str,bucket: str,link: str,) -> str: + def link_path( + project: str, + location: str, + bucket: str, + link: str, + ) -> str: """Returns a fully-qualified link string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format(project=project, location=location, bucket=bucket, link=link, ) + return "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format( + project=project, + location=location, + bucket=bucket, + link=link, + ) @staticmethod - def parse_link_path(path: str) -> Dict[str,str]: + def parse_link_path(path: str) -> Dict[str, str]: """Parses a link path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/links/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/links/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def log_bucket_path(project: str,location: str,bucket: str,) -> str: + def log_bucket_path( + project: str, + location: str, + bucket: str, + ) -> str: """Returns a fully-qualified log_bucket string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}".format(project=project, location=location, bucket=bucket, ) + return "projects/{project}/locations/{location}/buckets/{bucket}".format( + project=project, + location=location, + bucket=bucket, + ) @staticmethod - def parse_log_bucket_path(path: str) -> Dict[str,str]: + def parse_log_bucket_path(path: str) -> Dict[str, str]: """Parses a log_bucket path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def log_exclusion_path(project: str,exclusion: str,) -> str: + def log_exclusion_path( + project: str, + exclusion: str, + ) -> str: """Returns a fully-qualified log_exclusion string.""" - return "projects/{project}/exclusions/{exclusion}".format(project=project, exclusion=exclusion, ) + return "projects/{project}/exclusions/{exclusion}".format( + project=project, + exclusion=exclusion, + ) @staticmethod - def parse_log_exclusion_path(path: str) -> Dict[str,str]: + def parse_log_exclusion_path(path: str) -> Dict[str, str]: """Parses a log_exclusion path into its component segments.""" m = re.match(r"^projects/(?P.+?)/exclusions/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_sink_path(project: str,sink: str,) -> str: + def log_sink_path( + project: str, + sink: str, + ) -> str: """Returns a fully-qualified log_sink string.""" - return "projects/{project}/sinks/{sink}".format(project=project, sink=sink, ) + return "projects/{project}/sinks/{sink}".format( + project=project, + sink=sink, + ) @staticmethod - def parse_log_sink_path(path: str) -> Dict[str,str]: + def parse_log_sink_path(path: str) -> Dict[str, str]: """Parses a log_sink path into its component segments.""" m = re.match(r"^projects/(?P.+?)/sinks/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_view_path(project: str,location: str,bucket: str,view: str,) -> str: + def log_view_path( + project: str, + location: str, + bucket: str, + view: str, + ) -> str: """Returns a fully-qualified log_view string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format(project=project, location=location, bucket=bucket, view=view, ) + return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format( + project=project, + location=location, + bucket=bucket, + view=view, + ) @staticmethod - def parse_log_view_path(path: str) -> Dict[str,str]: + def parse_log_view_path(path: str) -> Dict[str, str]: """Parses a log_view path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def settings_path(project: str,) -> str: + def settings_path( + project: str, + ) -> str: """Returns a fully-qualified settings string.""" - return "projects/{project}/settings".format(project=project, ) + return "projects/{project}/settings".format( + project=project, + ) @staticmethod - def parse_settings_path(path: str) -> Dict[str,str]: + def parse_settings_path(path: str) -> Dict[str, str]: """Parses a settings path into its component segments.""" m = re.match(r"^projects/(?P.+?)/settings$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -325,14 +426,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -345,8 +450,10 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -385,15 +492,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -426,12 +536,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the config service v2 client. Args: @@ -486,13 +602,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = ConfigServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=ConfigServiceV2Client._DEFAULT_UNIVERSE) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = ConfigServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=ConfigServiceV2Client._DEFAULT_UNIVERSE, + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -504,7 +630,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -513,35 +641,40 @@ def __init__(self, *, if transport_provided: # transport is a ConfigServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." + "When providing a transport instance, provide its scopes directly." ) self._transport = cast(ConfigServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=ConfigServiceV2Client._DEFAULT_UNIVERSE, - default_mtls_endpoint=ConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=ConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" or ( - self._use_mtls_endpoint == "auto" and self._client_cert_source - ), - )) + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=ConfigServiceV2Client._DEFAULT_UNIVERSE, + default_mtls_endpoint=ConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=ConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[ConfigServiceV2Transport], Callable[..., ConfigServiceV2Transport]] = ( + transport_init: Union[ + Type[ConfigServiceV2Transport], Callable[..., ConfigServiceV2Transport] + ] = ( ConfigServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ConfigServiceV2Transport], transport) @@ -570,33 +703,46 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"client_options": client_options} if client_options else {}), + **( + {"client_options": client_options} + if client_options is not None + else {} + ), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.ConfigServiceV2Client`.", - extra = { + extra={ "serviceName": "google.logging.v2.ConfigServiceV2", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.logging.v2.ConfigServiceV2", "credentialsType": None, - } + }, ) - def list_buckets(self, - request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBucketsPager: + def list_buckets( + self, + request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketsPager: r"""Lists log buckets. .. code-block:: python @@ -668,10 +814,14 @@ def sample_list_buckets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -689,9 +839,7 @@ def sample_list_buckets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -719,13 +867,14 @@ def sample_list_buckets(): # Done; return the response. return response - def get_bucket(self, - request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def get_bucket( + self, + request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Gets a log bucket. .. code-block:: python @@ -784,9 +933,7 @@ def sample_get_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -803,13 +950,14 @@ def sample_get_bucket(): # Done; return the response. return response - def create_bucket_async(self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_bucket_async( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a log bucket asynchronously that can be used to store log entries. After a bucket has been created, the bucket's location @@ -879,9 +1027,7 @@ def sample_create_bucket_async(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -906,13 +1052,14 @@ def sample_create_bucket_async(): # Done; return the response. return response - def update_bucket_async(self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_bucket_async( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates a log bucket asynchronously. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -984,9 +1131,7 @@ def sample_update_bucket_async(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1011,13 +1156,14 @@ def sample_update_bucket_async(): # Done; return the response. return response - def create_bucket(self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def create_bucket( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Creates a log bucket that can be used to store log entries. After a bucket has been created, the bucket's location cannot be changed. @@ -1079,9 +1225,7 @@ def sample_create_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1098,13 +1242,14 @@ def sample_create_bucket(): # Done; return the response. return response - def update_bucket(self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def update_bucket( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Updates a log bucket. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -1169,9 +1314,7 @@ def sample_update_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1188,13 +1331,14 @@ def sample_update_bucket(): # Done; return the response. return response - def delete_bucket(self, - request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_bucket( + self, + request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a log bucket. Changes the bucket's ``lifecycle_state`` to the @@ -1249,9 +1393,7 @@ def sample_delete_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1265,13 +1407,14 @@ def sample_delete_bucket(): metadata=metadata, ) - def undelete_bucket(self, - request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def undelete_bucket( + self, + request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Undeletes a log bucket. A bucket that has been deleted can be undeleted within the grace period of 7 days. @@ -1323,9 +1466,7 @@ def sample_undelete_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1339,14 +1480,15 @@ def sample_undelete_bucket(): metadata=metadata, ) - def list_views(self, - request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListViewsPager: + def list_views( + self, + request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListViewsPager: r"""Lists views on a log bucket. .. code-block:: python @@ -1410,10 +1552,14 @@ def sample_list_views(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1431,9 +1577,7 @@ def sample_list_views(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1461,13 +1605,14 @@ def sample_list_views(): # Done; return the response. return response - def get_view(self, - request: Optional[Union[logging_config.GetViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def get_view( + self, + request: Optional[Union[logging_config.GetViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Gets a view on a log bucket.. .. code-block:: python @@ -1526,9 +1671,7 @@ def sample_get_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1545,13 +1688,14 @@ def sample_get_view(): # Done; return the response. return response - def create_view(self, - request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def create_view( + self, + request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Creates a view over log entries in a log bucket. A bucket may contain a maximum of 30 views. @@ -1612,9 +1756,7 @@ def sample_create_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1631,13 +1773,14 @@ def sample_create_view(): # Done; return the response. return response - def update_view(self, - request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def update_view( + self, + request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Updates a view on a log bucket. This method replaces the following fields in the existing view with values from the new view: ``filter``. If an ``UNAVAILABLE`` error is returned, this @@ -1700,9 +1843,7 @@ def sample_update_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1719,13 +1860,14 @@ def sample_update_view(): # Done; return the response. return response - def delete_view(self, - request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_view( + self, + request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is returned, this indicates that system is not in a state where it can delete the view. If this occurs, please try again in a few @@ -1778,9 +1920,7 @@ def sample_delete_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1794,14 +1934,15 @@ def sample_delete_view(): metadata=metadata, ) - def list_sinks(self, - request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListSinksPager: + def list_sinks( + self, + request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSinksPager: r"""Lists sinks. .. code-block:: python @@ -1868,10 +2009,14 @@ def sample_list_sinks(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1889,9 +2034,7 @@ def sample_list_sinks(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1919,14 +2062,15 @@ def sample_list_sinks(): # Done; return the response. return response - def get_sink(self, - request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def get_sink( + self, + request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Gets a sink. .. code-block:: python @@ -2000,10 +2144,14 @@ def sample_get_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2021,9 +2169,9 @@ def sample_get_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2040,15 +2188,16 @@ def sample_get_sink(): # Done; return the response. return response - def create_sink(self, - request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def create_sink( + self, + request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not @@ -2138,10 +2287,14 @@ def sample_create_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, sink] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2161,9 +2314,7 @@ def sample_create_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2180,16 +2331,17 @@ def sample_create_sink(): # Done; return the response. return response - def update_sink(self, - request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def update_sink( + self, + request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: ``destination``, and ``filter``. @@ -2303,10 +2455,14 @@ def sample_update_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name, sink, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2328,9 +2484,9 @@ def sample_update_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2347,14 +2503,15 @@ def sample_update_sink(): # Done; return the response. return response - def delete_sink(self, - request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_sink( + self, + request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a sink. If the sink has a unique ``writer_identity``, then that service account is also deleted. @@ -2414,10 +2571,14 @@ def sample_delete_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2435,9 +2596,9 @@ def sample_delete_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2451,16 +2612,17 @@ def sample_delete_sink(): metadata=metadata, ) - def create_link(self, - request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - link: Optional[logging_config.Link] = None, - link_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_link( + self, + request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + link: Optional[logging_config.Link] = None, + link_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Asynchronously creates a linked dataset in BigQuery which makes it possible to use BigQuery to read the logs stored in the log bucket. A log bucket may currently @@ -2548,10 +2710,14 @@ def sample_create_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, link, link_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2573,9 +2739,7 @@ def sample_create_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2600,14 +2764,15 @@ def sample_create_link(): # Done; return the response. return response - def delete_link(self, - request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_link( + self, + request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes a link. This will also delete the corresponding BigQuery linked dataset. @@ -2683,10 +2848,14 @@ def sample_delete_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2704,9 +2873,7 @@ def sample_delete_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2731,14 +2898,15 @@ def sample_delete_link(): # Done; return the response. return response - def list_links(self, - request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLinksPager: + def list_links( + self, + request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLinksPager: r"""Lists links. .. code-block:: python @@ -2804,10 +2972,14 @@ def sample_list_links(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2825,9 +2997,7 @@ def sample_list_links(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2855,14 +3025,15 @@ def sample_list_links(): # Done; return the response. return response - def get_link(self, - request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Link: + def get_link( + self, + request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Link: r"""Gets a link. .. code-block:: python @@ -2923,10 +3094,14 @@ def sample_get_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2944,9 +3119,7 @@ def sample_get_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2963,14 +3136,15 @@ def sample_get_link(): # Done; return the response. return response - def list_exclusions(self, - request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListExclusionsPager: + def list_exclusions( + self, + request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExclusionsPager: r"""Lists all the exclusions on the \_Default sink in a parent resource. @@ -3038,10 +3212,14 @@ def sample_list_exclusions(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3059,9 +3237,7 @@ def sample_list_exclusions(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3089,14 +3265,15 @@ def sample_list_exclusions(): # Done; return the response. return response - def get_exclusion(self, - request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def get_exclusion( + self, + request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Gets the description of an exclusion in the \_Default sink. .. code-block:: python @@ -3168,10 +3345,14 @@ def sample_get_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3189,9 +3370,7 @@ def sample_get_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3208,15 +3387,16 @@ def sample_get_exclusion(): # Done; return the response. return response - def create_exclusion(self, - request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, - *, - parent: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def create_exclusion( + self, + request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, + *, + parent: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Creates a new exclusion in the \_Default sink in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. @@ -3305,10 +3485,14 @@ def sample_create_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, exclusion] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3328,9 +3512,7 @@ def sample_create_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3347,16 +3529,17 @@ def sample_create_exclusion(): # Done; return the response. return response - def update_exclusion(self, - request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def update_exclusion( + self, + request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Changes one or more properties of an existing exclusion in the \_Default sink. @@ -3456,10 +3639,14 @@ def sample_update_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, exclusion, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3481,9 +3668,7 @@ def sample_update_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3500,14 +3685,15 @@ def sample_update_exclusion(): # Done; return the response. return response - def delete_exclusion(self, - request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_exclusion( + self, + request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes an exclusion in the \_Default sink. .. code-block:: python @@ -3566,10 +3752,14 @@ def sample_delete_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3587,9 +3777,7 @@ def sample_delete_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3603,13 +3791,14 @@ def sample_delete_exclusion(): metadata=metadata, ) - def get_cmek_settings(self, - request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + def get_cmek_settings( + self, + request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Gets the Logging CMEK settings for the given resource. Note: CMEK for the Log Router can be configured for Google Cloud @@ -3692,9 +3881,7 @@ def sample_get_cmek_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3711,13 +3898,14 @@ def sample_get_cmek_settings(): # Done; return the response. return response - def update_cmek_settings(self, - request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + def update_cmek_settings( + self, + request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Updates the Log Router CMEK settings for the given resource. Note: CMEK for the Log Router can currently only be configured @@ -3805,9 +3993,7 @@ def sample_update_cmek_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3824,14 +4010,15 @@ def sample_update_cmek_settings(): # Done; return the response. return response - def get_settings(self, - request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + def get_settings( + self, + request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Gets the Log Router settings for the given resource. Note: Settings for the Log Router can be get for Google Cloud @@ -3921,10 +4108,14 @@ def sample_get_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3942,9 +4133,7 @@ def sample_get_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3961,15 +4150,16 @@ def sample_get_settings(): # Done; return the response. return response - def update_settings(self, - request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, - *, - settings: Optional[logging_config.Settings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + def update_settings( + self, + request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, + *, + settings: Optional[logging_config.Settings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Updates the Log Router settings for the given resource. Note: Settings for the Log Router can currently only be @@ -4066,10 +4256,14 @@ def sample_update_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4089,9 +4283,7 @@ def sample_update_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4108,13 +4300,14 @@ def sample_update_settings(): # Done; return the response. return response - def copy_log_entries(self, - request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def copy_log_entries( + self, + request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Copies a set of log entries from a log bucket to a Cloud Storage bucket. @@ -4257,8 +4450,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -4267,7 +4459,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -4317,8 +4513,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -4327,7 +4522,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -4380,25 +4579,24 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - - - - + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "ConfigServiceV2Client", -) +__all__ = ("ConfigServiceV2Client",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py index f76b68bfee94..97dbac19187d 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -17,52 +17,59 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.logging_v2 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.cloud.logging_v2 import gapic_version as package_version from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +# Check once at module load time whether google-api-core's wrap_method supports +# OpenTelemetry tracing arguments (client_options, method_name, is_streaming, kind) +# to avoid recurring inspect.signature latency during client instantiation. +_WRAP_METHOD_SUPPORTS_TRACING = ( + "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters +) + class ConfigServiceV2Transport(abc.ABC): """Abstract transport class for ConfigServiceV2.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", ) - DEFAULT_HOST: str = 'logging.googleapis.com' + DEFAULT_HOST: str = "logging.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -104,38 +111,47 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._client_options = client_options - # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments - # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility - # with older versions of google-api-core. - self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrap_with_tracing = _WRAP_METHOD_SUPPORTS_TRACING self._wrapped_methods: Dict[Callable, Callable] = {} @@ -148,15 +164,24 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["client_options"] = self._client_options try: kwargs["kind"] = self.kind - # Base transport raises NotImplementedError for abstract kind property. - # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + # The abstract BaseTransport class raises NotImplementedError for the kind property. + # Concrete transport subclasses (gRPC, REST) override kind, so this exception handler + # is unreachable during normal execution. Excluded from coverage check. except NotImplementedError: # pragma: NO COVER pass return gapic_v1.method.wrap_method(func, *args, **kwargs) - # Remove tracing-specific arguments if older google-api-core is installed - for k in ["client_options", "method_name", "is_streaming", "kind"]: - kwargs.pop(k, None) - return gapic_v1.method.wrap_method(func, *args, **kwargs) + # The fallback below strips tracing-specific arguments when an older version + # of google-api-core is installed (which does not accept client_options, etc.). + # Excluded from coverage because our CI and testing environments always install + # a modern version of google-api-core that supports tracing. + for k in [ + "client_options", + "method_name", + "is_streaming", + "kind", + ]: # pragma: NO COVER + kwargs.pop(k, None) # pragma: NO COVER + return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -445,14 +470,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -462,291 +487,306 @@ def operations_client(self): raise NotImplementedError() @property - def list_buckets(self) -> Callable[ - [logging_config.ListBucketsRequest], - Union[ - logging_config.ListBucketsResponse, - Awaitable[logging_config.ListBucketsResponse] - ]]: + def list_buckets( + self, + ) -> Callable[ + [logging_config.ListBucketsRequest], + Union[ + logging_config.ListBucketsResponse, + Awaitable[logging_config.ListBucketsResponse], + ], + ]: raise NotImplementedError() @property - def get_bucket(self) -> Callable[ - [logging_config.GetBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: + def get_bucket( + self, + ) -> Callable[ + [logging_config.GetBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: raise NotImplementedError() @property - def create_bucket_async(self) -> Callable[ - [logging_config.CreateBucketRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_bucket_async( + self, + ) -> Callable[ + [logging_config.CreateBucketRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_bucket_async(self) -> Callable[ - [logging_config.UpdateBucketRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_bucket_async( + self, + ) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def create_bucket(self) -> Callable[ - [logging_config.CreateBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: + def create_bucket( + self, + ) -> Callable[ + [logging_config.CreateBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: raise NotImplementedError() @property - def update_bucket(self) -> Callable[ - [logging_config.UpdateBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: + def update_bucket( + self, + ) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: raise NotImplementedError() @property - def delete_bucket(self) -> Callable[ - [logging_config.DeleteBucketRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_bucket( + self, + ) -> Callable[ + [logging_config.DeleteBucketRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def undelete_bucket(self) -> Callable[ - [logging_config.UndeleteBucketRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def undelete_bucket( + self, + ) -> Callable[ + [logging_config.UndeleteBucketRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def list_views(self) -> Callable[ - [logging_config.ListViewsRequest], - Union[ - logging_config.ListViewsResponse, - Awaitable[logging_config.ListViewsResponse] - ]]: + def list_views( + self, + ) -> Callable[ + [logging_config.ListViewsRequest], + Union[ + logging_config.ListViewsResponse, + Awaitable[logging_config.ListViewsResponse], + ], + ]: raise NotImplementedError() @property - def get_view(self) -> Callable[ - [logging_config.GetViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: + def get_view( + self, + ) -> Callable[ + [logging_config.GetViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: raise NotImplementedError() @property - def create_view(self) -> Callable[ - [logging_config.CreateViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: + def create_view( + self, + ) -> Callable[ + [logging_config.CreateViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: raise NotImplementedError() @property - def update_view(self) -> Callable[ - [logging_config.UpdateViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: + def update_view( + self, + ) -> Callable[ + [logging_config.UpdateViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: raise NotImplementedError() @property - def delete_view(self) -> Callable[ - [logging_config.DeleteViewRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_view( + self, + ) -> Callable[ + [logging_config.DeleteViewRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def list_sinks(self) -> Callable[ - [logging_config.ListSinksRequest], - Union[ - logging_config.ListSinksResponse, - Awaitable[logging_config.ListSinksResponse] - ]]: + def list_sinks( + self, + ) -> Callable[ + [logging_config.ListSinksRequest], + Union[ + logging_config.ListSinksResponse, + Awaitable[logging_config.ListSinksResponse], + ], + ]: raise NotImplementedError() @property - def get_sink(self) -> Callable[ - [logging_config.GetSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: + def get_sink( + self, + ) -> Callable[ + [logging_config.GetSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: raise NotImplementedError() @property - def create_sink(self) -> Callable[ - [logging_config.CreateSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: + def create_sink( + self, + ) -> Callable[ + [logging_config.CreateSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: raise NotImplementedError() @property - def update_sink(self) -> Callable[ - [logging_config.UpdateSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: + def update_sink( + self, + ) -> Callable[ + [logging_config.UpdateSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: raise NotImplementedError() @property - def delete_sink(self) -> Callable[ - [logging_config.DeleteSinkRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_sink( + self, + ) -> Callable[ + [logging_config.DeleteSinkRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def create_link(self) -> Callable[ - [logging_config.CreateLinkRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_link( + self, + ) -> Callable[ + [logging_config.CreateLinkRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_link(self) -> Callable[ - [logging_config.DeleteLinkRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_link( + self, + ) -> Callable[ + [logging_config.DeleteLinkRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def list_links(self) -> Callable[ - [logging_config.ListLinksRequest], - Union[ - logging_config.ListLinksResponse, - Awaitable[logging_config.ListLinksResponse] - ]]: + def list_links( + self, + ) -> Callable[ + [logging_config.ListLinksRequest], + Union[ + logging_config.ListLinksResponse, + Awaitable[logging_config.ListLinksResponse], + ], + ]: raise NotImplementedError() @property - def get_link(self) -> Callable[ - [logging_config.GetLinkRequest], - Union[ - logging_config.Link, - Awaitable[logging_config.Link] - ]]: + def get_link( + self, + ) -> Callable[ + [logging_config.GetLinkRequest], + Union[logging_config.Link, Awaitable[logging_config.Link]], + ]: raise NotImplementedError() @property - def list_exclusions(self) -> Callable[ - [logging_config.ListExclusionsRequest], - Union[ - logging_config.ListExclusionsResponse, - Awaitable[logging_config.ListExclusionsResponse] - ]]: + def list_exclusions( + self, + ) -> Callable[ + [logging_config.ListExclusionsRequest], + Union[ + logging_config.ListExclusionsResponse, + Awaitable[logging_config.ListExclusionsResponse], + ], + ]: raise NotImplementedError() @property - def get_exclusion(self) -> Callable[ - [logging_config.GetExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: + def get_exclusion( + self, + ) -> Callable[ + [logging_config.GetExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: raise NotImplementedError() @property - def create_exclusion(self) -> Callable[ - [logging_config.CreateExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: + def create_exclusion( + self, + ) -> Callable[ + [logging_config.CreateExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: raise NotImplementedError() @property - def update_exclusion(self) -> Callable[ - [logging_config.UpdateExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: + def update_exclusion( + self, + ) -> Callable[ + [logging_config.UpdateExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: raise NotImplementedError() @property - def delete_exclusion(self) -> Callable[ - [logging_config.DeleteExclusionRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_exclusion( + self, + ) -> Callable[ + [logging_config.DeleteExclusionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def get_cmek_settings(self) -> Callable[ - [logging_config.GetCmekSettingsRequest], - Union[ - logging_config.CmekSettings, - Awaitable[logging_config.CmekSettings] - ]]: + def get_cmek_settings( + self, + ) -> Callable[ + [logging_config.GetCmekSettingsRequest], + Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], + ]: raise NotImplementedError() @property - def update_cmek_settings(self) -> Callable[ - [logging_config.UpdateCmekSettingsRequest], - Union[ - logging_config.CmekSettings, - Awaitable[logging_config.CmekSettings] - ]]: + def update_cmek_settings( + self, + ) -> Callable[ + [logging_config.UpdateCmekSettingsRequest], + Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], + ]: raise NotImplementedError() @property - def get_settings(self) -> Callable[ - [logging_config.GetSettingsRequest], - Union[ - logging_config.Settings, - Awaitable[logging_config.Settings] - ]]: + def get_settings( + self, + ) -> Callable[ + [logging_config.GetSettingsRequest], + Union[logging_config.Settings, Awaitable[logging_config.Settings]], + ]: raise NotImplementedError() @property - def update_settings(self) -> Callable[ - [logging_config.UpdateSettingsRequest], - Union[ - logging_config.Settings, - Awaitable[logging_config.Settings] - ]]: + def update_settings( + self, + ) -> Callable[ + [logging_config.UpdateSettingsRequest], + Union[logging_config.Settings, Awaitable[logging_config.Settings]], + ]: raise NotImplementedError() @property - def copy_log_entries(self) -> Callable[ - [logging_config.CopyLogEntriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def copy_log_entries( + self, + ) -> Callable[ + [logging_config.CopyLogEntriesRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property @@ -754,7 +794,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -781,6 +824,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'ConfigServiceV2Transport', -) +__all__ = ("ConfigServiceV2Transport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index 9c62d0b16de8..0fd4a31ba7f8 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -17,17 +17,19 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -from google.api_core import operations_v1 + from google.api_core.grpc_helpers import ( + ClientInterceptor, # type: ignore[attr-defined] + ) from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 + # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -35,21 +37,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import proto # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.logging_v2.types import logging_config +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import proto # type: ignore -from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from .base import ConfigServiceV2Transport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, ConfigServiceV2Transport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -59,7 +61,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -80,7 +84,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.logging.v2.ConfigServiceV2", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -91,7 +95,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -106,7 +114,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.logging.v2.ConfigServiceV2", "rpcName": client_call_details.method, "response": grpc_response, @@ -128,32 +136,35 @@ class ConfigServiceV2GrpcTransport(ConfigServiceV2Transport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'logging.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], - ] + def __init__( + self, + *, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -290,8 +301,17 @@ def __init__(self, *, channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None and otel_interceptor not in channel_interceptors + and not any( + getattr(i, "_is_otel_interceptor", None) is True + for i in channel_interceptors + ) ): channel_interceptors.append(otel_interceptor) @@ -300,22 +320,28 @@ def __init__(self, *, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) + self._grpc_channel = apply_interceptors( + self._grpc_channel, channel_interceptors + ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'logging.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -351,13 +377,12 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property @@ -377,9 +402,11 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def list_buckets(self) -> Callable[ - [logging_config.ListBucketsRequest], - logging_config.ListBucketsResponse]: + def list_buckets( + self, + ) -> Callable[ + [logging_config.ListBucketsRequest], logging_config.ListBucketsResponse + ]: r"""Return a callable for the list buckets method over gRPC. Lists log buckets. @@ -394,18 +421,18 @@ def list_buckets(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_buckets' not in self._stubs: - self._stubs['list_buckets'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListBuckets', + if "list_buckets" not in self._stubs: + self._stubs["list_buckets"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListBuckets", request_serializer=logging_config.ListBucketsRequest.serialize, response_deserializer=logging_config.ListBucketsResponse.deserialize, ) - return self._stubs['list_buckets'] + return self._stubs["list_buckets"] @property - def get_bucket(self) -> Callable[ - [logging_config.GetBucketRequest], - logging_config.LogBucket]: + def get_bucket( + self, + ) -> Callable[[logging_config.GetBucketRequest], logging_config.LogBucket]: r"""Return a callable for the get bucket method over gRPC. Gets a log bucket. @@ -420,18 +447,18 @@ def get_bucket(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_bucket' not in self._stubs: - self._stubs['get_bucket'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetBucket', + if "get_bucket" not in self._stubs: + self._stubs["get_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetBucket", request_serializer=logging_config.GetBucketRequest.serialize, response_deserializer=logging_config.LogBucket.deserialize, ) - return self._stubs['get_bucket'] + return self._stubs["get_bucket"] @property - def create_bucket_async(self) -> Callable[ - [logging_config.CreateBucketRequest], - operations_pb2.Operation]: + def create_bucket_async( + self, + ) -> Callable[[logging_config.CreateBucketRequest], operations_pb2.Operation]: r"""Return a callable for the create bucket async method over gRPC. Creates a log bucket asynchronously that can be used @@ -449,18 +476,18 @@ def create_bucket_async(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_bucket_async' not in self._stubs: - self._stubs['create_bucket_async'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateBucketAsync', + if "create_bucket_async" not in self._stubs: + self._stubs["create_bucket_async"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateBucketAsync", request_serializer=logging_config.CreateBucketRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_bucket_async'] + return self._stubs["create_bucket_async"] @property - def update_bucket_async(self) -> Callable[ - [logging_config.UpdateBucketRequest], - operations_pb2.Operation]: + def update_bucket_async( + self, + ) -> Callable[[logging_config.UpdateBucketRequest], operations_pb2.Operation]: r"""Return a callable for the update bucket async method over gRPC. Updates a log bucket asynchronously. @@ -481,18 +508,18 @@ def update_bucket_async(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_bucket_async' not in self._stubs: - self._stubs['update_bucket_async'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateBucketAsync', + if "update_bucket_async" not in self._stubs: + self._stubs["update_bucket_async"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateBucketAsync", request_serializer=logging_config.UpdateBucketRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_bucket_async'] + return self._stubs["update_bucket_async"] @property - def create_bucket(self) -> Callable[ - [logging_config.CreateBucketRequest], - logging_config.LogBucket]: + def create_bucket( + self, + ) -> Callable[[logging_config.CreateBucketRequest], logging_config.LogBucket]: r"""Return a callable for the create bucket method over gRPC. Creates a log bucket that can be used to store log @@ -509,18 +536,18 @@ def create_bucket(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_bucket' not in self._stubs: - self._stubs['create_bucket'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateBucket', + if "create_bucket" not in self._stubs: + self._stubs["create_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateBucket", request_serializer=logging_config.CreateBucketRequest.serialize, response_deserializer=logging_config.LogBucket.deserialize, ) - return self._stubs['create_bucket'] + return self._stubs["create_bucket"] @property - def update_bucket(self) -> Callable[ - [logging_config.UpdateBucketRequest], - logging_config.LogBucket]: + def update_bucket( + self, + ) -> Callable[[logging_config.UpdateBucketRequest], logging_config.LogBucket]: r"""Return a callable for the update bucket method over gRPC. Updates a log bucket. @@ -541,18 +568,18 @@ def update_bucket(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_bucket' not in self._stubs: - self._stubs['update_bucket'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateBucket', + if "update_bucket" not in self._stubs: + self._stubs["update_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateBucket", request_serializer=logging_config.UpdateBucketRequest.serialize, response_deserializer=logging_config.LogBucket.deserialize, ) - return self._stubs['update_bucket'] + return self._stubs["update_bucket"] @property - def delete_bucket(self) -> Callable[ - [logging_config.DeleteBucketRequest], - empty_pb2.Empty]: + def delete_bucket( + self, + ) -> Callable[[logging_config.DeleteBucketRequest], empty_pb2.Empty]: r"""Return a callable for the delete bucket method over gRPC. Deletes a log bucket. @@ -572,18 +599,18 @@ def delete_bucket(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_bucket' not in self._stubs: - self._stubs['delete_bucket'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteBucket', + if "delete_bucket" not in self._stubs: + self._stubs["delete_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteBucket", request_serializer=logging_config.DeleteBucketRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_bucket'] + return self._stubs["delete_bucket"] @property - def undelete_bucket(self) -> Callable[ - [logging_config.UndeleteBucketRequest], - empty_pb2.Empty]: + def undelete_bucket( + self, + ) -> Callable[[logging_config.UndeleteBucketRequest], empty_pb2.Empty]: r"""Return a callable for the undelete bucket method over gRPC. Undeletes a log bucket. A bucket that has been @@ -600,18 +627,18 @@ def undelete_bucket(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'undelete_bucket' not in self._stubs: - self._stubs['undelete_bucket'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UndeleteBucket', + if "undelete_bucket" not in self._stubs: + self._stubs["undelete_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UndeleteBucket", request_serializer=logging_config.UndeleteBucketRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['undelete_bucket'] + return self._stubs["undelete_bucket"] @property - def list_views(self) -> Callable[ - [logging_config.ListViewsRequest], - logging_config.ListViewsResponse]: + def list_views( + self, + ) -> Callable[[logging_config.ListViewsRequest], logging_config.ListViewsResponse]: r"""Return a callable for the list views method over gRPC. Lists views on a log bucket. @@ -626,18 +653,18 @@ def list_views(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_views' not in self._stubs: - self._stubs['list_views'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListViews', + if "list_views" not in self._stubs: + self._stubs["list_views"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListViews", request_serializer=logging_config.ListViewsRequest.serialize, response_deserializer=logging_config.ListViewsResponse.deserialize, ) - return self._stubs['list_views'] + return self._stubs["list_views"] @property - def get_view(self) -> Callable[ - [logging_config.GetViewRequest], - logging_config.LogView]: + def get_view( + self, + ) -> Callable[[logging_config.GetViewRequest], logging_config.LogView]: r"""Return a callable for the get view method over gRPC. Gets a view on a log bucket.. @@ -652,18 +679,18 @@ def get_view(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_view' not in self._stubs: - self._stubs['get_view'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetView', + if "get_view" not in self._stubs: + self._stubs["get_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetView", request_serializer=logging_config.GetViewRequest.serialize, response_deserializer=logging_config.LogView.deserialize, ) - return self._stubs['get_view'] + return self._stubs["get_view"] @property - def create_view(self) -> Callable[ - [logging_config.CreateViewRequest], - logging_config.LogView]: + def create_view( + self, + ) -> Callable[[logging_config.CreateViewRequest], logging_config.LogView]: r"""Return a callable for the create view method over gRPC. Creates a view over log entries in a log bucket. A @@ -679,18 +706,18 @@ def create_view(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_view' not in self._stubs: - self._stubs['create_view'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateView', + if "create_view" not in self._stubs: + self._stubs["create_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateView", request_serializer=logging_config.CreateViewRequest.serialize, response_deserializer=logging_config.LogView.deserialize, ) - return self._stubs['create_view'] + return self._stubs["create_view"] @property - def update_view(self) -> Callable[ - [logging_config.UpdateViewRequest], - logging_config.LogView]: + def update_view( + self, + ) -> Callable[[logging_config.UpdateViewRequest], logging_config.LogView]: r"""Return a callable for the update view method over gRPC. Updates a view on a log bucket. This method replaces the @@ -709,18 +736,18 @@ def update_view(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_view' not in self._stubs: - self._stubs['update_view'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateView', + if "update_view" not in self._stubs: + self._stubs["update_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateView", request_serializer=logging_config.UpdateViewRequest.serialize, response_deserializer=logging_config.LogView.deserialize, ) - return self._stubs['update_view'] + return self._stubs["update_view"] @property - def delete_view(self) -> Callable[ - [logging_config.DeleteViewRequest], - empty_pb2.Empty]: + def delete_view( + self, + ) -> Callable[[logging_config.DeleteViewRequest], empty_pb2.Empty]: r"""Return a callable for the delete view method over gRPC. Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is @@ -738,18 +765,18 @@ def delete_view(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_view' not in self._stubs: - self._stubs['delete_view'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteView', + if "delete_view" not in self._stubs: + self._stubs["delete_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteView", request_serializer=logging_config.DeleteViewRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_view'] + return self._stubs["delete_view"] @property - def list_sinks(self) -> Callable[ - [logging_config.ListSinksRequest], - logging_config.ListSinksResponse]: + def list_sinks( + self, + ) -> Callable[[logging_config.ListSinksRequest], logging_config.ListSinksResponse]: r"""Return a callable for the list sinks method over gRPC. Lists sinks. @@ -764,18 +791,18 @@ def list_sinks(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_sinks' not in self._stubs: - self._stubs['list_sinks'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListSinks', + if "list_sinks" not in self._stubs: + self._stubs["list_sinks"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListSinks", request_serializer=logging_config.ListSinksRequest.serialize, response_deserializer=logging_config.ListSinksResponse.deserialize, ) - return self._stubs['list_sinks'] + return self._stubs["list_sinks"] @property - def get_sink(self) -> Callable[ - [logging_config.GetSinkRequest], - logging_config.LogSink]: + def get_sink( + self, + ) -> Callable[[logging_config.GetSinkRequest], logging_config.LogSink]: r"""Return a callable for the get sink method over gRPC. Gets a sink. @@ -790,18 +817,18 @@ def get_sink(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_sink' not in self._stubs: - self._stubs['get_sink'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetSink', + if "get_sink" not in self._stubs: + self._stubs["get_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetSink", request_serializer=logging_config.GetSinkRequest.serialize, response_deserializer=logging_config.LogSink.deserialize, ) - return self._stubs['get_sink'] + return self._stubs["get_sink"] @property - def create_sink(self) -> Callable[ - [logging_config.CreateSinkRequest], - logging_config.LogSink]: + def create_sink( + self, + ) -> Callable[[logging_config.CreateSinkRequest], logging_config.LogSink]: r"""Return a callable for the create sink method over gRPC. Creates a sink that exports specified log entries to a @@ -820,18 +847,18 @@ def create_sink(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_sink' not in self._stubs: - self._stubs['create_sink'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateSink', + if "create_sink" not in self._stubs: + self._stubs["create_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateSink", request_serializer=logging_config.CreateSinkRequest.serialize, response_deserializer=logging_config.LogSink.deserialize, ) - return self._stubs['create_sink'] + return self._stubs["create_sink"] @property - def update_sink(self) -> Callable[ - [logging_config.UpdateSinkRequest], - logging_config.LogSink]: + def update_sink( + self, + ) -> Callable[[logging_config.UpdateSinkRequest], logging_config.LogSink]: r"""Return a callable for the update sink method over gRPC. Updates a sink. This method replaces the following fields in the @@ -851,18 +878,18 @@ def update_sink(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_sink' not in self._stubs: - self._stubs['update_sink'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateSink', + if "update_sink" not in self._stubs: + self._stubs["update_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateSink", request_serializer=logging_config.UpdateSinkRequest.serialize, response_deserializer=logging_config.LogSink.deserialize, ) - return self._stubs['update_sink'] + return self._stubs["update_sink"] @property - def delete_sink(self) -> Callable[ - [logging_config.DeleteSinkRequest], - empty_pb2.Empty]: + def delete_sink( + self, + ) -> Callable[[logging_config.DeleteSinkRequest], empty_pb2.Empty]: r"""Return a callable for the delete sink method over gRPC. Deletes a sink. If the sink has a unique ``writer_identity``, @@ -878,18 +905,18 @@ def delete_sink(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_sink' not in self._stubs: - self._stubs['delete_sink'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteSink', + if "delete_sink" not in self._stubs: + self._stubs["delete_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteSink", request_serializer=logging_config.DeleteSinkRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_sink'] + return self._stubs["delete_sink"] @property - def create_link(self) -> Callable[ - [logging_config.CreateLinkRequest], - operations_pb2.Operation]: + def create_link( + self, + ) -> Callable[[logging_config.CreateLinkRequest], operations_pb2.Operation]: r"""Return a callable for the create link method over gRPC. Asynchronously creates a linked dataset in BigQuery @@ -907,18 +934,18 @@ def create_link(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_link' not in self._stubs: - self._stubs['create_link'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateLink', + if "create_link" not in self._stubs: + self._stubs["create_link"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateLink", request_serializer=logging_config.CreateLinkRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_link'] + return self._stubs["create_link"] @property - def delete_link(self) -> Callable[ - [logging_config.DeleteLinkRequest], - operations_pb2.Operation]: + def delete_link( + self, + ) -> Callable[[logging_config.DeleteLinkRequest], operations_pb2.Operation]: r"""Return a callable for the delete link method over gRPC. Deletes a link. This will also delete the @@ -934,18 +961,18 @@ def delete_link(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_link' not in self._stubs: - self._stubs['delete_link'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteLink', + if "delete_link" not in self._stubs: + self._stubs["delete_link"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteLink", request_serializer=logging_config.DeleteLinkRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_link'] + return self._stubs["delete_link"] @property - def list_links(self) -> Callable[ - [logging_config.ListLinksRequest], - logging_config.ListLinksResponse]: + def list_links( + self, + ) -> Callable[[logging_config.ListLinksRequest], logging_config.ListLinksResponse]: r"""Return a callable for the list links method over gRPC. Lists links. @@ -960,18 +987,18 @@ def list_links(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_links' not in self._stubs: - self._stubs['list_links'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListLinks', + if "list_links" not in self._stubs: + self._stubs["list_links"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListLinks", request_serializer=logging_config.ListLinksRequest.serialize, response_deserializer=logging_config.ListLinksResponse.deserialize, ) - return self._stubs['list_links'] + return self._stubs["list_links"] @property - def get_link(self) -> Callable[ - [logging_config.GetLinkRequest], - logging_config.Link]: + def get_link( + self, + ) -> Callable[[logging_config.GetLinkRequest], logging_config.Link]: r"""Return a callable for the get link method over gRPC. Gets a link. @@ -986,18 +1013,20 @@ def get_link(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_link' not in self._stubs: - self._stubs['get_link'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetLink', + if "get_link" not in self._stubs: + self._stubs["get_link"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetLink", request_serializer=logging_config.GetLinkRequest.serialize, response_deserializer=logging_config.Link.deserialize, ) - return self._stubs['get_link'] + return self._stubs["get_link"] @property - def list_exclusions(self) -> Callable[ - [logging_config.ListExclusionsRequest], - logging_config.ListExclusionsResponse]: + def list_exclusions( + self, + ) -> Callable[ + [logging_config.ListExclusionsRequest], logging_config.ListExclusionsResponse + ]: r"""Return a callable for the list exclusions method over gRPC. Lists all the exclusions on the \_Default sink in a parent @@ -1013,18 +1042,18 @@ def list_exclusions(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_exclusions' not in self._stubs: - self._stubs['list_exclusions'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListExclusions', + if "list_exclusions" not in self._stubs: + self._stubs["list_exclusions"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListExclusions", request_serializer=logging_config.ListExclusionsRequest.serialize, response_deserializer=logging_config.ListExclusionsResponse.deserialize, ) - return self._stubs['list_exclusions'] + return self._stubs["list_exclusions"] @property - def get_exclusion(self) -> Callable[ - [logging_config.GetExclusionRequest], - logging_config.LogExclusion]: + def get_exclusion( + self, + ) -> Callable[[logging_config.GetExclusionRequest], logging_config.LogExclusion]: r"""Return a callable for the get exclusion method over gRPC. Gets the description of an exclusion in the \_Default sink. @@ -1039,18 +1068,18 @@ def get_exclusion(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_exclusion' not in self._stubs: - self._stubs['get_exclusion'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetExclusion', + if "get_exclusion" not in self._stubs: + self._stubs["get_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetExclusion", request_serializer=logging_config.GetExclusionRequest.serialize, response_deserializer=logging_config.LogExclusion.deserialize, ) - return self._stubs['get_exclusion'] + return self._stubs["get_exclusion"] @property - def create_exclusion(self) -> Callable[ - [logging_config.CreateExclusionRequest], - logging_config.LogExclusion]: + def create_exclusion( + self, + ) -> Callable[[logging_config.CreateExclusionRequest], logging_config.LogExclusion]: r"""Return a callable for the create exclusion method over gRPC. Creates a new exclusion in the \_Default sink in a specified @@ -1067,18 +1096,18 @@ def create_exclusion(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_exclusion' not in self._stubs: - self._stubs['create_exclusion'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateExclusion', + if "create_exclusion" not in self._stubs: + self._stubs["create_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateExclusion", request_serializer=logging_config.CreateExclusionRequest.serialize, response_deserializer=logging_config.LogExclusion.deserialize, ) - return self._stubs['create_exclusion'] + return self._stubs["create_exclusion"] @property - def update_exclusion(self) -> Callable[ - [logging_config.UpdateExclusionRequest], - logging_config.LogExclusion]: + def update_exclusion( + self, + ) -> Callable[[logging_config.UpdateExclusionRequest], logging_config.LogExclusion]: r"""Return a callable for the update exclusion method over gRPC. Changes one or more properties of an existing exclusion in the @@ -1094,18 +1123,18 @@ def update_exclusion(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_exclusion' not in self._stubs: - self._stubs['update_exclusion'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateExclusion', + if "update_exclusion" not in self._stubs: + self._stubs["update_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateExclusion", request_serializer=logging_config.UpdateExclusionRequest.serialize, response_deserializer=logging_config.LogExclusion.deserialize, ) - return self._stubs['update_exclusion'] + return self._stubs["update_exclusion"] @property - def delete_exclusion(self) -> Callable[ - [logging_config.DeleteExclusionRequest], - empty_pb2.Empty]: + def delete_exclusion( + self, + ) -> Callable[[logging_config.DeleteExclusionRequest], empty_pb2.Empty]: r"""Return a callable for the delete exclusion method over gRPC. Deletes an exclusion in the \_Default sink. @@ -1120,18 +1149,18 @@ def delete_exclusion(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_exclusion' not in self._stubs: - self._stubs['delete_exclusion'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteExclusion', + if "delete_exclusion" not in self._stubs: + self._stubs["delete_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteExclusion", request_serializer=logging_config.DeleteExclusionRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_exclusion'] + return self._stubs["delete_exclusion"] @property - def get_cmek_settings(self) -> Callable[ - [logging_config.GetCmekSettingsRequest], - logging_config.CmekSettings]: + def get_cmek_settings( + self, + ) -> Callable[[logging_config.GetCmekSettingsRequest], logging_config.CmekSettings]: r"""Return a callable for the get cmek settings method over gRPC. Gets the Logging CMEK settings for the given resource. @@ -1155,18 +1184,20 @@ def get_cmek_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_cmek_settings' not in self._stubs: - self._stubs['get_cmek_settings'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetCmekSettings', + if "get_cmek_settings" not in self._stubs: + self._stubs["get_cmek_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetCmekSettings", request_serializer=logging_config.GetCmekSettingsRequest.serialize, response_deserializer=logging_config.CmekSettings.deserialize, ) - return self._stubs['get_cmek_settings'] + return self._stubs["get_cmek_settings"] @property - def update_cmek_settings(self) -> Callable[ - [logging_config.UpdateCmekSettingsRequest], - logging_config.CmekSettings]: + def update_cmek_settings( + self, + ) -> Callable[ + [logging_config.UpdateCmekSettingsRequest], logging_config.CmekSettings + ]: r"""Return a callable for the update cmek settings method over gRPC. Updates the Log Router CMEK settings for the given resource. @@ -1195,18 +1226,18 @@ def update_cmek_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_cmek_settings' not in self._stubs: - self._stubs['update_cmek_settings'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateCmekSettings', + if "update_cmek_settings" not in self._stubs: + self._stubs["update_cmek_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateCmekSettings", request_serializer=logging_config.UpdateCmekSettingsRequest.serialize, response_deserializer=logging_config.CmekSettings.deserialize, ) - return self._stubs['update_cmek_settings'] + return self._stubs["update_cmek_settings"] @property - def get_settings(self) -> Callable[ - [logging_config.GetSettingsRequest], - logging_config.Settings]: + def get_settings( + self, + ) -> Callable[[logging_config.GetSettingsRequest], logging_config.Settings]: r"""Return a callable for the get settings method over gRPC. Gets the Log Router settings for the given resource. @@ -1231,18 +1262,18 @@ def get_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_settings' not in self._stubs: - self._stubs['get_settings'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetSettings', + if "get_settings" not in self._stubs: + self._stubs["get_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetSettings", request_serializer=logging_config.GetSettingsRequest.serialize, response_deserializer=logging_config.Settings.deserialize, ) - return self._stubs['get_settings'] + return self._stubs["get_settings"] @property - def update_settings(self) -> Callable[ - [logging_config.UpdateSettingsRequest], - logging_config.Settings]: + def update_settings( + self, + ) -> Callable[[logging_config.UpdateSettingsRequest], logging_config.Settings]: r"""Return a callable for the update settings method over gRPC. Updates the Log Router settings for the given resource. @@ -1274,18 +1305,18 @@ def update_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_settings' not in self._stubs: - self._stubs['update_settings'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateSettings', + if "update_settings" not in self._stubs: + self._stubs["update_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateSettings", request_serializer=logging_config.UpdateSettingsRequest.serialize, response_deserializer=logging_config.Settings.deserialize, ) - return self._stubs['update_settings'] + return self._stubs["update_settings"] @property - def copy_log_entries(self) -> Callable[ - [logging_config.CopyLogEntriesRequest], - operations_pb2.Operation]: + def copy_log_entries( + self, + ) -> Callable[[logging_config.CopyLogEntriesRequest], operations_pb2.Operation]: r"""Return a callable for the copy log entries method over gRPC. Copies a set of log entries from a log bucket to a @@ -1301,13 +1332,13 @@ def copy_log_entries(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'copy_log_entries' not in self._stubs: - self._stubs['copy_log_entries'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CopyLogEntries', + if "copy_log_entries" not in self._stubs: + self._stubs["copy_log_entries"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CopyLogEntries", request_serializer=logging_config.CopyLogEntriesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['copy_log_entries'] + return self._stubs["copy_log_entries"] def close(self): self._logged_channel.close() @@ -1316,8 +1347,7 @@ def close(self): def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1334,8 +1364,7 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1351,9 +1380,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1371,6 +1401,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'ConfigServiceV2GrpcTransport', -) +__all__ = ("ConfigServiceV2GrpcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py index 50469def8e08..40c01d7305c8 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -13,29 +13,48 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import inspect import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Iterable, + Iterator, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.logging_v2 import gapic_version as package_version - +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.logging_v2 import gapic_version as package_version +from google.cloud.logging_v2._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -44,6 +63,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -57,12 +77,12 @@ _LOGGER = std_logging.getLogger(__name__) -from google.cloud.logging_v2.services.logging_service_v2 import pagers -from google.cloud.logging_v2.types import log_entry -from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore -from .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO +from google.cloud.logging_v2.services.logging_service_v2 import pagers +from google.cloud.logging_v2.types import log_entry, logging +from google.longrunning import operations_pb2 # type: ignore + +from .transports.base import DEFAULT_CLIENT_INFO, LoggingServiceV2Transport from .transports.grpc import LoggingServiceV2GrpcTransport from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport @@ -74,13 +94,15 @@ class LoggingServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[LoggingServiceV2Transport]] _transport_registry["grpc"] = LoggingServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = LoggingServiceV2GrpcAsyncIOTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[LoggingServiceV2Transport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[LoggingServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -140,8 +162,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LoggingServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -158,73 +179,103 @@ def transport(self) -> LoggingServiceV2Transport: return self._transport @staticmethod - def log_path(project: str,log: str,) -> str: + def log_path( + project: str, + log: str, + ) -> str: """Returns a fully-qualified log string.""" - return "projects/{project}/logs/{log}".format(project=project, log=log, ) + return "projects/{project}/logs/{log}".format( + project=project, + log=log, + ) @staticmethod - def parse_log_path(path: str) -> Dict[str,str]: + def parse_log_path(path: str) -> Dict[str, str]: """Parses a log path into its component segments.""" m = re.match(r"^projects/(?P.+?)/logs/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -256,14 +307,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -276,8 +331,10 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -316,15 +373,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -357,12 +417,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the logging service v2 client. Args: @@ -417,13 +483,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = LoggingServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = LoggingServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE, + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -435,7 +511,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -444,35 +522,41 @@ def __init__(self, *, if transport_provided: # transport is a LoggingServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." + "When providing a transport instance, provide its scopes directly." ) self._transport = cast(LoggingServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE, - default_mtls_endpoint=LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" or ( - self._use_mtls_endpoint == "auto" and self._client_cert_source - ), - )) + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE, + default_mtls_endpoint=LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[LoggingServiceV2Transport], Callable[..., LoggingServiceV2Transport]] = ( + transport_init: Union[ + Type[LoggingServiceV2Transport], + Callable[..., LoggingServiceV2Transport], + ] = ( LoggingServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., LoggingServiceV2Transport], transport) @@ -501,33 +585,46 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"client_options": client_options} if client_options else {}), + **( + {"client_options": client_options} + if client_options is not None + else {} + ), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.LoggingServiceV2Client`.", - extra = { + extra={ "serviceName": "google.logging.v2.LoggingServiceV2", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.logging.v2.LoggingServiceV2", "credentialsType": None, - } + }, ) - def delete_log(self, - request: Optional[Union[logging.DeleteLogRequest, dict]] = None, - *, - log_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_log( + self, + request: Optional[Union[logging.DeleteLogRequest, dict]] = None, + *, + log_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes all the log entries in a log for the \_Default Log Bucket. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be @@ -590,10 +687,14 @@ def sample_delete_log(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -611,9 +712,7 @@ def sample_delete_log(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("log_name", request.log_name), - )), + gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)), ) # Validate the universe domain. @@ -627,17 +726,18 @@ def sample_delete_log(): metadata=metadata, ) - def write_log_entries(self, - request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, - *, - log_name: Optional[str] = None, - resource: Optional[monitored_resource_pb2.MonitoredResource] = None, - labels: Optional[MutableMapping[str, str]] = None, - entries: Optional[MutableSequence[log_entry.LogEntry]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging.WriteLogEntriesResponse: + def write_log_entries( + self, + request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, + *, + log_name: Optional[str] = None, + resource: Optional[monitored_resource_pb2.MonitoredResource] = None, + labels: Optional[MutableMapping[str, str]] = None, + entries: Optional[MutableSequence[log_entry.LogEntry]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging.WriteLogEntriesResponse: r"""Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent @@ -780,10 +880,14 @@ def sample_write_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name, resource, labels, entries] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -818,16 +922,17 @@ def sample_write_log_entries(): # Done; return the response. return response - def list_log_entries(self, - request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, - *, - resource_names: Optional[MutableSequence[str]] = None, - filter: Optional[str] = None, - order_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogEntriesPager: + def list_log_entries( + self, + request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, + *, + resource_names: Optional[MutableSequence[str]] = None, + filter: Optional[str] = None, + order_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogEntriesPager: r"""Lists log entries. Use this method to retrieve log entries that originated from a project/folder/organization/billing account. For ways to export log entries, see `Exporting @@ -930,10 +1035,14 @@ def sample_list_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [resource_names, filter, order_by] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -977,13 +1086,16 @@ def sample_list_log_entries(): # Done; return the response. return response - def list_monitored_resource_descriptors(self, - request: Optional[Union[logging.ListMonitoredResourceDescriptorsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMonitoredResourceDescriptorsPager: + def list_monitored_resource_descriptors( + self, + request: Optional[ + Union[logging.ListMonitoredResourceDescriptorsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMonitoredResourceDescriptorsPager: r"""Lists the descriptors for monitored resource types used by Logging. @@ -1042,7 +1154,9 @@ def sample_list_monitored_resource_descriptors(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_monitored_resource_descriptors] + rpc = self._transport._wrapped_methods[ + self._transport.list_monitored_resource_descriptors + ] # Validate the universe domain. self._validate_universe_domain() @@ -1069,14 +1183,15 @@ def sample_list_monitored_resource_descriptors(): # Done; return the response. return response - def list_logs(self, - request: Optional[Union[logging.ListLogsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogsPager: + def list_logs( + self, + request: Optional[Union[logging.ListLogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogsPager: r"""Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have entries are listed. @@ -1143,10 +1258,14 @@ def sample_list_logs(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1164,9 +1283,7 @@ def sample_list_logs(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1194,13 +1311,14 @@ def sample_list_logs(): # Done; return the response. return response - def tail_log_entries(self, - requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Iterable[logging.TailLogEntriesResponse]: + def tail_log_entries( + self, + requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[logging.TailLogEntriesResponse]: r"""Streaming read of log entries as they are ingested. Until the stream is terminated, it will continue reading logs. @@ -1331,8 +1449,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1341,7 +1458,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1391,8 +1512,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1401,7 +1521,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1454,25 +1578,24 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - - - - + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "LoggingServiceV2Client", -) +__all__ = ("LoggingServiceV2Client",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index 133f00107ae2..82763d3d459b 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -17,52 +17,60 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.logging_v2 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.cloud.logging_v2 import gapic_version as package_version from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +# Check once at module load time whether google-api-core's wrap_method supports +# OpenTelemetry tracing arguments (client_options, method_name, is_streaming, kind) +# to avoid recurring inspect.signature latency during client instantiation. +_WRAP_METHOD_SUPPORTS_TRACING = ( + "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters +) + class LoggingServiceV2Transport(abc.ABC): """Abstract transport class for LoggingServiceV2.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", + "https://www.googleapis.com/auth/logging.write", ) - DEFAULT_HOST: str = 'logging.googleapis.com' + DEFAULT_HOST: str = "logging.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -104,38 +112,47 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._client_options = client_options - # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments - # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility - # with older versions of google-api-core. - self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrap_with_tracing = _WRAP_METHOD_SUPPORTS_TRACING self._wrapped_methods: Dict[Callable, Callable] = {} @@ -148,15 +165,24 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["client_options"] = self._client_options try: kwargs["kind"] = self.kind - # Base transport raises NotImplementedError for abstract kind property. - # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + # The abstract BaseTransport class raises NotImplementedError for the kind property. + # Concrete transport subclasses (gRPC, REST) override kind, so this exception handler + # is unreachable during normal execution. Excluded from coverage check. except NotImplementedError: # pragma: NO COVER pass return gapic_v1.method.wrap_method(func, *args, **kwargs) - # Remove tracing-specific arguments if older google-api-core is installed - for k in ["client_options", "method_name", "is_streaming", "kind"]: - kwargs.pop(k, None) - return gapic_v1.method.wrap_method(func, *args, **kwargs) + # The fallback below strips tracing-specific arguments when an older version + # of google-api-core is installed (which does not accept client_options, etc.). + # Excluded from coverage because our CI and testing environments always install + # a modern version of google-api-core that supports tracing. + for k in [ + "client_options", + "method_name", + "is_streaming", + "kind", + ]: # pragma: NO COVER + kwargs.pop(k, None) # pragma: NO COVER + return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -279,69 +305,77 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def delete_log(self) -> Callable[ - [logging.DeleteLogRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_log( + self, + ) -> Callable[ + [logging.DeleteLogRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: raise NotImplementedError() @property - def write_log_entries(self) -> Callable[ - [logging.WriteLogEntriesRequest], - Union[ - logging.WriteLogEntriesResponse, - Awaitable[logging.WriteLogEntriesResponse] - ]]: + def write_log_entries( + self, + ) -> Callable[ + [logging.WriteLogEntriesRequest], + Union[ + logging.WriteLogEntriesResponse, Awaitable[logging.WriteLogEntriesResponse] + ], + ]: raise NotImplementedError() @property - def list_log_entries(self) -> Callable[ - [logging.ListLogEntriesRequest], - Union[ - logging.ListLogEntriesResponse, - Awaitable[logging.ListLogEntriesResponse] - ]]: + def list_log_entries( + self, + ) -> Callable[ + [logging.ListLogEntriesRequest], + Union[ + logging.ListLogEntriesResponse, Awaitable[logging.ListLogEntriesResponse] + ], + ]: raise NotImplementedError() @property - def list_monitored_resource_descriptors(self) -> Callable[ - [logging.ListMonitoredResourceDescriptorsRequest], - Union[ - logging.ListMonitoredResourceDescriptorsResponse, - Awaitable[logging.ListMonitoredResourceDescriptorsResponse] - ]]: + def list_monitored_resource_descriptors( + self, + ) -> Callable[ + [logging.ListMonitoredResourceDescriptorsRequest], + Union[ + logging.ListMonitoredResourceDescriptorsResponse, + Awaitable[logging.ListMonitoredResourceDescriptorsResponse], + ], + ]: raise NotImplementedError() @property - def list_logs(self) -> Callable[ - [logging.ListLogsRequest], - Union[ - logging.ListLogsResponse, - Awaitable[logging.ListLogsResponse] - ]]: + def list_logs( + self, + ) -> Callable[ + [logging.ListLogsRequest], + Union[logging.ListLogsResponse, Awaitable[logging.ListLogsResponse]], + ]: raise NotImplementedError() @property - def tail_log_entries(self) -> Callable[ - [logging.TailLogEntriesRequest], - Union[ - logging.TailLogEntriesResponse, - Awaitable[logging.TailLogEntriesResponse] - ]]: + def tail_log_entries( + self, + ) -> Callable[ + [logging.TailLogEntriesRequest], + Union[ + logging.TailLogEntriesResponse, Awaitable[logging.TailLogEntriesResponse] + ], + ]: raise NotImplementedError() @property @@ -349,7 +383,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -376,6 +413,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'LoggingServiceV2Transport', -) +__all__ = ("LoggingServiceV2Transport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index 5df5fb7d48e1..bd4c44c84030 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -17,16 +17,19 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] + from google.api_core.grpc_helpers import ( + ClientInterceptor, # type: ignore[attr-defined] + ) from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 + # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -34,21 +37,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import proto # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.logging_v2.types import logging +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import proto # type: ignore -from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from .base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, LoggingServiceV2Transport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -58,7 +61,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -79,7 +84,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.logging.v2.LoggingServiceV2", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -90,7 +95,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -105,7 +114,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.logging.v2.LoggingServiceV2", "rpcName": client_call_details.method, "response": grpc_response, @@ -127,32 +136,35 @@ class LoggingServiceV2GrpcTransport(LoggingServiceV2Transport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'logging.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], - ] + def __init__( + self, + *, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -288,8 +300,17 @@ def __init__(self, *, channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None and otel_interceptor not in channel_interceptors + and not any( + getattr(i, "_is_otel_interceptor", None) is True + for i in channel_interceptors + ) ): channel_interceptors.append(otel_interceptor) @@ -298,22 +319,28 @@ def __init__(self, *, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) + self._grpc_channel = apply_interceptors( + self._grpc_channel, channel_interceptors + ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'logging.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -349,19 +376,16 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property - def delete_log(self) -> Callable[ - [logging.DeleteLogRequest], - empty_pb2.Empty]: + def delete_log(self) -> Callable[[logging.DeleteLogRequest], empty_pb2.Empty]: r"""Return a callable for the delete log method over gRPC. Deletes all the log entries in a log for the \_Default Log @@ -380,18 +404,18 @@ def delete_log(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_log' not in self._stubs: - self._stubs['delete_log'] = self._logged_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/DeleteLog', + if "delete_log" not in self._stubs: + self._stubs["delete_log"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/DeleteLog", request_serializer=logging.DeleteLogRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_log'] + return self._stubs["delete_log"] @property - def write_log_entries(self) -> Callable[ - [logging.WriteLogEntriesRequest], - logging.WriteLogEntriesResponse]: + def write_log_entries( + self, + ) -> Callable[[logging.WriteLogEntriesRequest], logging.WriteLogEntriesResponse]: r"""Return a callable for the write log entries method over gRPC. Writes log entries to Logging. This API method is the @@ -412,18 +436,18 @@ def write_log_entries(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'write_log_entries' not in self._stubs: - self._stubs['write_log_entries'] = self._logged_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/WriteLogEntries', + if "write_log_entries" not in self._stubs: + self._stubs["write_log_entries"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/WriteLogEntries", request_serializer=logging.WriteLogEntriesRequest.serialize, response_deserializer=logging.WriteLogEntriesResponse.deserialize, ) - return self._stubs['write_log_entries'] + return self._stubs["write_log_entries"] @property - def list_log_entries(self) -> Callable[ - [logging.ListLogEntriesRequest], - logging.ListLogEntriesResponse]: + def list_log_entries( + self, + ) -> Callable[[logging.ListLogEntriesRequest], logging.ListLogEntriesResponse]: r"""Return a callable for the list log entries method over gRPC. Lists log entries. Use this method to retrieve log entries that @@ -441,18 +465,21 @@ def list_log_entries(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_log_entries' not in self._stubs: - self._stubs['list_log_entries'] = self._logged_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/ListLogEntries', + if "list_log_entries" not in self._stubs: + self._stubs["list_log_entries"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/ListLogEntries", request_serializer=logging.ListLogEntriesRequest.serialize, response_deserializer=logging.ListLogEntriesResponse.deserialize, ) - return self._stubs['list_log_entries'] + return self._stubs["list_log_entries"] @property - def list_monitored_resource_descriptors(self) -> Callable[ - [logging.ListMonitoredResourceDescriptorsRequest], - logging.ListMonitoredResourceDescriptorsResponse]: + def list_monitored_resource_descriptors( + self, + ) -> Callable[ + [logging.ListMonitoredResourceDescriptorsRequest], + logging.ListMonitoredResourceDescriptorsResponse, + ]: r"""Return a callable for the list monitored resource descriptors method over gRPC. @@ -469,18 +496,20 @@ def list_monitored_resource_descriptors(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_monitored_resource_descriptors' not in self._stubs: - self._stubs['list_monitored_resource_descriptors'] = self._logged_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors', - request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize, - response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize, + if "list_monitored_resource_descriptors" not in self._stubs: + self._stubs["list_monitored_resource_descriptors"] = ( + self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors", + request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize, + response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize, + ) ) - return self._stubs['list_monitored_resource_descriptors'] + return self._stubs["list_monitored_resource_descriptors"] @property - def list_logs(self) -> Callable[ - [logging.ListLogsRequest], - logging.ListLogsResponse]: + def list_logs( + self, + ) -> Callable[[logging.ListLogsRequest], logging.ListLogsResponse]: r"""Return a callable for the list logs method over gRPC. Lists the logs in projects, organizations, folders, @@ -497,18 +526,18 @@ def list_logs(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_logs' not in self._stubs: - self._stubs['list_logs'] = self._logged_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/ListLogs', + if "list_logs" not in self._stubs: + self._stubs["list_logs"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/ListLogs", request_serializer=logging.ListLogsRequest.serialize, response_deserializer=logging.ListLogsResponse.deserialize, ) - return self._stubs['list_logs'] + return self._stubs["list_logs"] @property - def tail_log_entries(self) -> Callable[ - [logging.TailLogEntriesRequest], - logging.TailLogEntriesResponse]: + def tail_log_entries( + self, + ) -> Callable[[logging.TailLogEntriesRequest], logging.TailLogEntriesResponse]: r"""Return a callable for the tail log entries method over gRPC. Streaming read of log entries as they are ingested. @@ -525,13 +554,13 @@ def tail_log_entries(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'tail_log_entries' not in self._stubs: - self._stubs['tail_log_entries'] = self._logged_channel.stream_stream( - '/google.logging.v2.LoggingServiceV2/TailLogEntries', + if "tail_log_entries" not in self._stubs: + self._stubs["tail_log_entries"] = self._logged_channel.stream_stream( + "/google.logging.v2.LoggingServiceV2/TailLogEntries", request_serializer=logging.TailLogEntriesRequest.serialize, response_deserializer=logging.TailLogEntriesResponse.deserialize, ) - return self._stubs['tail_log_entries'] + return self._stubs["tail_log_entries"] def close(self): self._logged_channel.close() @@ -540,8 +569,7 @@ def close(self): def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -558,8 +586,7 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -575,9 +602,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -595,6 +623,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'LoggingServiceV2GrpcTransport', -) +__all__ = ("LoggingServiceV2GrpcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py index b8341f860cf0..45708b5c5e34 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -13,29 +13,46 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import inspect import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.logging_v2 import gapic_version as package_version - +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.logging_v2 import gapic_version as package_version +from google.cloud.logging_v2._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -44,6 +61,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -57,13 +75,14 @@ _LOGGER = std_logging.getLogger(__name__) -from google.cloud.logging_v2.services.metrics_service_v2 import pagers -from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore import google.api.distribution_pb2 as distribution_pb2 # type: ignore import google.api.metric_pb2 as metric_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO +from google.cloud.logging_v2.services.metrics_service_v2 import pagers +from google.cloud.logging_v2.types import logging_metrics +from google.longrunning import operations_pb2 # type: ignore + +from .transports.base import DEFAULT_CLIENT_INFO, MetricsServiceV2Transport from .transports.grpc import MetricsServiceV2GrpcTransport from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport @@ -75,13 +94,15 @@ class MetricsServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[MetricsServiceV2Transport]] _transport_registry["grpc"] = MetricsServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[MetricsServiceV2Transport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[MetricsServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -141,8 +162,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: MetricsServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -159,73 +179,103 @@ def transport(self) -> MetricsServiceV2Transport: return self._transport @staticmethod - def log_metric_path(project: str,metric: str,) -> str: + def log_metric_path( + project: str, + metric: str, + ) -> str: """Returns a fully-qualified log_metric string.""" - return "projects/{project}/metrics/{metric}".format(project=project, metric=metric, ) + return "projects/{project}/metrics/{metric}".format( + project=project, + metric=metric, + ) @staticmethod - def parse_log_metric_path(path: str) -> Dict[str,str]: + def parse_log_metric_path(path: str) -> Dict[str, str]: """Parses a log_metric path into its component segments.""" m = re.match(r"^projects/(?P.+?)/metrics/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -257,14 +307,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -277,8 +331,10 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -317,15 +373,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -358,12 +417,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the metrics service v2 client. Args: @@ -418,13 +483,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = MetricsServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=MetricsServiceV2Client._DEFAULT_UNIVERSE) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = MetricsServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=MetricsServiceV2Client._DEFAULT_UNIVERSE, + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -436,7 +511,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -445,35 +522,41 @@ def __init__(self, *, if transport_provided: # transport is a MetricsServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." + "When providing a transport instance, provide its scopes directly." ) self._transport = cast(MetricsServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=MetricsServiceV2Client._DEFAULT_UNIVERSE, - default_mtls_endpoint=MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" or ( - self._use_mtls_endpoint == "auto" and self._client_cert_source - ), - )) + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=MetricsServiceV2Client._DEFAULT_UNIVERSE, + default_mtls_endpoint=MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[MetricsServiceV2Transport], Callable[..., MetricsServiceV2Transport]] = ( + transport_init: Union[ + Type[MetricsServiceV2Transport], + Callable[..., MetricsServiceV2Transport], + ] = ( MetricsServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., MetricsServiceV2Transport], transport) @@ -502,33 +585,46 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"client_options": client_options} if client_options else {}), + **( + {"client_options": client_options} + if client_options is not None + else {} + ), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.MetricsServiceV2Client`.", - extra = { + extra={ "serviceName": "google.logging.v2.MetricsServiceV2", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.logging.v2.MetricsServiceV2", "credentialsType": None, - } + }, ) - def list_log_metrics(self, - request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogMetricsPager: + def list_log_metrics( + self, + request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogMetricsPager: r"""Lists logs-based metrics. .. code-block:: python @@ -593,10 +689,14 @@ def sample_list_log_metrics(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -614,9 +714,7 @@ def sample_list_log_metrics(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -644,14 +742,15 @@ def sample_list_log_metrics(): # Done; return the response. return response - def get_log_metric(self, - request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def get_log_metric( + self, + request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Gets a logs-based metric. .. code-block:: python @@ -721,10 +820,14 @@ def sample_get_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -742,9 +845,9 @@ def sample_get_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -761,15 +864,16 @@ def sample_get_log_metric(): # Done; return the response. return response - def create_log_metric(self, - request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, - *, - parent: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def create_log_metric( + self, + request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates a logs-based metric. .. code-block:: python @@ -855,10 +959,14 @@ def sample_create_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, metric] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -878,9 +986,7 @@ def sample_create_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -897,15 +1003,16 @@ def sample_create_log_metric(): # Done; return the response. return response - def update_log_metric(self, - request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def update_log_metric( + self, + request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates or updates a logs-based metric. .. code-block:: python @@ -990,10 +1097,14 @@ def sample_update_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name, metric] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1013,9 +1124,9 @@ def sample_update_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -1032,14 +1143,15 @@ def sample_update_log_metric(): # Done; return the response. return response - def delete_log_metric(self, - request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_log_metric( + self, + request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a logs-based metric. .. code-block:: python @@ -1090,10 +1202,14 @@ def sample_delete_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1111,9 +1227,9 @@ def sample_delete_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -1182,8 +1298,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1192,7 +1307,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1242,8 +1361,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1252,7 +1370,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1305,25 +1427,24 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - - - - + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "MetricsServiceV2Client", -) +__all__ = ("MetricsServiceV2Client",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index 292ad249a3f6..5e8c203f0a9f 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -17,52 +17,60 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.logging_v2 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.cloud.logging_v2 import gapic_version as package_version from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +# Check once at module load time whether google-api-core's wrap_method supports +# OpenTelemetry tracing arguments (client_options, method_name, is_streaming, kind) +# to avoid recurring inspect.signature latency during client instantiation. +_WRAP_METHOD_SUPPORTS_TRACING = ( + "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters +) + class MetricsServiceV2Transport(abc.ABC): """Abstract transport class for MetricsServiceV2.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", + "https://www.googleapis.com/auth/logging.write", ) - DEFAULT_HOST: str = 'logging.googleapis.com' + DEFAULT_HOST: str = "logging.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -104,38 +112,47 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._client_options = client_options - # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments - # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility - # with older versions of google-api-core. - self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrap_with_tracing = _WRAP_METHOD_SUPPORTS_TRACING self._wrapped_methods: Dict[Callable, Callable] = {} @@ -148,15 +165,24 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["client_options"] = self._client_options try: kwargs["kind"] = self.kind - # Base transport raises NotImplementedError for abstract kind property. - # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + # The abstract BaseTransport class raises NotImplementedError for the kind property. + # Concrete transport subclasses (gRPC, REST) override kind, so this exception handler + # is unreachable during normal execution. Excluded from coverage check. except NotImplementedError: # pragma: NO COVER pass return gapic_v1.method.wrap_method(func, *args, **kwargs) - # Remove tracing-specific arguments if older google-api-core is installed - for k in ["client_options", "method_name", "is_streaming", "kind"]: - kwargs.pop(k, None) - return gapic_v1.method.wrap_method(func, *args, **kwargs) + # The fallback below strips tracing-specific arguments when an older version + # of google-api-core is installed (which does not accept client_options, etc.). + # Excluded from coverage because our CI and testing environments always install + # a modern version of google-api-core that supports tracing. + for k in [ + "client_options", + "method_name", + "is_streaming", + "kind", + ]: # pragma: NO COVER + kwargs.pop(k, None) # pragma: NO COVER + return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -250,60 +276,63 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def list_log_metrics(self) -> Callable[ - [logging_metrics.ListLogMetricsRequest], - Union[ - logging_metrics.ListLogMetricsResponse, - Awaitable[logging_metrics.ListLogMetricsResponse] - ]]: + def list_log_metrics( + self, + ) -> Callable[ + [logging_metrics.ListLogMetricsRequest], + Union[ + logging_metrics.ListLogMetricsResponse, + Awaitable[logging_metrics.ListLogMetricsResponse], + ], + ]: raise NotImplementedError() @property - def get_log_metric(self) -> Callable[ - [logging_metrics.GetLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: + def get_log_metric( + self, + ) -> Callable[ + [logging_metrics.GetLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: raise NotImplementedError() @property - def create_log_metric(self) -> Callable[ - [logging_metrics.CreateLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: + def create_log_metric( + self, + ) -> Callable[ + [logging_metrics.CreateLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: raise NotImplementedError() @property - def update_log_metric(self) -> Callable[ - [logging_metrics.UpdateLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: + def update_log_metric( + self, + ) -> Callable[ + [logging_metrics.UpdateLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: raise NotImplementedError() @property - def delete_log_metric(self) -> Callable[ - [logging_metrics.DeleteLogMetricRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_log_metric( + self, + ) -> Callable[ + [logging_metrics.DeleteLogMetricRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property @@ -311,7 +340,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -338,6 +370,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'MetricsServiceV2Transport', -) +__all__ = ("MetricsServiceV2Transport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index 358403b0f13a..8b3f065959fb 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -17,16 +17,19 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] + from google.api_core.grpc_helpers import ( + ClientInterceptor, # type: ignore[attr-defined] + ) from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 + # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -34,21 +37,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import proto # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.logging_v2.types import logging_metrics +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import proto # type: ignore -from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from .base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, MetricsServiceV2Transport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -58,7 +61,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -79,7 +84,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.logging.v2.MetricsServiceV2", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -90,7 +95,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -105,7 +114,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.logging.v2.MetricsServiceV2", "rpcName": client_call_details.method, "response": grpc_response, @@ -127,32 +136,35 @@ class MetricsServiceV2GrpcTransport(MetricsServiceV2Transport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'logging.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], - ] + def __init__( + self, + *, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -288,8 +300,17 @@ def __init__(self, *, channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None and otel_interceptor not in channel_interceptors + and not any( + getattr(i, "_is_otel_interceptor", None) is True + for i in channel_interceptors + ) ): channel_interceptors.append(otel_interceptor) @@ -298,22 +319,28 @@ def __init__(self, *, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) + self._grpc_channel = apply_interceptors( + self._grpc_channel, channel_interceptors + ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'logging.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -349,19 +376,20 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property - def list_log_metrics(self) -> Callable[ - [logging_metrics.ListLogMetricsRequest], - logging_metrics.ListLogMetricsResponse]: + def list_log_metrics( + self, + ) -> Callable[ + [logging_metrics.ListLogMetricsRequest], logging_metrics.ListLogMetricsResponse + ]: r"""Return a callable for the list log metrics method over gRPC. Lists logs-based metrics. @@ -376,18 +404,18 @@ def list_log_metrics(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_log_metrics' not in self._stubs: - self._stubs['list_log_metrics'] = self._logged_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/ListLogMetrics', + if "list_log_metrics" not in self._stubs: + self._stubs["list_log_metrics"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/ListLogMetrics", request_serializer=logging_metrics.ListLogMetricsRequest.serialize, response_deserializer=logging_metrics.ListLogMetricsResponse.deserialize, ) - return self._stubs['list_log_metrics'] + return self._stubs["list_log_metrics"] @property - def get_log_metric(self) -> Callable[ - [logging_metrics.GetLogMetricRequest], - logging_metrics.LogMetric]: + def get_log_metric( + self, + ) -> Callable[[logging_metrics.GetLogMetricRequest], logging_metrics.LogMetric]: r"""Return a callable for the get log metric method over gRPC. Gets a logs-based metric. @@ -402,18 +430,18 @@ def get_log_metric(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_log_metric' not in self._stubs: - self._stubs['get_log_metric'] = self._logged_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/GetLogMetric', + if "get_log_metric" not in self._stubs: + self._stubs["get_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/GetLogMetric", request_serializer=logging_metrics.GetLogMetricRequest.serialize, response_deserializer=logging_metrics.LogMetric.deserialize, ) - return self._stubs['get_log_metric'] + return self._stubs["get_log_metric"] @property - def create_log_metric(self) -> Callable[ - [logging_metrics.CreateLogMetricRequest], - logging_metrics.LogMetric]: + def create_log_metric( + self, + ) -> Callable[[logging_metrics.CreateLogMetricRequest], logging_metrics.LogMetric]: r"""Return a callable for the create log metric method over gRPC. Creates a logs-based metric. @@ -428,18 +456,18 @@ def create_log_metric(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_log_metric' not in self._stubs: - self._stubs['create_log_metric'] = self._logged_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/CreateLogMetric', + if "create_log_metric" not in self._stubs: + self._stubs["create_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/CreateLogMetric", request_serializer=logging_metrics.CreateLogMetricRequest.serialize, response_deserializer=logging_metrics.LogMetric.deserialize, ) - return self._stubs['create_log_metric'] + return self._stubs["create_log_metric"] @property - def update_log_metric(self) -> Callable[ - [logging_metrics.UpdateLogMetricRequest], - logging_metrics.LogMetric]: + def update_log_metric( + self, + ) -> Callable[[logging_metrics.UpdateLogMetricRequest], logging_metrics.LogMetric]: r"""Return a callable for the update log metric method over gRPC. Creates or updates a logs-based metric. @@ -454,18 +482,18 @@ def update_log_metric(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_log_metric' not in self._stubs: - self._stubs['update_log_metric'] = self._logged_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/UpdateLogMetric', + if "update_log_metric" not in self._stubs: + self._stubs["update_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/UpdateLogMetric", request_serializer=logging_metrics.UpdateLogMetricRequest.serialize, response_deserializer=logging_metrics.LogMetric.deserialize, ) - return self._stubs['update_log_metric'] + return self._stubs["update_log_metric"] @property - def delete_log_metric(self) -> Callable[ - [logging_metrics.DeleteLogMetricRequest], - empty_pb2.Empty]: + def delete_log_metric( + self, + ) -> Callable[[logging_metrics.DeleteLogMetricRequest], empty_pb2.Empty]: r"""Return a callable for the delete log metric method over gRPC. Deletes a logs-based metric. @@ -480,13 +508,13 @@ def delete_log_metric(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_log_metric' not in self._stubs: - self._stubs['delete_log_metric'] = self._logged_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/DeleteLogMetric', + if "delete_log_metric" not in self._stubs: + self._stubs["delete_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/DeleteLogMetric", request_serializer=logging_metrics.DeleteLogMetricRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_log_metric'] + return self._stubs["delete_log_metric"] def close(self): self._logged_channel.close() @@ -495,8 +523,7 @@ def close(self): def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -513,8 +540,7 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -530,9 +556,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -550,6 +577,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'MetricsServiceV2GrpcTransport', -) +__all__ = ("MetricsServiceV2GrpcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py index eea18eb4f790..a9b4f7214230 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py @@ -13,29 +13,46 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import inspect import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.logging_v2 import gapic_version as package_version - +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.logging_v2 import gapic_version as package_version +from google.cloud.logging_v2._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -44,6 +61,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -57,15 +75,16 @@ _LOGGER = std_logging.getLogger(__name__) -from google.cloud.logging_v2.services.config_service_v2 import pagers -from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import ConfigServiceV2Transport, DEFAULT_CLIENT_INFO +from google.cloud.logging_v2.services.config_service_v2 import pagers +from google.cloud.logging_v2.types import logging_config +from google.longrunning import operations_pb2 # type: ignore + +from .transports.base import DEFAULT_CLIENT_INFO, ConfigServiceV2Transport from .transports.grpc import ConfigServiceV2GrpcTransport from .transports.grpc_asyncio import ConfigServiceV2GrpcAsyncIOTransport @@ -77,13 +96,15 @@ class BaseConfigServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[ConfigServiceV2Transport]] _transport_registry["grpc"] = ConfigServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = ConfigServiceV2GrpcAsyncIOTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConfigServiceV2Transport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ConfigServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -143,8 +164,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BaseConfigServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -161,139 +181,220 @@ def transport(self) -> ConfigServiceV2Transport: return self._transport @staticmethod - def cmek_settings_path(project: str,) -> str: + def cmek_settings_path( + project: str, + ) -> str: """Returns a fully-qualified cmek_settings string.""" - return "projects/{project}/cmekSettings".format(project=project, ) + return "projects/{project}/cmekSettings".format( + project=project, + ) @staticmethod - def parse_cmek_settings_path(path: str) -> Dict[str,str]: + def parse_cmek_settings_path(path: str) -> Dict[str, str]: """Parses a cmek_settings path into its component segments.""" m = re.match(r"^projects/(?P.+?)/cmekSettings$", path) return m.groupdict() if m else {} @staticmethod - def link_path(project: str,location: str,bucket: str,link: str,) -> str: + def link_path( + project: str, + location: str, + bucket: str, + link: str, + ) -> str: """Returns a fully-qualified link string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format(project=project, location=location, bucket=bucket, link=link, ) + return "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format( + project=project, + location=location, + bucket=bucket, + link=link, + ) @staticmethod - def parse_link_path(path: str) -> Dict[str,str]: + def parse_link_path(path: str) -> Dict[str, str]: """Parses a link path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/links/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/links/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def log_bucket_path(project: str,location: str,bucket: str,) -> str: + def log_bucket_path( + project: str, + location: str, + bucket: str, + ) -> str: """Returns a fully-qualified log_bucket string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}".format(project=project, location=location, bucket=bucket, ) + return "projects/{project}/locations/{location}/buckets/{bucket}".format( + project=project, + location=location, + bucket=bucket, + ) @staticmethod - def parse_log_bucket_path(path: str) -> Dict[str,str]: + def parse_log_bucket_path(path: str) -> Dict[str, str]: """Parses a log_bucket path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def log_exclusion_path(project: str,exclusion: str,) -> str: + def log_exclusion_path( + project: str, + exclusion: str, + ) -> str: """Returns a fully-qualified log_exclusion string.""" - return "projects/{project}/exclusions/{exclusion}".format(project=project, exclusion=exclusion, ) + return "projects/{project}/exclusions/{exclusion}".format( + project=project, + exclusion=exclusion, + ) @staticmethod - def parse_log_exclusion_path(path: str) -> Dict[str,str]: + def parse_log_exclusion_path(path: str) -> Dict[str, str]: """Parses a log_exclusion path into its component segments.""" m = re.match(r"^projects/(?P.+?)/exclusions/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_sink_path(project: str,sink: str,) -> str: + def log_sink_path( + project: str, + sink: str, + ) -> str: """Returns a fully-qualified log_sink string.""" - return "projects/{project}/sinks/{sink}".format(project=project, sink=sink, ) + return "projects/{project}/sinks/{sink}".format( + project=project, + sink=sink, + ) @staticmethod - def parse_log_sink_path(path: str) -> Dict[str,str]: + def parse_log_sink_path(path: str) -> Dict[str, str]: """Parses a log_sink path into its component segments.""" m = re.match(r"^projects/(?P.+?)/sinks/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_view_path(project: str,location: str,bucket: str,view: str,) -> str: + def log_view_path( + project: str, + location: str, + bucket: str, + view: str, + ) -> str: """Returns a fully-qualified log_view string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format(project=project, location=location, bucket=bucket, view=view, ) + return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format( + project=project, + location=location, + bucket=bucket, + view=view, + ) @staticmethod - def parse_log_view_path(path: str) -> Dict[str,str]: + def parse_log_view_path(path: str) -> Dict[str, str]: """Parses a log_view path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def settings_path(project: str,) -> str: + def settings_path( + project: str, + ) -> str: """Returns a fully-qualified settings string.""" - return "projects/{project}/settings".format(project=project, ) + return "projects/{project}/settings".format( + project=project, + ) @staticmethod - def parse_settings_path(path: str) -> Dict[str,str]: + def parse_settings_path(path: str) -> Dict[str, str]: """Parses a settings path into its component segments.""" m = re.match(r"^projects/(?P.+?)/settings$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -325,14 +426,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -345,8 +450,10 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -385,15 +492,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -426,12 +536,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the base config service v2 client. Args: @@ -486,13 +602,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = BaseConfigServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=BaseConfigServiceV2Client._DEFAULT_UNIVERSE) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = BaseConfigServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=BaseConfigServiceV2Client._DEFAULT_UNIVERSE, + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -504,7 +630,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -513,35 +641,40 @@ def __init__(self, *, if transport_provided: # transport is a ConfigServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." + "When providing a transport instance, provide its scopes directly." ) self._transport = cast(ConfigServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=BaseConfigServiceV2Client._DEFAULT_UNIVERSE, - default_mtls_endpoint=BaseConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=BaseConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" or ( - self._use_mtls_endpoint == "auto" and self._client_cert_source - ), - )) + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=BaseConfigServiceV2Client._DEFAULT_UNIVERSE, + default_mtls_endpoint=BaseConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=BaseConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[ConfigServiceV2Transport], Callable[..., ConfigServiceV2Transport]] = ( + transport_init: Union[ + Type[ConfigServiceV2Transport], Callable[..., ConfigServiceV2Transport] + ] = ( BaseConfigServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ConfigServiceV2Transport], transport) @@ -570,33 +703,46 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"client_options": client_options} if client_options else {}), + **( + {"client_options": client_options} + if client_options is not None + else {} + ), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.BaseConfigServiceV2Client`.", - extra = { + extra={ "serviceName": "google.logging.v2.ConfigServiceV2", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.logging.v2.ConfigServiceV2", "credentialsType": None, - } + }, ) - def list_buckets(self, - request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBucketsPager: + def list_buckets( + self, + request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketsPager: r"""Lists log buckets. .. code-block:: python @@ -668,10 +814,14 @@ def sample_list_buckets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -689,9 +839,7 @@ def sample_list_buckets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -719,13 +867,14 @@ def sample_list_buckets(): # Done; return the response. return response - def get_bucket(self, - request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def get_bucket( + self, + request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Gets a log bucket. .. code-block:: python @@ -784,9 +933,7 @@ def sample_get_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -803,13 +950,14 @@ def sample_get_bucket(): # Done; return the response. return response - def create_bucket_async(self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_bucket_async( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a log bucket asynchronously that can be used to store log entries. After a bucket has been created, the bucket's location @@ -879,9 +1027,7 @@ def sample_create_bucket_async(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -906,13 +1052,14 @@ def sample_create_bucket_async(): # Done; return the response. return response - def update_bucket_async(self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_bucket_async( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates a log bucket asynchronously. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -984,9 +1131,7 @@ def sample_update_bucket_async(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1011,13 +1156,14 @@ def sample_update_bucket_async(): # Done; return the response. return response - def create_bucket(self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def create_bucket( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Creates a log bucket that can be used to store log entries. After a bucket has been created, the bucket's location cannot be changed. @@ -1079,9 +1225,7 @@ def sample_create_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1098,13 +1242,14 @@ def sample_create_bucket(): # Done; return the response. return response - def update_bucket(self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def update_bucket( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Updates a log bucket. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -1169,9 +1314,7 @@ def sample_update_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1188,13 +1331,14 @@ def sample_update_bucket(): # Done; return the response. return response - def delete_bucket(self, - request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_bucket( + self, + request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a log bucket. Changes the bucket's ``lifecycle_state`` to the @@ -1249,9 +1393,7 @@ def sample_delete_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1265,13 +1407,14 @@ def sample_delete_bucket(): metadata=metadata, ) - def undelete_bucket(self, - request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def undelete_bucket( + self, + request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Undeletes a log bucket. A bucket that has been deleted can be undeleted within the grace period of 7 days. @@ -1323,9 +1466,7 @@ def sample_undelete_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1339,14 +1480,15 @@ def sample_undelete_bucket(): metadata=metadata, ) - def _list_views(self, - request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListViewsPager: + def _list_views( + self, + request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListViewsPager: r"""Lists views on a log bucket. .. code-block:: python @@ -1410,10 +1552,14 @@ def sample_list_views(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1431,9 +1577,7 @@ def sample_list_views(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1461,13 +1605,14 @@ def sample_list_views(): # Done; return the response. return response - def _get_view(self, - request: Optional[Union[logging_config.GetViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def _get_view( + self, + request: Optional[Union[logging_config.GetViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Gets a view on a log bucket.. .. code-block:: python @@ -1526,9 +1671,7 @@ def sample_get_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1545,13 +1688,14 @@ def sample_get_view(): # Done; return the response. return response - def _create_view(self, - request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def _create_view( + self, + request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Creates a view over log entries in a log bucket. A bucket may contain a maximum of 30 views. @@ -1612,9 +1756,7 @@ def sample_create_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1631,13 +1773,14 @@ def sample_create_view(): # Done; return the response. return response - def _update_view(self, - request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def _update_view( + self, + request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Updates a view on a log bucket. This method replaces the following fields in the existing view with values from the new view: ``filter``. If an ``UNAVAILABLE`` error is returned, this @@ -1700,9 +1843,7 @@ def sample_update_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1719,13 +1860,14 @@ def sample_update_view(): # Done; return the response. return response - def _delete_view(self, - request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def _delete_view( + self, + request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is returned, this indicates that system is not in a state where it can delete the view. If this occurs, please try again in a few @@ -1778,9 +1920,7 @@ def sample_delete_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1794,14 +1934,15 @@ def sample_delete_view(): metadata=metadata, ) - def _list_sinks(self, - request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListSinksPager: + def _list_sinks( + self, + request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSinksPager: r"""Lists sinks. .. code-block:: python @@ -1868,10 +2009,14 @@ def sample_list_sinks(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1889,9 +2034,7 @@ def sample_list_sinks(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1919,14 +2062,15 @@ def sample_list_sinks(): # Done; return the response. return response - def _get_sink(self, - request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def _get_sink( + self, + request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Gets a sink. .. code-block:: python @@ -2000,10 +2144,14 @@ def sample_get_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2021,9 +2169,9 @@ def sample_get_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2040,15 +2188,16 @@ def sample_get_sink(): # Done; return the response. return response - def _create_sink(self, - request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def _create_sink( + self, + request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not @@ -2138,10 +2287,14 @@ def sample_create_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, sink] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2161,9 +2314,7 @@ def sample_create_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2180,16 +2331,17 @@ def sample_create_sink(): # Done; return the response. return response - def _update_sink(self, - request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def _update_sink( + self, + request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: ``destination``, and ``filter``. @@ -2303,10 +2455,14 @@ def sample_update_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name, sink, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2328,9 +2484,9 @@ def sample_update_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2347,14 +2503,15 @@ def sample_update_sink(): # Done; return the response. return response - def _delete_sink(self, - request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def _delete_sink( + self, + request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a sink. If the sink has a unique ``writer_identity``, then that service account is also deleted. @@ -2414,10 +2571,14 @@ def sample_delete_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2435,9 +2596,9 @@ def sample_delete_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2451,16 +2612,17 @@ def sample_delete_sink(): metadata=metadata, ) - def _create_link(self, - request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - link: Optional[logging_config.Link] = None, - link_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def _create_link( + self, + request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + link: Optional[logging_config.Link] = None, + link_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Asynchronously creates a linked dataset in BigQuery which makes it possible to use BigQuery to read the logs stored in the log bucket. A log bucket may currently @@ -2548,10 +2710,14 @@ def sample_create_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, link, link_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2573,9 +2739,7 @@ def sample_create_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2600,14 +2764,15 @@ def sample_create_link(): # Done; return the response. return response - def _delete_link(self, - request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def _delete_link( + self, + request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes a link. This will also delete the corresponding BigQuery linked dataset. @@ -2683,10 +2848,14 @@ def sample_delete_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2704,9 +2873,7 @@ def sample_delete_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2731,14 +2898,15 @@ def sample_delete_link(): # Done; return the response. return response - def _list_links(self, - request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLinksPager: + def _list_links( + self, + request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLinksPager: r"""Lists links. .. code-block:: python @@ -2804,10 +2972,14 @@ def sample_list_links(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2825,9 +2997,7 @@ def sample_list_links(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2855,14 +3025,15 @@ def sample_list_links(): # Done; return the response. return response - def _get_link(self, - request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Link: + def _get_link( + self, + request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Link: r"""Gets a link. .. code-block:: python @@ -2923,10 +3094,14 @@ def sample_get_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2944,9 +3119,7 @@ def sample_get_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2963,14 +3136,15 @@ def sample_get_link(): # Done; return the response. return response - def _list_exclusions(self, - request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListExclusionsPager: + def _list_exclusions( + self, + request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExclusionsPager: r"""Lists all the exclusions on the \_Default sink in a parent resource. @@ -3038,10 +3212,14 @@ def sample_list_exclusions(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3059,9 +3237,7 @@ def sample_list_exclusions(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3089,14 +3265,15 @@ def sample_list_exclusions(): # Done; return the response. return response - def _get_exclusion(self, - request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def _get_exclusion( + self, + request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Gets the description of an exclusion in the \_Default sink. .. code-block:: python @@ -3168,10 +3345,14 @@ def sample_get_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3189,9 +3370,7 @@ def sample_get_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3208,15 +3387,16 @@ def sample_get_exclusion(): # Done; return the response. return response - def _create_exclusion(self, - request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, - *, - parent: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def _create_exclusion( + self, + request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, + *, + parent: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Creates a new exclusion in the \_Default sink in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. @@ -3305,10 +3485,14 @@ def sample_create_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, exclusion] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3328,9 +3512,7 @@ def sample_create_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3347,16 +3529,17 @@ def sample_create_exclusion(): # Done; return the response. return response - def _update_exclusion(self, - request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def _update_exclusion( + self, + request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Changes one or more properties of an existing exclusion in the \_Default sink. @@ -3456,10 +3639,14 @@ def sample_update_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, exclusion, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3481,9 +3668,7 @@ def sample_update_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3500,14 +3685,15 @@ def sample_update_exclusion(): # Done; return the response. return response - def _delete_exclusion(self, - request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def _delete_exclusion( + self, + request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes an exclusion in the \_Default sink. .. code-block:: python @@ -3566,10 +3752,14 @@ def sample_delete_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3587,9 +3777,7 @@ def sample_delete_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3603,13 +3791,14 @@ def sample_delete_exclusion(): metadata=metadata, ) - def _get_cmek_settings(self, - request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + def _get_cmek_settings( + self, + request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Gets the Logging CMEK settings for the given resource. Note: CMEK for the Log Router can be configured for Google Cloud @@ -3692,9 +3881,7 @@ def sample_get_cmek_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3711,13 +3898,14 @@ def sample_get_cmek_settings(): # Done; return the response. return response - def _update_cmek_settings(self, - request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + def _update_cmek_settings( + self, + request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Updates the Log Router CMEK settings for the given resource. Note: CMEK for the Log Router can currently only be configured @@ -3805,9 +3993,7 @@ def sample_update_cmek_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3824,14 +4010,15 @@ def sample_update_cmek_settings(): # Done; return the response. return response - def _get_settings(self, - request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + def _get_settings( + self, + request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Gets the Log Router settings for the given resource. Note: Settings for the Log Router can be get for Google Cloud @@ -3921,10 +4108,14 @@ def sample_get_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3942,9 +4133,7 @@ def sample_get_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3961,15 +4150,16 @@ def sample_get_settings(): # Done; return the response. return response - def _update_settings(self, - request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, - *, - settings: Optional[logging_config.Settings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + def _update_settings( + self, + request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, + *, + settings: Optional[logging_config.Settings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Updates the Log Router settings for the given resource. Note: Settings for the Log Router can currently only be @@ -4066,10 +4256,14 @@ def sample_update_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4089,9 +4283,7 @@ def sample_update_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4108,13 +4300,14 @@ def sample_update_settings(): # Done; return the response. return response - def _copy_log_entries(self, - request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def _copy_log_entries( + self, + request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Copies a set of log entries from a log bucket to a Cloud Storage bucket. @@ -4257,8 +4450,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -4267,7 +4459,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -4317,8 +4513,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -4327,7 +4522,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -4380,25 +4579,24 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - - - - + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "BaseConfigServiceV2Client", -) +__all__ = ("BaseConfigServiceV2Client",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py index f76b68bfee94..97dbac19187d 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -17,52 +17,59 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.logging_v2 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.cloud.logging_v2 import gapic_version as package_version from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +# Check once at module load time whether google-api-core's wrap_method supports +# OpenTelemetry tracing arguments (client_options, method_name, is_streaming, kind) +# to avoid recurring inspect.signature latency during client instantiation. +_WRAP_METHOD_SUPPORTS_TRACING = ( + "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters +) + class ConfigServiceV2Transport(abc.ABC): """Abstract transport class for ConfigServiceV2.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", ) - DEFAULT_HOST: str = 'logging.googleapis.com' + DEFAULT_HOST: str = "logging.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -104,38 +111,47 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._client_options = client_options - # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments - # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility - # with older versions of google-api-core. - self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrap_with_tracing = _WRAP_METHOD_SUPPORTS_TRACING self._wrapped_methods: Dict[Callable, Callable] = {} @@ -148,15 +164,24 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["client_options"] = self._client_options try: kwargs["kind"] = self.kind - # Base transport raises NotImplementedError for abstract kind property. - # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + # The abstract BaseTransport class raises NotImplementedError for the kind property. + # Concrete transport subclasses (gRPC, REST) override kind, so this exception handler + # is unreachable during normal execution. Excluded from coverage check. except NotImplementedError: # pragma: NO COVER pass return gapic_v1.method.wrap_method(func, *args, **kwargs) - # Remove tracing-specific arguments if older google-api-core is installed - for k in ["client_options", "method_name", "is_streaming", "kind"]: - kwargs.pop(k, None) - return gapic_v1.method.wrap_method(func, *args, **kwargs) + # The fallback below strips tracing-specific arguments when an older version + # of google-api-core is installed (which does not accept client_options, etc.). + # Excluded from coverage because our CI and testing environments always install + # a modern version of google-api-core that supports tracing. + for k in [ + "client_options", + "method_name", + "is_streaming", + "kind", + ]: # pragma: NO COVER + kwargs.pop(k, None) # pragma: NO COVER + return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -445,14 +470,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -462,291 +487,306 @@ def operations_client(self): raise NotImplementedError() @property - def list_buckets(self) -> Callable[ - [logging_config.ListBucketsRequest], - Union[ - logging_config.ListBucketsResponse, - Awaitable[logging_config.ListBucketsResponse] - ]]: + def list_buckets( + self, + ) -> Callable[ + [logging_config.ListBucketsRequest], + Union[ + logging_config.ListBucketsResponse, + Awaitable[logging_config.ListBucketsResponse], + ], + ]: raise NotImplementedError() @property - def get_bucket(self) -> Callable[ - [logging_config.GetBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: + def get_bucket( + self, + ) -> Callable[ + [logging_config.GetBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: raise NotImplementedError() @property - def create_bucket_async(self) -> Callable[ - [logging_config.CreateBucketRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_bucket_async( + self, + ) -> Callable[ + [logging_config.CreateBucketRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_bucket_async(self) -> Callable[ - [logging_config.UpdateBucketRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_bucket_async( + self, + ) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def create_bucket(self) -> Callable[ - [logging_config.CreateBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: + def create_bucket( + self, + ) -> Callable[ + [logging_config.CreateBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: raise NotImplementedError() @property - def update_bucket(self) -> Callable[ - [logging_config.UpdateBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: + def update_bucket( + self, + ) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: raise NotImplementedError() @property - def delete_bucket(self) -> Callable[ - [logging_config.DeleteBucketRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_bucket( + self, + ) -> Callable[ + [logging_config.DeleteBucketRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def undelete_bucket(self) -> Callable[ - [logging_config.UndeleteBucketRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def undelete_bucket( + self, + ) -> Callable[ + [logging_config.UndeleteBucketRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def list_views(self) -> Callable[ - [logging_config.ListViewsRequest], - Union[ - logging_config.ListViewsResponse, - Awaitable[logging_config.ListViewsResponse] - ]]: + def list_views( + self, + ) -> Callable[ + [logging_config.ListViewsRequest], + Union[ + logging_config.ListViewsResponse, + Awaitable[logging_config.ListViewsResponse], + ], + ]: raise NotImplementedError() @property - def get_view(self) -> Callable[ - [logging_config.GetViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: + def get_view( + self, + ) -> Callable[ + [logging_config.GetViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: raise NotImplementedError() @property - def create_view(self) -> Callable[ - [logging_config.CreateViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: + def create_view( + self, + ) -> Callable[ + [logging_config.CreateViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: raise NotImplementedError() @property - def update_view(self) -> Callable[ - [logging_config.UpdateViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: + def update_view( + self, + ) -> Callable[ + [logging_config.UpdateViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: raise NotImplementedError() @property - def delete_view(self) -> Callable[ - [logging_config.DeleteViewRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_view( + self, + ) -> Callable[ + [logging_config.DeleteViewRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def list_sinks(self) -> Callable[ - [logging_config.ListSinksRequest], - Union[ - logging_config.ListSinksResponse, - Awaitable[logging_config.ListSinksResponse] - ]]: + def list_sinks( + self, + ) -> Callable[ + [logging_config.ListSinksRequest], + Union[ + logging_config.ListSinksResponse, + Awaitable[logging_config.ListSinksResponse], + ], + ]: raise NotImplementedError() @property - def get_sink(self) -> Callable[ - [logging_config.GetSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: + def get_sink( + self, + ) -> Callable[ + [logging_config.GetSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: raise NotImplementedError() @property - def create_sink(self) -> Callable[ - [logging_config.CreateSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: + def create_sink( + self, + ) -> Callable[ + [logging_config.CreateSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: raise NotImplementedError() @property - def update_sink(self) -> Callable[ - [logging_config.UpdateSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: + def update_sink( + self, + ) -> Callable[ + [logging_config.UpdateSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: raise NotImplementedError() @property - def delete_sink(self) -> Callable[ - [logging_config.DeleteSinkRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_sink( + self, + ) -> Callable[ + [logging_config.DeleteSinkRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def create_link(self) -> Callable[ - [logging_config.CreateLinkRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_link( + self, + ) -> Callable[ + [logging_config.CreateLinkRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_link(self) -> Callable[ - [logging_config.DeleteLinkRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_link( + self, + ) -> Callable[ + [logging_config.DeleteLinkRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def list_links(self) -> Callable[ - [logging_config.ListLinksRequest], - Union[ - logging_config.ListLinksResponse, - Awaitable[logging_config.ListLinksResponse] - ]]: + def list_links( + self, + ) -> Callable[ + [logging_config.ListLinksRequest], + Union[ + logging_config.ListLinksResponse, + Awaitable[logging_config.ListLinksResponse], + ], + ]: raise NotImplementedError() @property - def get_link(self) -> Callable[ - [logging_config.GetLinkRequest], - Union[ - logging_config.Link, - Awaitable[logging_config.Link] - ]]: + def get_link( + self, + ) -> Callable[ + [logging_config.GetLinkRequest], + Union[logging_config.Link, Awaitable[logging_config.Link]], + ]: raise NotImplementedError() @property - def list_exclusions(self) -> Callable[ - [logging_config.ListExclusionsRequest], - Union[ - logging_config.ListExclusionsResponse, - Awaitable[logging_config.ListExclusionsResponse] - ]]: + def list_exclusions( + self, + ) -> Callable[ + [logging_config.ListExclusionsRequest], + Union[ + logging_config.ListExclusionsResponse, + Awaitable[logging_config.ListExclusionsResponse], + ], + ]: raise NotImplementedError() @property - def get_exclusion(self) -> Callable[ - [logging_config.GetExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: + def get_exclusion( + self, + ) -> Callable[ + [logging_config.GetExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: raise NotImplementedError() @property - def create_exclusion(self) -> Callable[ - [logging_config.CreateExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: + def create_exclusion( + self, + ) -> Callable[ + [logging_config.CreateExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: raise NotImplementedError() @property - def update_exclusion(self) -> Callable[ - [logging_config.UpdateExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: + def update_exclusion( + self, + ) -> Callable[ + [logging_config.UpdateExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: raise NotImplementedError() @property - def delete_exclusion(self) -> Callable[ - [logging_config.DeleteExclusionRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_exclusion( + self, + ) -> Callable[ + [logging_config.DeleteExclusionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def get_cmek_settings(self) -> Callable[ - [logging_config.GetCmekSettingsRequest], - Union[ - logging_config.CmekSettings, - Awaitable[logging_config.CmekSettings] - ]]: + def get_cmek_settings( + self, + ) -> Callable[ + [logging_config.GetCmekSettingsRequest], + Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], + ]: raise NotImplementedError() @property - def update_cmek_settings(self) -> Callable[ - [logging_config.UpdateCmekSettingsRequest], - Union[ - logging_config.CmekSettings, - Awaitable[logging_config.CmekSettings] - ]]: + def update_cmek_settings( + self, + ) -> Callable[ + [logging_config.UpdateCmekSettingsRequest], + Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], + ]: raise NotImplementedError() @property - def get_settings(self) -> Callable[ - [logging_config.GetSettingsRequest], - Union[ - logging_config.Settings, - Awaitable[logging_config.Settings] - ]]: + def get_settings( + self, + ) -> Callable[ + [logging_config.GetSettingsRequest], + Union[logging_config.Settings, Awaitable[logging_config.Settings]], + ]: raise NotImplementedError() @property - def update_settings(self) -> Callable[ - [logging_config.UpdateSettingsRequest], - Union[ - logging_config.Settings, - Awaitable[logging_config.Settings] - ]]: + def update_settings( + self, + ) -> Callable[ + [logging_config.UpdateSettingsRequest], + Union[logging_config.Settings, Awaitable[logging_config.Settings]], + ]: raise NotImplementedError() @property - def copy_log_entries(self) -> Callable[ - [logging_config.CopyLogEntriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def copy_log_entries( + self, + ) -> Callable[ + [logging_config.CopyLogEntriesRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property @@ -754,7 +794,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -781,6 +824,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'ConfigServiceV2Transport', -) +__all__ = ("ConfigServiceV2Transport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index 9c62d0b16de8..0fd4a31ba7f8 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -17,17 +17,19 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -from google.api_core import operations_v1 + from google.api_core.grpc_helpers import ( + ClientInterceptor, # type: ignore[attr-defined] + ) from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 + # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -35,21 +37,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import proto # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.logging_v2.types import logging_config +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import proto # type: ignore -from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from .base import ConfigServiceV2Transport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, ConfigServiceV2Transport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -59,7 +61,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -80,7 +84,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.logging.v2.ConfigServiceV2", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -91,7 +95,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -106,7 +114,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.logging.v2.ConfigServiceV2", "rpcName": client_call_details.method, "response": grpc_response, @@ -128,32 +136,35 @@ class ConfigServiceV2GrpcTransport(ConfigServiceV2Transport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'logging.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], - ] + def __init__( + self, + *, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -290,8 +301,17 @@ def __init__(self, *, channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None and otel_interceptor not in channel_interceptors + and not any( + getattr(i, "_is_otel_interceptor", None) is True + for i in channel_interceptors + ) ): channel_interceptors.append(otel_interceptor) @@ -300,22 +320,28 @@ def __init__(self, *, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) + self._grpc_channel = apply_interceptors( + self._grpc_channel, channel_interceptors + ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'logging.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -351,13 +377,12 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property @@ -377,9 +402,11 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def list_buckets(self) -> Callable[ - [logging_config.ListBucketsRequest], - logging_config.ListBucketsResponse]: + def list_buckets( + self, + ) -> Callable[ + [logging_config.ListBucketsRequest], logging_config.ListBucketsResponse + ]: r"""Return a callable for the list buckets method over gRPC. Lists log buckets. @@ -394,18 +421,18 @@ def list_buckets(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_buckets' not in self._stubs: - self._stubs['list_buckets'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListBuckets', + if "list_buckets" not in self._stubs: + self._stubs["list_buckets"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListBuckets", request_serializer=logging_config.ListBucketsRequest.serialize, response_deserializer=logging_config.ListBucketsResponse.deserialize, ) - return self._stubs['list_buckets'] + return self._stubs["list_buckets"] @property - def get_bucket(self) -> Callable[ - [logging_config.GetBucketRequest], - logging_config.LogBucket]: + def get_bucket( + self, + ) -> Callable[[logging_config.GetBucketRequest], logging_config.LogBucket]: r"""Return a callable for the get bucket method over gRPC. Gets a log bucket. @@ -420,18 +447,18 @@ def get_bucket(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_bucket' not in self._stubs: - self._stubs['get_bucket'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetBucket', + if "get_bucket" not in self._stubs: + self._stubs["get_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetBucket", request_serializer=logging_config.GetBucketRequest.serialize, response_deserializer=logging_config.LogBucket.deserialize, ) - return self._stubs['get_bucket'] + return self._stubs["get_bucket"] @property - def create_bucket_async(self) -> Callable[ - [logging_config.CreateBucketRequest], - operations_pb2.Operation]: + def create_bucket_async( + self, + ) -> Callable[[logging_config.CreateBucketRequest], operations_pb2.Operation]: r"""Return a callable for the create bucket async method over gRPC. Creates a log bucket asynchronously that can be used @@ -449,18 +476,18 @@ def create_bucket_async(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_bucket_async' not in self._stubs: - self._stubs['create_bucket_async'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateBucketAsync', + if "create_bucket_async" not in self._stubs: + self._stubs["create_bucket_async"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateBucketAsync", request_serializer=logging_config.CreateBucketRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_bucket_async'] + return self._stubs["create_bucket_async"] @property - def update_bucket_async(self) -> Callable[ - [logging_config.UpdateBucketRequest], - operations_pb2.Operation]: + def update_bucket_async( + self, + ) -> Callable[[logging_config.UpdateBucketRequest], operations_pb2.Operation]: r"""Return a callable for the update bucket async method over gRPC. Updates a log bucket asynchronously. @@ -481,18 +508,18 @@ def update_bucket_async(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_bucket_async' not in self._stubs: - self._stubs['update_bucket_async'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateBucketAsync', + if "update_bucket_async" not in self._stubs: + self._stubs["update_bucket_async"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateBucketAsync", request_serializer=logging_config.UpdateBucketRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_bucket_async'] + return self._stubs["update_bucket_async"] @property - def create_bucket(self) -> Callable[ - [logging_config.CreateBucketRequest], - logging_config.LogBucket]: + def create_bucket( + self, + ) -> Callable[[logging_config.CreateBucketRequest], logging_config.LogBucket]: r"""Return a callable for the create bucket method over gRPC. Creates a log bucket that can be used to store log @@ -509,18 +536,18 @@ def create_bucket(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_bucket' not in self._stubs: - self._stubs['create_bucket'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateBucket', + if "create_bucket" not in self._stubs: + self._stubs["create_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateBucket", request_serializer=logging_config.CreateBucketRequest.serialize, response_deserializer=logging_config.LogBucket.deserialize, ) - return self._stubs['create_bucket'] + return self._stubs["create_bucket"] @property - def update_bucket(self) -> Callable[ - [logging_config.UpdateBucketRequest], - logging_config.LogBucket]: + def update_bucket( + self, + ) -> Callable[[logging_config.UpdateBucketRequest], logging_config.LogBucket]: r"""Return a callable for the update bucket method over gRPC. Updates a log bucket. @@ -541,18 +568,18 @@ def update_bucket(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_bucket' not in self._stubs: - self._stubs['update_bucket'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateBucket', + if "update_bucket" not in self._stubs: + self._stubs["update_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateBucket", request_serializer=logging_config.UpdateBucketRequest.serialize, response_deserializer=logging_config.LogBucket.deserialize, ) - return self._stubs['update_bucket'] + return self._stubs["update_bucket"] @property - def delete_bucket(self) -> Callable[ - [logging_config.DeleteBucketRequest], - empty_pb2.Empty]: + def delete_bucket( + self, + ) -> Callable[[logging_config.DeleteBucketRequest], empty_pb2.Empty]: r"""Return a callable for the delete bucket method over gRPC. Deletes a log bucket. @@ -572,18 +599,18 @@ def delete_bucket(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_bucket' not in self._stubs: - self._stubs['delete_bucket'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteBucket', + if "delete_bucket" not in self._stubs: + self._stubs["delete_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteBucket", request_serializer=logging_config.DeleteBucketRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_bucket'] + return self._stubs["delete_bucket"] @property - def undelete_bucket(self) -> Callable[ - [logging_config.UndeleteBucketRequest], - empty_pb2.Empty]: + def undelete_bucket( + self, + ) -> Callable[[logging_config.UndeleteBucketRequest], empty_pb2.Empty]: r"""Return a callable for the undelete bucket method over gRPC. Undeletes a log bucket. A bucket that has been @@ -600,18 +627,18 @@ def undelete_bucket(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'undelete_bucket' not in self._stubs: - self._stubs['undelete_bucket'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UndeleteBucket', + if "undelete_bucket" not in self._stubs: + self._stubs["undelete_bucket"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UndeleteBucket", request_serializer=logging_config.UndeleteBucketRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['undelete_bucket'] + return self._stubs["undelete_bucket"] @property - def list_views(self) -> Callable[ - [logging_config.ListViewsRequest], - logging_config.ListViewsResponse]: + def list_views( + self, + ) -> Callable[[logging_config.ListViewsRequest], logging_config.ListViewsResponse]: r"""Return a callable for the list views method over gRPC. Lists views on a log bucket. @@ -626,18 +653,18 @@ def list_views(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_views' not in self._stubs: - self._stubs['list_views'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListViews', + if "list_views" not in self._stubs: + self._stubs["list_views"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListViews", request_serializer=logging_config.ListViewsRequest.serialize, response_deserializer=logging_config.ListViewsResponse.deserialize, ) - return self._stubs['list_views'] + return self._stubs["list_views"] @property - def get_view(self) -> Callable[ - [logging_config.GetViewRequest], - logging_config.LogView]: + def get_view( + self, + ) -> Callable[[logging_config.GetViewRequest], logging_config.LogView]: r"""Return a callable for the get view method over gRPC. Gets a view on a log bucket.. @@ -652,18 +679,18 @@ def get_view(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_view' not in self._stubs: - self._stubs['get_view'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetView', + if "get_view" not in self._stubs: + self._stubs["get_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetView", request_serializer=logging_config.GetViewRequest.serialize, response_deserializer=logging_config.LogView.deserialize, ) - return self._stubs['get_view'] + return self._stubs["get_view"] @property - def create_view(self) -> Callable[ - [logging_config.CreateViewRequest], - logging_config.LogView]: + def create_view( + self, + ) -> Callable[[logging_config.CreateViewRequest], logging_config.LogView]: r"""Return a callable for the create view method over gRPC. Creates a view over log entries in a log bucket. A @@ -679,18 +706,18 @@ def create_view(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_view' not in self._stubs: - self._stubs['create_view'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateView', + if "create_view" not in self._stubs: + self._stubs["create_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateView", request_serializer=logging_config.CreateViewRequest.serialize, response_deserializer=logging_config.LogView.deserialize, ) - return self._stubs['create_view'] + return self._stubs["create_view"] @property - def update_view(self) -> Callable[ - [logging_config.UpdateViewRequest], - logging_config.LogView]: + def update_view( + self, + ) -> Callable[[logging_config.UpdateViewRequest], logging_config.LogView]: r"""Return a callable for the update view method over gRPC. Updates a view on a log bucket. This method replaces the @@ -709,18 +736,18 @@ def update_view(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_view' not in self._stubs: - self._stubs['update_view'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateView', + if "update_view" not in self._stubs: + self._stubs["update_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateView", request_serializer=logging_config.UpdateViewRequest.serialize, response_deserializer=logging_config.LogView.deserialize, ) - return self._stubs['update_view'] + return self._stubs["update_view"] @property - def delete_view(self) -> Callable[ - [logging_config.DeleteViewRequest], - empty_pb2.Empty]: + def delete_view( + self, + ) -> Callable[[logging_config.DeleteViewRequest], empty_pb2.Empty]: r"""Return a callable for the delete view method over gRPC. Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is @@ -738,18 +765,18 @@ def delete_view(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_view' not in self._stubs: - self._stubs['delete_view'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteView', + if "delete_view" not in self._stubs: + self._stubs["delete_view"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteView", request_serializer=logging_config.DeleteViewRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_view'] + return self._stubs["delete_view"] @property - def list_sinks(self) -> Callable[ - [logging_config.ListSinksRequest], - logging_config.ListSinksResponse]: + def list_sinks( + self, + ) -> Callable[[logging_config.ListSinksRequest], logging_config.ListSinksResponse]: r"""Return a callable for the list sinks method over gRPC. Lists sinks. @@ -764,18 +791,18 @@ def list_sinks(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_sinks' not in self._stubs: - self._stubs['list_sinks'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListSinks', + if "list_sinks" not in self._stubs: + self._stubs["list_sinks"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListSinks", request_serializer=logging_config.ListSinksRequest.serialize, response_deserializer=logging_config.ListSinksResponse.deserialize, ) - return self._stubs['list_sinks'] + return self._stubs["list_sinks"] @property - def get_sink(self) -> Callable[ - [logging_config.GetSinkRequest], - logging_config.LogSink]: + def get_sink( + self, + ) -> Callable[[logging_config.GetSinkRequest], logging_config.LogSink]: r"""Return a callable for the get sink method over gRPC. Gets a sink. @@ -790,18 +817,18 @@ def get_sink(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_sink' not in self._stubs: - self._stubs['get_sink'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetSink', + if "get_sink" not in self._stubs: + self._stubs["get_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetSink", request_serializer=logging_config.GetSinkRequest.serialize, response_deserializer=logging_config.LogSink.deserialize, ) - return self._stubs['get_sink'] + return self._stubs["get_sink"] @property - def create_sink(self) -> Callable[ - [logging_config.CreateSinkRequest], - logging_config.LogSink]: + def create_sink( + self, + ) -> Callable[[logging_config.CreateSinkRequest], logging_config.LogSink]: r"""Return a callable for the create sink method over gRPC. Creates a sink that exports specified log entries to a @@ -820,18 +847,18 @@ def create_sink(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_sink' not in self._stubs: - self._stubs['create_sink'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateSink', + if "create_sink" not in self._stubs: + self._stubs["create_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateSink", request_serializer=logging_config.CreateSinkRequest.serialize, response_deserializer=logging_config.LogSink.deserialize, ) - return self._stubs['create_sink'] + return self._stubs["create_sink"] @property - def update_sink(self) -> Callable[ - [logging_config.UpdateSinkRequest], - logging_config.LogSink]: + def update_sink( + self, + ) -> Callable[[logging_config.UpdateSinkRequest], logging_config.LogSink]: r"""Return a callable for the update sink method over gRPC. Updates a sink. This method replaces the following fields in the @@ -851,18 +878,18 @@ def update_sink(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_sink' not in self._stubs: - self._stubs['update_sink'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateSink', + if "update_sink" not in self._stubs: + self._stubs["update_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateSink", request_serializer=logging_config.UpdateSinkRequest.serialize, response_deserializer=logging_config.LogSink.deserialize, ) - return self._stubs['update_sink'] + return self._stubs["update_sink"] @property - def delete_sink(self) -> Callable[ - [logging_config.DeleteSinkRequest], - empty_pb2.Empty]: + def delete_sink( + self, + ) -> Callable[[logging_config.DeleteSinkRequest], empty_pb2.Empty]: r"""Return a callable for the delete sink method over gRPC. Deletes a sink. If the sink has a unique ``writer_identity``, @@ -878,18 +905,18 @@ def delete_sink(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_sink' not in self._stubs: - self._stubs['delete_sink'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteSink', + if "delete_sink" not in self._stubs: + self._stubs["delete_sink"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteSink", request_serializer=logging_config.DeleteSinkRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_sink'] + return self._stubs["delete_sink"] @property - def create_link(self) -> Callable[ - [logging_config.CreateLinkRequest], - operations_pb2.Operation]: + def create_link( + self, + ) -> Callable[[logging_config.CreateLinkRequest], operations_pb2.Operation]: r"""Return a callable for the create link method over gRPC. Asynchronously creates a linked dataset in BigQuery @@ -907,18 +934,18 @@ def create_link(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_link' not in self._stubs: - self._stubs['create_link'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateLink', + if "create_link" not in self._stubs: + self._stubs["create_link"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateLink", request_serializer=logging_config.CreateLinkRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_link'] + return self._stubs["create_link"] @property - def delete_link(self) -> Callable[ - [logging_config.DeleteLinkRequest], - operations_pb2.Operation]: + def delete_link( + self, + ) -> Callable[[logging_config.DeleteLinkRequest], operations_pb2.Operation]: r"""Return a callable for the delete link method over gRPC. Deletes a link. This will also delete the @@ -934,18 +961,18 @@ def delete_link(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_link' not in self._stubs: - self._stubs['delete_link'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteLink', + if "delete_link" not in self._stubs: + self._stubs["delete_link"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteLink", request_serializer=logging_config.DeleteLinkRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_link'] + return self._stubs["delete_link"] @property - def list_links(self) -> Callable[ - [logging_config.ListLinksRequest], - logging_config.ListLinksResponse]: + def list_links( + self, + ) -> Callable[[logging_config.ListLinksRequest], logging_config.ListLinksResponse]: r"""Return a callable for the list links method over gRPC. Lists links. @@ -960,18 +987,18 @@ def list_links(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_links' not in self._stubs: - self._stubs['list_links'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListLinks', + if "list_links" not in self._stubs: + self._stubs["list_links"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListLinks", request_serializer=logging_config.ListLinksRequest.serialize, response_deserializer=logging_config.ListLinksResponse.deserialize, ) - return self._stubs['list_links'] + return self._stubs["list_links"] @property - def get_link(self) -> Callable[ - [logging_config.GetLinkRequest], - logging_config.Link]: + def get_link( + self, + ) -> Callable[[logging_config.GetLinkRequest], logging_config.Link]: r"""Return a callable for the get link method over gRPC. Gets a link. @@ -986,18 +1013,20 @@ def get_link(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_link' not in self._stubs: - self._stubs['get_link'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetLink', + if "get_link" not in self._stubs: + self._stubs["get_link"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetLink", request_serializer=logging_config.GetLinkRequest.serialize, response_deserializer=logging_config.Link.deserialize, ) - return self._stubs['get_link'] + return self._stubs["get_link"] @property - def list_exclusions(self) -> Callable[ - [logging_config.ListExclusionsRequest], - logging_config.ListExclusionsResponse]: + def list_exclusions( + self, + ) -> Callable[ + [logging_config.ListExclusionsRequest], logging_config.ListExclusionsResponse + ]: r"""Return a callable for the list exclusions method over gRPC. Lists all the exclusions on the \_Default sink in a parent @@ -1013,18 +1042,18 @@ def list_exclusions(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_exclusions' not in self._stubs: - self._stubs['list_exclusions'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListExclusions', + if "list_exclusions" not in self._stubs: + self._stubs["list_exclusions"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/ListExclusions", request_serializer=logging_config.ListExclusionsRequest.serialize, response_deserializer=logging_config.ListExclusionsResponse.deserialize, ) - return self._stubs['list_exclusions'] + return self._stubs["list_exclusions"] @property - def get_exclusion(self) -> Callable[ - [logging_config.GetExclusionRequest], - logging_config.LogExclusion]: + def get_exclusion( + self, + ) -> Callable[[logging_config.GetExclusionRequest], logging_config.LogExclusion]: r"""Return a callable for the get exclusion method over gRPC. Gets the description of an exclusion in the \_Default sink. @@ -1039,18 +1068,18 @@ def get_exclusion(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_exclusion' not in self._stubs: - self._stubs['get_exclusion'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetExclusion', + if "get_exclusion" not in self._stubs: + self._stubs["get_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetExclusion", request_serializer=logging_config.GetExclusionRequest.serialize, response_deserializer=logging_config.LogExclusion.deserialize, ) - return self._stubs['get_exclusion'] + return self._stubs["get_exclusion"] @property - def create_exclusion(self) -> Callable[ - [logging_config.CreateExclusionRequest], - logging_config.LogExclusion]: + def create_exclusion( + self, + ) -> Callable[[logging_config.CreateExclusionRequest], logging_config.LogExclusion]: r"""Return a callable for the create exclusion method over gRPC. Creates a new exclusion in the \_Default sink in a specified @@ -1067,18 +1096,18 @@ def create_exclusion(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_exclusion' not in self._stubs: - self._stubs['create_exclusion'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateExclusion', + if "create_exclusion" not in self._stubs: + self._stubs["create_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CreateExclusion", request_serializer=logging_config.CreateExclusionRequest.serialize, response_deserializer=logging_config.LogExclusion.deserialize, ) - return self._stubs['create_exclusion'] + return self._stubs["create_exclusion"] @property - def update_exclusion(self) -> Callable[ - [logging_config.UpdateExclusionRequest], - logging_config.LogExclusion]: + def update_exclusion( + self, + ) -> Callable[[logging_config.UpdateExclusionRequest], logging_config.LogExclusion]: r"""Return a callable for the update exclusion method over gRPC. Changes one or more properties of an existing exclusion in the @@ -1094,18 +1123,18 @@ def update_exclusion(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_exclusion' not in self._stubs: - self._stubs['update_exclusion'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateExclusion', + if "update_exclusion" not in self._stubs: + self._stubs["update_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateExclusion", request_serializer=logging_config.UpdateExclusionRequest.serialize, response_deserializer=logging_config.LogExclusion.deserialize, ) - return self._stubs['update_exclusion'] + return self._stubs["update_exclusion"] @property - def delete_exclusion(self) -> Callable[ - [logging_config.DeleteExclusionRequest], - empty_pb2.Empty]: + def delete_exclusion( + self, + ) -> Callable[[logging_config.DeleteExclusionRequest], empty_pb2.Empty]: r"""Return a callable for the delete exclusion method over gRPC. Deletes an exclusion in the \_Default sink. @@ -1120,18 +1149,18 @@ def delete_exclusion(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_exclusion' not in self._stubs: - self._stubs['delete_exclusion'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteExclusion', + if "delete_exclusion" not in self._stubs: + self._stubs["delete_exclusion"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/DeleteExclusion", request_serializer=logging_config.DeleteExclusionRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_exclusion'] + return self._stubs["delete_exclusion"] @property - def get_cmek_settings(self) -> Callable[ - [logging_config.GetCmekSettingsRequest], - logging_config.CmekSettings]: + def get_cmek_settings( + self, + ) -> Callable[[logging_config.GetCmekSettingsRequest], logging_config.CmekSettings]: r"""Return a callable for the get cmek settings method over gRPC. Gets the Logging CMEK settings for the given resource. @@ -1155,18 +1184,20 @@ def get_cmek_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_cmek_settings' not in self._stubs: - self._stubs['get_cmek_settings'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetCmekSettings', + if "get_cmek_settings" not in self._stubs: + self._stubs["get_cmek_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetCmekSettings", request_serializer=logging_config.GetCmekSettingsRequest.serialize, response_deserializer=logging_config.CmekSettings.deserialize, ) - return self._stubs['get_cmek_settings'] + return self._stubs["get_cmek_settings"] @property - def update_cmek_settings(self) -> Callable[ - [logging_config.UpdateCmekSettingsRequest], - logging_config.CmekSettings]: + def update_cmek_settings( + self, + ) -> Callable[ + [logging_config.UpdateCmekSettingsRequest], logging_config.CmekSettings + ]: r"""Return a callable for the update cmek settings method over gRPC. Updates the Log Router CMEK settings for the given resource. @@ -1195,18 +1226,18 @@ def update_cmek_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_cmek_settings' not in self._stubs: - self._stubs['update_cmek_settings'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateCmekSettings', + if "update_cmek_settings" not in self._stubs: + self._stubs["update_cmek_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateCmekSettings", request_serializer=logging_config.UpdateCmekSettingsRequest.serialize, response_deserializer=logging_config.CmekSettings.deserialize, ) - return self._stubs['update_cmek_settings'] + return self._stubs["update_cmek_settings"] @property - def get_settings(self) -> Callable[ - [logging_config.GetSettingsRequest], - logging_config.Settings]: + def get_settings( + self, + ) -> Callable[[logging_config.GetSettingsRequest], logging_config.Settings]: r"""Return a callable for the get settings method over gRPC. Gets the Log Router settings for the given resource. @@ -1231,18 +1262,18 @@ def get_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_settings' not in self._stubs: - self._stubs['get_settings'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetSettings', + if "get_settings" not in self._stubs: + self._stubs["get_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/GetSettings", request_serializer=logging_config.GetSettingsRequest.serialize, response_deserializer=logging_config.Settings.deserialize, ) - return self._stubs['get_settings'] + return self._stubs["get_settings"] @property - def update_settings(self) -> Callable[ - [logging_config.UpdateSettingsRequest], - logging_config.Settings]: + def update_settings( + self, + ) -> Callable[[logging_config.UpdateSettingsRequest], logging_config.Settings]: r"""Return a callable for the update settings method over gRPC. Updates the Log Router settings for the given resource. @@ -1274,18 +1305,18 @@ def update_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_settings' not in self._stubs: - self._stubs['update_settings'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateSettings', + if "update_settings" not in self._stubs: + self._stubs["update_settings"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/UpdateSettings", request_serializer=logging_config.UpdateSettingsRequest.serialize, response_deserializer=logging_config.Settings.deserialize, ) - return self._stubs['update_settings'] + return self._stubs["update_settings"] @property - def copy_log_entries(self) -> Callable[ - [logging_config.CopyLogEntriesRequest], - operations_pb2.Operation]: + def copy_log_entries( + self, + ) -> Callable[[logging_config.CopyLogEntriesRequest], operations_pb2.Operation]: r"""Return a callable for the copy log entries method over gRPC. Copies a set of log entries from a log bucket to a @@ -1301,13 +1332,13 @@ def copy_log_entries(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'copy_log_entries' not in self._stubs: - self._stubs['copy_log_entries'] = self._logged_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CopyLogEntries', + if "copy_log_entries" not in self._stubs: + self._stubs["copy_log_entries"] = self._logged_channel.unary_unary( + "/google.logging.v2.ConfigServiceV2/CopyLogEntries", request_serializer=logging_config.CopyLogEntriesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['copy_log_entries'] + return self._stubs["copy_log_entries"] def close(self): self._logged_channel.close() @@ -1316,8 +1347,7 @@ def close(self): def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1334,8 +1364,7 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1351,9 +1380,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1371,6 +1401,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'ConfigServiceV2GrpcTransport', -) +__all__ = ("ConfigServiceV2GrpcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py index 50469def8e08..40c01d7305c8 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -13,29 +13,48 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import inspect import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Iterable, + Iterator, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.logging_v2 import gapic_version as package_version - +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.logging_v2 import gapic_version as package_version +from google.cloud.logging_v2._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -44,6 +63,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -57,12 +77,12 @@ _LOGGER = std_logging.getLogger(__name__) -from google.cloud.logging_v2.services.logging_service_v2 import pagers -from google.cloud.logging_v2.types import log_entry -from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore -from .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO +from google.cloud.logging_v2.services.logging_service_v2 import pagers +from google.cloud.logging_v2.types import log_entry, logging +from google.longrunning import operations_pb2 # type: ignore + +from .transports.base import DEFAULT_CLIENT_INFO, LoggingServiceV2Transport from .transports.grpc import LoggingServiceV2GrpcTransport from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport @@ -74,13 +94,15 @@ class LoggingServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[LoggingServiceV2Transport]] _transport_registry["grpc"] = LoggingServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = LoggingServiceV2GrpcAsyncIOTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[LoggingServiceV2Transport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[LoggingServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -140,8 +162,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LoggingServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -158,73 +179,103 @@ def transport(self) -> LoggingServiceV2Transport: return self._transport @staticmethod - def log_path(project: str,log: str,) -> str: + def log_path( + project: str, + log: str, + ) -> str: """Returns a fully-qualified log string.""" - return "projects/{project}/logs/{log}".format(project=project, log=log, ) + return "projects/{project}/logs/{log}".format( + project=project, + log=log, + ) @staticmethod - def parse_log_path(path: str) -> Dict[str,str]: + def parse_log_path(path: str) -> Dict[str, str]: """Parses a log path into its component segments.""" m = re.match(r"^projects/(?P.+?)/logs/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -256,14 +307,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -276,8 +331,10 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -316,15 +373,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -357,12 +417,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the logging service v2 client. Args: @@ -417,13 +483,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = LoggingServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = LoggingServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE, + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -435,7 +511,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -444,35 +522,41 @@ def __init__(self, *, if transport_provided: # transport is a LoggingServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." + "When providing a transport instance, provide its scopes directly." ) self._transport = cast(LoggingServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE, - default_mtls_endpoint=LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" or ( - self._use_mtls_endpoint == "auto" and self._client_cert_source - ), - )) + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE, + default_mtls_endpoint=LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[LoggingServiceV2Transport], Callable[..., LoggingServiceV2Transport]] = ( + transport_init: Union[ + Type[LoggingServiceV2Transport], + Callable[..., LoggingServiceV2Transport], + ] = ( LoggingServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., LoggingServiceV2Transport], transport) @@ -501,33 +585,46 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"client_options": client_options} if client_options else {}), + **( + {"client_options": client_options} + if client_options is not None + else {} + ), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.LoggingServiceV2Client`.", - extra = { + extra={ "serviceName": "google.logging.v2.LoggingServiceV2", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.logging.v2.LoggingServiceV2", "credentialsType": None, - } + }, ) - def delete_log(self, - request: Optional[Union[logging.DeleteLogRequest, dict]] = None, - *, - log_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_log( + self, + request: Optional[Union[logging.DeleteLogRequest, dict]] = None, + *, + log_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes all the log entries in a log for the \_Default Log Bucket. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be @@ -590,10 +687,14 @@ def sample_delete_log(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -611,9 +712,7 @@ def sample_delete_log(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("log_name", request.log_name), - )), + gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)), ) # Validate the universe domain. @@ -627,17 +726,18 @@ def sample_delete_log(): metadata=metadata, ) - def write_log_entries(self, - request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, - *, - log_name: Optional[str] = None, - resource: Optional[monitored_resource_pb2.MonitoredResource] = None, - labels: Optional[MutableMapping[str, str]] = None, - entries: Optional[MutableSequence[log_entry.LogEntry]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging.WriteLogEntriesResponse: + def write_log_entries( + self, + request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, + *, + log_name: Optional[str] = None, + resource: Optional[monitored_resource_pb2.MonitoredResource] = None, + labels: Optional[MutableMapping[str, str]] = None, + entries: Optional[MutableSequence[log_entry.LogEntry]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging.WriteLogEntriesResponse: r"""Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent @@ -780,10 +880,14 @@ def sample_write_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name, resource, labels, entries] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -818,16 +922,17 @@ def sample_write_log_entries(): # Done; return the response. return response - def list_log_entries(self, - request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, - *, - resource_names: Optional[MutableSequence[str]] = None, - filter: Optional[str] = None, - order_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogEntriesPager: + def list_log_entries( + self, + request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, + *, + resource_names: Optional[MutableSequence[str]] = None, + filter: Optional[str] = None, + order_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogEntriesPager: r"""Lists log entries. Use this method to retrieve log entries that originated from a project/folder/organization/billing account. For ways to export log entries, see `Exporting @@ -930,10 +1035,14 @@ def sample_list_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [resource_names, filter, order_by] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -977,13 +1086,16 @@ def sample_list_log_entries(): # Done; return the response. return response - def list_monitored_resource_descriptors(self, - request: Optional[Union[logging.ListMonitoredResourceDescriptorsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMonitoredResourceDescriptorsPager: + def list_monitored_resource_descriptors( + self, + request: Optional[ + Union[logging.ListMonitoredResourceDescriptorsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMonitoredResourceDescriptorsPager: r"""Lists the descriptors for monitored resource types used by Logging. @@ -1042,7 +1154,9 @@ def sample_list_monitored_resource_descriptors(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_monitored_resource_descriptors] + rpc = self._transport._wrapped_methods[ + self._transport.list_monitored_resource_descriptors + ] # Validate the universe domain. self._validate_universe_domain() @@ -1069,14 +1183,15 @@ def sample_list_monitored_resource_descriptors(): # Done; return the response. return response - def list_logs(self, - request: Optional[Union[logging.ListLogsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogsPager: + def list_logs( + self, + request: Optional[Union[logging.ListLogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogsPager: r"""Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have entries are listed. @@ -1143,10 +1258,14 @@ def sample_list_logs(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1164,9 +1283,7 @@ def sample_list_logs(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1194,13 +1311,14 @@ def sample_list_logs(): # Done; return the response. return response - def tail_log_entries(self, - requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Iterable[logging.TailLogEntriesResponse]: + def tail_log_entries( + self, + requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[logging.TailLogEntriesResponse]: r"""Streaming read of log entries as they are ingested. Until the stream is terminated, it will continue reading logs. @@ -1331,8 +1449,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1341,7 +1458,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1391,8 +1512,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1401,7 +1521,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1454,25 +1578,24 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - - - - + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "LoggingServiceV2Client", -) +__all__ = ("LoggingServiceV2Client",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index 133f00107ae2..82763d3d459b 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -17,52 +17,60 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.logging_v2 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.cloud.logging_v2 import gapic_version as package_version from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +# Check once at module load time whether google-api-core's wrap_method supports +# OpenTelemetry tracing arguments (client_options, method_name, is_streaming, kind) +# to avoid recurring inspect.signature latency during client instantiation. +_WRAP_METHOD_SUPPORTS_TRACING = ( + "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters +) + class LoggingServiceV2Transport(abc.ABC): """Abstract transport class for LoggingServiceV2.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", + "https://www.googleapis.com/auth/logging.write", ) - DEFAULT_HOST: str = 'logging.googleapis.com' + DEFAULT_HOST: str = "logging.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -104,38 +112,47 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._client_options = client_options - # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments - # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility - # with older versions of google-api-core. - self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrap_with_tracing = _WRAP_METHOD_SUPPORTS_TRACING self._wrapped_methods: Dict[Callable, Callable] = {} @@ -148,15 +165,24 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["client_options"] = self._client_options try: kwargs["kind"] = self.kind - # Base transport raises NotImplementedError for abstract kind property. - # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + # The abstract BaseTransport class raises NotImplementedError for the kind property. + # Concrete transport subclasses (gRPC, REST) override kind, so this exception handler + # is unreachable during normal execution. Excluded from coverage check. except NotImplementedError: # pragma: NO COVER pass return gapic_v1.method.wrap_method(func, *args, **kwargs) - # Remove tracing-specific arguments if older google-api-core is installed - for k in ["client_options", "method_name", "is_streaming", "kind"]: - kwargs.pop(k, None) - return gapic_v1.method.wrap_method(func, *args, **kwargs) + # The fallback below strips tracing-specific arguments when an older version + # of google-api-core is installed (which does not accept client_options, etc.). + # Excluded from coverage because our CI and testing environments always install + # a modern version of google-api-core that supports tracing. + for k in [ + "client_options", + "method_name", + "is_streaming", + "kind", + ]: # pragma: NO COVER + kwargs.pop(k, None) # pragma: NO COVER + return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -279,69 +305,77 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def delete_log(self) -> Callable[ - [logging.DeleteLogRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_log( + self, + ) -> Callable[ + [logging.DeleteLogRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: raise NotImplementedError() @property - def write_log_entries(self) -> Callable[ - [logging.WriteLogEntriesRequest], - Union[ - logging.WriteLogEntriesResponse, - Awaitable[logging.WriteLogEntriesResponse] - ]]: + def write_log_entries( + self, + ) -> Callable[ + [logging.WriteLogEntriesRequest], + Union[ + logging.WriteLogEntriesResponse, Awaitable[logging.WriteLogEntriesResponse] + ], + ]: raise NotImplementedError() @property - def list_log_entries(self) -> Callable[ - [logging.ListLogEntriesRequest], - Union[ - logging.ListLogEntriesResponse, - Awaitable[logging.ListLogEntriesResponse] - ]]: + def list_log_entries( + self, + ) -> Callable[ + [logging.ListLogEntriesRequest], + Union[ + logging.ListLogEntriesResponse, Awaitable[logging.ListLogEntriesResponse] + ], + ]: raise NotImplementedError() @property - def list_monitored_resource_descriptors(self) -> Callable[ - [logging.ListMonitoredResourceDescriptorsRequest], - Union[ - logging.ListMonitoredResourceDescriptorsResponse, - Awaitable[logging.ListMonitoredResourceDescriptorsResponse] - ]]: + def list_monitored_resource_descriptors( + self, + ) -> Callable[ + [logging.ListMonitoredResourceDescriptorsRequest], + Union[ + logging.ListMonitoredResourceDescriptorsResponse, + Awaitable[logging.ListMonitoredResourceDescriptorsResponse], + ], + ]: raise NotImplementedError() @property - def list_logs(self) -> Callable[ - [logging.ListLogsRequest], - Union[ - logging.ListLogsResponse, - Awaitable[logging.ListLogsResponse] - ]]: + def list_logs( + self, + ) -> Callable[ + [logging.ListLogsRequest], + Union[logging.ListLogsResponse, Awaitable[logging.ListLogsResponse]], + ]: raise NotImplementedError() @property - def tail_log_entries(self) -> Callable[ - [logging.TailLogEntriesRequest], - Union[ - logging.TailLogEntriesResponse, - Awaitable[logging.TailLogEntriesResponse] - ]]: + def tail_log_entries( + self, + ) -> Callable[ + [logging.TailLogEntriesRequest], + Union[ + logging.TailLogEntriesResponse, Awaitable[logging.TailLogEntriesResponse] + ], + ]: raise NotImplementedError() @property @@ -349,7 +383,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -376,6 +413,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'LoggingServiceV2Transport', -) +__all__ = ("LoggingServiceV2Transport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index 5df5fb7d48e1..bd4c44c84030 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -17,16 +17,19 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] + from google.api_core.grpc_helpers import ( + ClientInterceptor, # type: ignore[attr-defined] + ) from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 + # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -34,21 +37,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import proto # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.logging_v2.types import logging +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import proto # type: ignore -from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from .base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, LoggingServiceV2Transport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -58,7 +61,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -79,7 +84,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.logging.v2.LoggingServiceV2", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -90,7 +95,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -105,7 +114,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.logging.v2.LoggingServiceV2", "rpcName": client_call_details.method, "response": grpc_response, @@ -127,32 +136,35 @@ class LoggingServiceV2GrpcTransport(LoggingServiceV2Transport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'logging.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], - ] + def __init__( + self, + *, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -288,8 +300,17 @@ def __init__(self, *, channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None and otel_interceptor not in channel_interceptors + and not any( + getattr(i, "_is_otel_interceptor", None) is True + for i in channel_interceptors + ) ): channel_interceptors.append(otel_interceptor) @@ -298,22 +319,28 @@ def __init__(self, *, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) + self._grpc_channel = apply_interceptors( + self._grpc_channel, channel_interceptors + ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'logging.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -349,19 +376,16 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property - def delete_log(self) -> Callable[ - [logging.DeleteLogRequest], - empty_pb2.Empty]: + def delete_log(self) -> Callable[[logging.DeleteLogRequest], empty_pb2.Empty]: r"""Return a callable for the delete log method over gRPC. Deletes all the log entries in a log for the \_Default Log @@ -380,18 +404,18 @@ def delete_log(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_log' not in self._stubs: - self._stubs['delete_log'] = self._logged_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/DeleteLog', + if "delete_log" not in self._stubs: + self._stubs["delete_log"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/DeleteLog", request_serializer=logging.DeleteLogRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_log'] + return self._stubs["delete_log"] @property - def write_log_entries(self) -> Callable[ - [logging.WriteLogEntriesRequest], - logging.WriteLogEntriesResponse]: + def write_log_entries( + self, + ) -> Callable[[logging.WriteLogEntriesRequest], logging.WriteLogEntriesResponse]: r"""Return a callable for the write log entries method over gRPC. Writes log entries to Logging. This API method is the @@ -412,18 +436,18 @@ def write_log_entries(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'write_log_entries' not in self._stubs: - self._stubs['write_log_entries'] = self._logged_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/WriteLogEntries', + if "write_log_entries" not in self._stubs: + self._stubs["write_log_entries"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/WriteLogEntries", request_serializer=logging.WriteLogEntriesRequest.serialize, response_deserializer=logging.WriteLogEntriesResponse.deserialize, ) - return self._stubs['write_log_entries'] + return self._stubs["write_log_entries"] @property - def list_log_entries(self) -> Callable[ - [logging.ListLogEntriesRequest], - logging.ListLogEntriesResponse]: + def list_log_entries( + self, + ) -> Callable[[logging.ListLogEntriesRequest], logging.ListLogEntriesResponse]: r"""Return a callable for the list log entries method over gRPC. Lists log entries. Use this method to retrieve log entries that @@ -441,18 +465,21 @@ def list_log_entries(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_log_entries' not in self._stubs: - self._stubs['list_log_entries'] = self._logged_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/ListLogEntries', + if "list_log_entries" not in self._stubs: + self._stubs["list_log_entries"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/ListLogEntries", request_serializer=logging.ListLogEntriesRequest.serialize, response_deserializer=logging.ListLogEntriesResponse.deserialize, ) - return self._stubs['list_log_entries'] + return self._stubs["list_log_entries"] @property - def list_monitored_resource_descriptors(self) -> Callable[ - [logging.ListMonitoredResourceDescriptorsRequest], - logging.ListMonitoredResourceDescriptorsResponse]: + def list_monitored_resource_descriptors( + self, + ) -> Callable[ + [logging.ListMonitoredResourceDescriptorsRequest], + logging.ListMonitoredResourceDescriptorsResponse, + ]: r"""Return a callable for the list monitored resource descriptors method over gRPC. @@ -469,18 +496,20 @@ def list_monitored_resource_descriptors(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_monitored_resource_descriptors' not in self._stubs: - self._stubs['list_monitored_resource_descriptors'] = self._logged_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors', - request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize, - response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize, + if "list_monitored_resource_descriptors" not in self._stubs: + self._stubs["list_monitored_resource_descriptors"] = ( + self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors", + request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize, + response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize, + ) ) - return self._stubs['list_monitored_resource_descriptors'] + return self._stubs["list_monitored_resource_descriptors"] @property - def list_logs(self) -> Callable[ - [logging.ListLogsRequest], - logging.ListLogsResponse]: + def list_logs( + self, + ) -> Callable[[logging.ListLogsRequest], logging.ListLogsResponse]: r"""Return a callable for the list logs method over gRPC. Lists the logs in projects, organizations, folders, @@ -497,18 +526,18 @@ def list_logs(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_logs' not in self._stubs: - self._stubs['list_logs'] = self._logged_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/ListLogs', + if "list_logs" not in self._stubs: + self._stubs["list_logs"] = self._logged_channel.unary_unary( + "/google.logging.v2.LoggingServiceV2/ListLogs", request_serializer=logging.ListLogsRequest.serialize, response_deserializer=logging.ListLogsResponse.deserialize, ) - return self._stubs['list_logs'] + return self._stubs["list_logs"] @property - def tail_log_entries(self) -> Callable[ - [logging.TailLogEntriesRequest], - logging.TailLogEntriesResponse]: + def tail_log_entries( + self, + ) -> Callable[[logging.TailLogEntriesRequest], logging.TailLogEntriesResponse]: r"""Return a callable for the tail log entries method over gRPC. Streaming read of log entries as they are ingested. @@ -525,13 +554,13 @@ def tail_log_entries(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'tail_log_entries' not in self._stubs: - self._stubs['tail_log_entries'] = self._logged_channel.stream_stream( - '/google.logging.v2.LoggingServiceV2/TailLogEntries', + if "tail_log_entries" not in self._stubs: + self._stubs["tail_log_entries"] = self._logged_channel.stream_stream( + "/google.logging.v2.LoggingServiceV2/TailLogEntries", request_serializer=logging.TailLogEntriesRequest.serialize, response_deserializer=logging.TailLogEntriesResponse.deserialize, ) - return self._stubs['tail_log_entries'] + return self._stubs["tail_log_entries"] def close(self): self._logged_channel.close() @@ -540,8 +569,7 @@ def close(self): def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -558,8 +586,7 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -575,9 +602,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -595,6 +623,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'LoggingServiceV2GrpcTransport', -) +__all__ = ("LoggingServiceV2GrpcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py index 754b29849c6b..d7c96031b7f4 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -13,29 +13,46 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import inspect import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.logging_v2 import gapic_version as package_version - +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.logging_v2 import gapic_version as package_version +from google.cloud.logging_v2._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -44,6 +61,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -57,13 +75,14 @@ _LOGGER = std_logging.getLogger(__name__) -from google.cloud.logging_v2.services.metrics_service_v2 import pagers -from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore import google.api.distribution_pb2 as distribution_pb2 # type: ignore import google.api.metric_pb2 as metric_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO +from google.cloud.logging_v2.services.metrics_service_v2 import pagers +from google.cloud.logging_v2.types import logging_metrics +from google.longrunning import operations_pb2 # type: ignore + +from .transports.base import DEFAULT_CLIENT_INFO, MetricsServiceV2Transport from .transports.grpc import MetricsServiceV2GrpcTransport from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport @@ -75,13 +94,15 @@ class BaseMetricsServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[MetricsServiceV2Transport]] _transport_registry["grpc"] = MetricsServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[MetricsServiceV2Transport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[MetricsServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -141,8 +162,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BaseMetricsServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -159,73 +179,103 @@ def transport(self) -> MetricsServiceV2Transport: return self._transport @staticmethod - def log_metric_path(project: str,metric: str,) -> str: + def log_metric_path( + project: str, + metric: str, + ) -> str: """Returns a fully-qualified log_metric string.""" - return "projects/{project}/metrics/{metric}".format(project=project, metric=metric, ) + return "projects/{project}/metrics/{metric}".format( + project=project, + metric=metric, + ) @staticmethod - def parse_log_metric_path(path: str) -> Dict[str,str]: + def parse_log_metric_path(path: str) -> Dict[str, str]: """Parses a log_metric path into its component segments.""" m = re.match(r"^projects/(?P.+?)/metrics/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -257,14 +307,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -277,8 +331,10 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -317,15 +373,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -358,12 +417,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the base metrics service v2 client. Args: @@ -418,13 +483,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = BaseMetricsServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=BaseMetricsServiceV2Client._DEFAULT_UNIVERSE) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = BaseMetricsServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=BaseMetricsServiceV2Client._DEFAULT_UNIVERSE, + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -436,7 +511,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -445,35 +522,41 @@ def __init__(self, *, if transport_provided: # transport is a MetricsServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." + "When providing a transport instance, provide its scopes directly." ) self._transport = cast(MetricsServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=BaseMetricsServiceV2Client._DEFAULT_UNIVERSE, - default_mtls_endpoint=BaseMetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=BaseMetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" or ( - self._use_mtls_endpoint == "auto" and self._client_cert_source - ), - )) + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=BaseMetricsServiceV2Client._DEFAULT_UNIVERSE, + default_mtls_endpoint=BaseMetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=BaseMetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[MetricsServiceV2Transport], Callable[..., MetricsServiceV2Transport]] = ( + transport_init: Union[ + Type[MetricsServiceV2Transport], + Callable[..., MetricsServiceV2Transport], + ] = ( BaseMetricsServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., MetricsServiceV2Transport], transport) @@ -502,33 +585,46 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"client_options": client_options} if client_options else {}), + **( + {"client_options": client_options} + if client_options is not None + else {} + ), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.BaseMetricsServiceV2Client`.", - extra = { + extra={ "serviceName": "google.logging.v2.MetricsServiceV2", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.logging.v2.MetricsServiceV2", "credentialsType": None, - } + }, ) - def _list_log_metrics(self, - request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogMetricsPager: + def _list_log_metrics( + self, + request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogMetricsPager: r"""Lists logs-based metrics. .. code-block:: python @@ -593,10 +689,14 @@ def sample_list_log_metrics(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -614,9 +714,7 @@ def sample_list_log_metrics(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -644,14 +742,15 @@ def sample_list_log_metrics(): # Done; return the response. return response - def _get_log_metric(self, - request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def _get_log_metric( + self, + request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Gets a logs-based metric. .. code-block:: python @@ -721,10 +820,14 @@ def sample_get_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -742,9 +845,9 @@ def sample_get_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -761,15 +864,16 @@ def sample_get_log_metric(): # Done; return the response. return response - def _create_log_metric(self, - request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, - *, - parent: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def _create_log_metric( + self, + request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates a logs-based metric. .. code-block:: python @@ -855,10 +959,14 @@ def sample_create_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, metric] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -878,9 +986,7 @@ def sample_create_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -897,15 +1003,16 @@ def sample_create_log_metric(): # Done; return the response. return response - def _update_log_metric(self, - request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def _update_log_metric( + self, + request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates or updates a logs-based metric. .. code-block:: python @@ -990,10 +1097,14 @@ def sample_update_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name, metric] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1013,9 +1124,9 @@ def sample_update_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -1032,14 +1143,15 @@ def sample_update_log_metric(): # Done; return the response. return response - def _delete_log_metric(self, - request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def _delete_log_metric( + self, + request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a logs-based metric. .. code-block:: python @@ -1090,10 +1202,14 @@ def sample_delete_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1111,9 +1227,9 @@ def sample_delete_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -1182,8 +1298,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1192,7 +1307,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1242,8 +1361,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1252,7 +1370,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1305,25 +1427,24 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - - - - + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "BaseMetricsServiceV2Client", -) +__all__ = ("BaseMetricsServiceV2Client",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index 292ad249a3f6..5e8c203f0a9f 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -17,52 +17,60 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.logging_v2 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - +from google.cloud.logging_v2 import gapic_version as package_version from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +# Check once at module load time whether google-api-core's wrap_method supports +# OpenTelemetry tracing arguments (client_options, method_name, is_streaming, kind) +# to avoid recurring inspect.signature latency during client instantiation. +_WRAP_METHOD_SUPPORTS_TRACING = ( + "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters +) + class MetricsServiceV2Transport(abc.ABC): """Abstract transport class for MetricsServiceV2.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", + "https://www.googleapis.com/auth/logging.write", ) - DEFAULT_HOST: str = 'logging.googleapis.com' + DEFAULT_HOST: str = "logging.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -104,38 +112,47 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._client_options = client_options - # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments - # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility - # with older versions of google-api-core. - self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrap_with_tracing = _WRAP_METHOD_SUPPORTS_TRACING self._wrapped_methods: Dict[Callable, Callable] = {} @@ -148,15 +165,24 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["client_options"] = self._client_options try: kwargs["kind"] = self.kind - # Base transport raises NotImplementedError for abstract kind property. - # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + # The abstract BaseTransport class raises NotImplementedError for the kind property. + # Concrete transport subclasses (gRPC, REST) override kind, so this exception handler + # is unreachable during normal execution. Excluded from coverage check. except NotImplementedError: # pragma: NO COVER pass return gapic_v1.method.wrap_method(func, *args, **kwargs) - # Remove tracing-specific arguments if older google-api-core is installed - for k in ["client_options", "method_name", "is_streaming", "kind"]: - kwargs.pop(k, None) - return gapic_v1.method.wrap_method(func, *args, **kwargs) + # The fallback below strips tracing-specific arguments when an older version + # of google-api-core is installed (which does not accept client_options, etc.). + # Excluded from coverage because our CI and testing environments always install + # a modern version of google-api-core that supports tracing. + for k in [ + "client_options", + "method_name", + "is_streaming", + "kind", + ]: # pragma: NO COVER + kwargs.pop(k, None) # pragma: NO COVER + return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -250,60 +276,63 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def list_log_metrics(self) -> Callable[ - [logging_metrics.ListLogMetricsRequest], - Union[ - logging_metrics.ListLogMetricsResponse, - Awaitable[logging_metrics.ListLogMetricsResponse] - ]]: + def list_log_metrics( + self, + ) -> Callable[ + [logging_metrics.ListLogMetricsRequest], + Union[ + logging_metrics.ListLogMetricsResponse, + Awaitable[logging_metrics.ListLogMetricsResponse], + ], + ]: raise NotImplementedError() @property - def get_log_metric(self) -> Callable[ - [logging_metrics.GetLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: + def get_log_metric( + self, + ) -> Callable[ + [logging_metrics.GetLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: raise NotImplementedError() @property - def create_log_metric(self) -> Callable[ - [logging_metrics.CreateLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: + def create_log_metric( + self, + ) -> Callable[ + [logging_metrics.CreateLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: raise NotImplementedError() @property - def update_log_metric(self) -> Callable[ - [logging_metrics.UpdateLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: + def update_log_metric( + self, + ) -> Callable[ + [logging_metrics.UpdateLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: raise NotImplementedError() @property - def delete_log_metric(self) -> Callable[ - [logging_metrics.DeleteLogMetricRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_log_metric( + self, + ) -> Callable[ + [logging_metrics.DeleteLogMetricRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property @@ -311,7 +340,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -338,6 +370,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'MetricsServiceV2Transport', -) +__all__ = ("MetricsServiceV2Transport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index 358403b0f13a..8b3f065959fb 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -17,16 +17,19 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] + from google.api_core.grpc_helpers import ( + ClientInterceptor, # type: ignore[attr-defined] + ) from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 + # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -34,21 +37,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import proto # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.logging_v2.types import logging_metrics +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import proto # type: ignore -from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from .base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, MetricsServiceV2Transport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -58,7 +61,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -79,7 +84,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.logging.v2.MetricsServiceV2", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -90,7 +95,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -105,7 +114,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.logging.v2.MetricsServiceV2", "rpcName": client_call_details.method, "response": grpc_response, @@ -127,32 +136,35 @@ class MetricsServiceV2GrpcTransport(MetricsServiceV2Transport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'logging.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], - ] + def __init__( + self, + *, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -288,8 +300,17 @@ def __init__(self, *, channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None and otel_interceptor not in channel_interceptors + and not any( + getattr(i, "_is_otel_interceptor", None) is True + for i in channel_interceptors + ) ): channel_interceptors.append(otel_interceptor) @@ -298,22 +319,28 @@ def __init__(self, *, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) + self._grpc_channel = apply_interceptors( + self._grpc_channel, channel_interceptors + ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'logging.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "logging.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -349,19 +376,20 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property - def list_log_metrics(self) -> Callable[ - [logging_metrics.ListLogMetricsRequest], - logging_metrics.ListLogMetricsResponse]: + def list_log_metrics( + self, + ) -> Callable[ + [logging_metrics.ListLogMetricsRequest], logging_metrics.ListLogMetricsResponse + ]: r"""Return a callable for the list log metrics method over gRPC. Lists logs-based metrics. @@ -376,18 +404,18 @@ def list_log_metrics(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_log_metrics' not in self._stubs: - self._stubs['list_log_metrics'] = self._logged_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/ListLogMetrics', + if "list_log_metrics" not in self._stubs: + self._stubs["list_log_metrics"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/ListLogMetrics", request_serializer=logging_metrics.ListLogMetricsRequest.serialize, response_deserializer=logging_metrics.ListLogMetricsResponse.deserialize, ) - return self._stubs['list_log_metrics'] + return self._stubs["list_log_metrics"] @property - def get_log_metric(self) -> Callable[ - [logging_metrics.GetLogMetricRequest], - logging_metrics.LogMetric]: + def get_log_metric( + self, + ) -> Callable[[logging_metrics.GetLogMetricRequest], logging_metrics.LogMetric]: r"""Return a callable for the get log metric method over gRPC. Gets a logs-based metric. @@ -402,18 +430,18 @@ def get_log_metric(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_log_metric' not in self._stubs: - self._stubs['get_log_metric'] = self._logged_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/GetLogMetric', + if "get_log_metric" not in self._stubs: + self._stubs["get_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/GetLogMetric", request_serializer=logging_metrics.GetLogMetricRequest.serialize, response_deserializer=logging_metrics.LogMetric.deserialize, ) - return self._stubs['get_log_metric'] + return self._stubs["get_log_metric"] @property - def create_log_metric(self) -> Callable[ - [logging_metrics.CreateLogMetricRequest], - logging_metrics.LogMetric]: + def create_log_metric( + self, + ) -> Callable[[logging_metrics.CreateLogMetricRequest], logging_metrics.LogMetric]: r"""Return a callable for the create log metric method over gRPC. Creates a logs-based metric. @@ -428,18 +456,18 @@ def create_log_metric(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_log_metric' not in self._stubs: - self._stubs['create_log_metric'] = self._logged_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/CreateLogMetric', + if "create_log_metric" not in self._stubs: + self._stubs["create_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/CreateLogMetric", request_serializer=logging_metrics.CreateLogMetricRequest.serialize, response_deserializer=logging_metrics.LogMetric.deserialize, ) - return self._stubs['create_log_metric'] + return self._stubs["create_log_metric"] @property - def update_log_metric(self) -> Callable[ - [logging_metrics.UpdateLogMetricRequest], - logging_metrics.LogMetric]: + def update_log_metric( + self, + ) -> Callable[[logging_metrics.UpdateLogMetricRequest], logging_metrics.LogMetric]: r"""Return a callable for the update log metric method over gRPC. Creates or updates a logs-based metric. @@ -454,18 +482,18 @@ def update_log_metric(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_log_metric' not in self._stubs: - self._stubs['update_log_metric'] = self._logged_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/UpdateLogMetric', + if "update_log_metric" not in self._stubs: + self._stubs["update_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/UpdateLogMetric", request_serializer=logging_metrics.UpdateLogMetricRequest.serialize, response_deserializer=logging_metrics.LogMetric.deserialize, ) - return self._stubs['update_log_metric'] + return self._stubs["update_log_metric"] @property - def delete_log_metric(self) -> Callable[ - [logging_metrics.DeleteLogMetricRequest], - empty_pb2.Empty]: + def delete_log_metric( + self, + ) -> Callable[[logging_metrics.DeleteLogMetricRequest], empty_pb2.Empty]: r"""Return a callable for the delete log metric method over gRPC. Deletes a logs-based metric. @@ -480,13 +508,13 @@ def delete_log_metric(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_log_metric' not in self._stubs: - self._stubs['delete_log_metric'] = self._logged_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/DeleteLogMetric', + if "delete_log_metric" not in self._stubs: + self._stubs["delete_log_metric"] = self._logged_channel.unary_unary( + "/google.logging.v2.MetricsServiceV2/DeleteLogMetric", request_serializer=logging_metrics.DeleteLogMetricRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_log_metric'] + return self._stubs["delete_log_metric"] def close(self): self._logged_channel.close() @@ -495,8 +523,7 @@ def close(self): def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -513,8 +540,7 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -530,9 +556,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -550,6 +577,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'MetricsServiceV2GrpcTransport', -) +__all__ = ("MetricsServiceV2GrpcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py index dfd1e7898250..3424c66def78 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -13,29 +13,46 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import inspect import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.redis_v1 import gapic_version as package_version - +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.redis_v1 import gapic_version as package_version +from google.cloud.redis_v1._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -44,6 +61,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -57,24 +75,27 @@ _LOGGER = std_logging.getLogger(__name__) -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.redis_v1.services.cloud_redis import pagers -from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import CloudRedisTransport, DEFAULT_CLIENT_INFO +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.redis_v1.services.cloud_redis import pagers +from google.cloud.redis_v1.types import cloud_redis +from google.longrunning import operations_pb2 # type: ignore + +from .transports.base import DEFAULT_CLIENT_INFO, CloudRedisTransport from .transports.grpc import CloudRedisGrpcTransport from .transports.grpc_asyncio import CloudRedisGrpcAsyncIOTransport from .transports.rest import CloudRedisRestTransport + ASYNC_REST_EXCEPTION = None try: from .transports.rest_asyncio import AsyncCloudRedisRestTransport + HAS_ASYNC_REST_DEPENDENCIES = True -except ImportError as e: # pragma: NO COVER +except ImportError as e: # pragma: NO COVER HAS_ASYNC_REST_DEPENDENCIES = False ASYNC_REST_EXCEPTION = e @@ -86,6 +107,7 @@ class CloudRedisClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[CloudRedisTransport]] _transport_registry["grpc"] = CloudRedisGrpcTransport _transport_registry["grpc_asyncio"] = CloudRedisGrpcAsyncIOTransport @@ -93,9 +115,10 @@ class CloudRedisClientMeta(type): if HAS_ASYNC_REST_DEPENDENCIES: # pragma: NO COVER _transport_registry["rest_asyncio"] = AsyncCloudRedisRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[CloudRedisTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[CloudRedisTransport]: """Returns an appropriate transport class. Args: @@ -106,7 +129,9 @@ def get_transport_class(cls, The transport class to use. """ # If a specific transport is requested, return that one. - if label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES: # pragma: NO COVER + if ( + label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES + ): # pragma: NO COVER raise ASYNC_REST_EXCEPTION if label: return cls._transport_registry[label] @@ -178,8 +203,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CloudRedisClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -196,73 +220,108 @@ def transport(self) -> CloudRedisTransport: return self._transport @staticmethod - def instance_path(project: str,location: str,instance: str,) -> str: + def instance_path( + project: str, + location: str, + instance: str, + ) -> str: """Returns a fully-qualified instance string.""" - return "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) + return "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) @staticmethod - def parse_instance_path(path: str) -> Dict[str,str]: + def parse_instance_path(path: str) -> Dict[str, str]: """Parses a instance path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -294,14 +353,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -314,8 +377,10 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -354,15 +419,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -395,12 +463,16 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the cloud redis client. Args: @@ -458,13 +530,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = CloudRedisClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=CloudRedisClient._DEFAULT_UNIVERSE) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = CloudRedisClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=CloudRedisClient._DEFAULT_UNIVERSE, + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -476,7 +558,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -485,30 +569,31 @@ def __init__(self, *, if transport_provided: # transport is a CloudRedisTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." + "When providing a transport instance, provide its scopes directly." ) self._transport = cast(CloudRedisTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=CloudRedisClient._DEFAULT_UNIVERSE, - default_mtls_endpoint=CloudRedisClient.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=CloudRedisClient._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" or ( - self._use_mtls_endpoint == "auto" and self._client_cert_source - ), - )) + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=CloudRedisClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=CloudRedisClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=CloudRedisClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) if not transport_provided: - transport_init: Union[Type[CloudRedisTransport], Callable[..., CloudRedisTransport]] = ( + transport_init: Union[ + Type[CloudRedisTransport], Callable[..., CloudRedisTransport] + ] = ( CloudRedisClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., CloudRedisTransport], transport) @@ -521,9 +606,12 @@ def __init__(self, *, "google.api_core.client_options.ClientOptions.quota_project_id": self._client_options.quota_project_id, "google.api_core.client_options.ClientOptions.client_cert_source": self._client_options.client_cert_source, "google.api_core.client_options.ClientOptions.api_audience": self._client_options.api_audience, - } - provided_unsupported_params = [name for name, value in unsupported_params.items() if value is not None] + provided_unsupported_params = [ + name + for name, value in unsupported_params.items() + if value is not None + ] if provided_unsupported_params: raise core_exceptions.AsyncRestUnsupportedParameterError( # type: ignore f"The following provided parameters are not supported for `transport=rest_asyncio`: {', '.join(provided_unsupported_params)}" @@ -537,8 +625,12 @@ def __init__(self, *, import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) # When OpenTelemetry tracing is enabled, pass client_options to the transport # so it can wire tracing interceptors and method spans. @@ -564,33 +656,46 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"client_options": client_options} if client_options else {}), + **( + {"client_options": client_options} + if client_options is not None + else {} + ), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.redis_v1.CloudRedisClient`.", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.cloud.redis.v1.CloudRedis", "credentialsType": None, - } + }, ) - def list_instances(self, - request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListInstancesPager: + def list_instances( + self, + request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListInstancesPager: r"""Lists all Redis instances owned by a project in either the specified location (region) or all locations. @@ -663,10 +768,14 @@ def sample_list_instances(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -684,9 +793,7 @@ def sample_list_instances(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -714,14 +821,15 @@ def sample_list_instances(): # Done; return the response. return response - def get_instance(self, - request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_redis.Instance: + def get_instance( + self, + request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.Instance: r"""Gets the details of a specific Redis instance. .. code-block:: python @@ -778,10 +886,14 @@ def sample_get_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -799,9 +911,7 @@ def sample_get_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -818,14 +928,15 @@ def sample_get_instance(): # Done; return the response. return response - def get_instance_auth_string(self, - request: Optional[Union[cloud_redis.GetInstanceAuthStringRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_redis.InstanceAuthString: + def get_instance_auth_string( + self, + request: Optional[Union[cloud_redis.GetInstanceAuthStringRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.InstanceAuthString: r"""Gets the AUTH string for a Redis instance. If AUTH is not enabled for the instance the response will be empty. This information is not included in the details returned @@ -885,10 +996,14 @@ def sample_get_instance_auth_string(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -906,9 +1021,7 @@ def sample_get_instance_auth_string(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -925,16 +1038,17 @@ def sample_get_instance_auth_string(): # Done; return the response. return response - def create_instance(self, - request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, - *, - parent: Optional[str] = None, - instance_id: Optional[str] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_instance( + self, + request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance_id: Optional[str] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a Redis instance based on the specified tier and memory size. @@ -1040,10 +1154,14 @@ def sample_create_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, instance_id, instance] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1065,9 +1183,7 @@ def sample_create_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1092,15 +1208,16 @@ def sample_create_instance(): # Done; return the response. return response - def update_instance(self, - request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, - *, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_instance( + self, + request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, + *, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates the metadata and configuration of a specific Redis instance. Completed longrunning.Operation will contain the new @@ -1190,10 +1307,14 @@ def sample_update_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [update_mask, instance] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1213,9 +1334,9 @@ def sample_update_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("instance.name", request.instance.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("instance.name", request.instance.name),) + ), ) # Validate the universe domain. @@ -1240,15 +1361,16 @@ def sample_update_instance(): # Done; return the response. return response - def upgrade_instance(self, - request: Optional[Union[cloud_redis.UpgradeInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - redis_version: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def upgrade_instance( + self, + request: Optional[Union[cloud_redis.UpgradeInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + redis_version: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Upgrades Redis instance to the newer Redis version specified in the request. @@ -1323,10 +1445,14 @@ def sample_upgrade_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, redis_version] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1346,9 +1472,7 @@ def sample_upgrade_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1373,15 +1497,16 @@ def sample_upgrade_instance(): # Done; return the response. return response - def import_instance(self, - request: Optional[Union[cloud_redis.ImportInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - input_config: Optional[cloud_redis.InputConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def import_instance( + self, + request: Optional[Union[cloud_redis.ImportInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + input_config: Optional[cloud_redis.InputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. Redis may stop serving during this operation. Instance @@ -1466,10 +1591,14 @@ def sample_import_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, input_config] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1489,9 +1618,7 @@ def sample_import_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1516,15 +1643,16 @@ def sample_import_instance(): # Done; return the response. return response - def export_instance(self, - request: Optional[Union[cloud_redis.ExportInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - output_config: Optional[cloud_redis.OutputConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def export_instance( + self, + request: Optional[Union[cloud_redis.ExportInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + output_config: Optional[cloud_redis.OutputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Export Redis instance data into a Redis RDB format file in Cloud Storage. Redis will continue serving during this operation. @@ -1606,10 +1734,14 @@ def sample_export_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, output_config] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1629,9 +1761,7 @@ def sample_export_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1656,15 +1786,18 @@ def sample_export_instance(): # Done; return the response. return response - def failover_instance(self, - request: Optional[Union[cloud_redis.FailoverInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - data_protection_mode: Optional[cloud_redis.FailoverInstanceRequest.DataProtectionMode] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def failover_instance( + self, + request: Optional[Union[cloud_redis.FailoverInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + data_protection_mode: Optional[ + cloud_redis.FailoverInstanceRequest.DataProtectionMode + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Initiates a failover of the primary node to current replica node for a specific STANDARD tier Cloud Memorystore for Redis instance. @@ -1740,10 +1873,14 @@ def sample_failover_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, data_protection_mode] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1763,9 +1900,7 @@ def sample_failover_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1790,14 +1925,15 @@ def sample_failover_instance(): # Done; return the response. return response - def delete_instance(self, - request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_instance( + self, + request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes a specific Redis instance. Instance stops serving and data is deleted. @@ -1871,10 +2007,14 @@ def sample_delete_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1892,9 +2032,7 @@ def sample_delete_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1919,16 +2057,19 @@ def sample_delete_instance(): # Done; return the response. return response - def reschedule_maintenance(self, - request: Optional[Union[cloud_redis.RescheduleMaintenanceRequest, dict]] = None, - *, - name: Optional[str] = None, - reschedule_type: Optional[cloud_redis.RescheduleMaintenanceRequest.RescheduleType] = None, - schedule_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def reschedule_maintenance( + self, + request: Optional[Union[cloud_redis.RescheduleMaintenanceRequest, dict]] = None, + *, + name: Optional[str] = None, + reschedule_type: Optional[ + cloud_redis.RescheduleMaintenanceRequest.RescheduleType + ] = None, + schedule_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Reschedule maintenance for a given instance in a given project and location. @@ -2011,10 +2152,14 @@ def sample_reschedule_maintenance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, reschedule_type, schedule_time] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2036,9 +2181,7 @@ def sample_reschedule_maintenance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2118,8 +2261,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -2128,7 +2270,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2178,8 +2324,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -2188,7 +2333,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2242,15 +2391,19 @@ def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def cancel_operation( self, @@ -2297,15 +2450,19 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def wait_operation( self, @@ -2355,8 +2512,7 @@ def wait_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -2365,7 +2521,11 @@ def wait_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2415,8 +2575,7 @@ def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -2425,7 +2584,11 @@ def get_location( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2475,8 +2638,7 @@ def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -2485,7 +2647,11 @@ def list_locations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2494,9 +2660,9 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "CloudRedisClient", -) +__all__ = ("CloudRedisClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py index a46f83e02401..4e35e31a04f6 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -17,49 +17,54 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.redis_v1 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core +import google.auth # type: ignore +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.redis_v1 import gapic_version as package_version from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +# Check once at module load time whether google-api-core's wrap_method supports +# OpenTelemetry tracing arguments (client_options, method_name, is_streaming, kind) +# to avoid recurring inspect.signature latency during client instantiation. +_WRAP_METHOD_SUPPORTS_TRACING = ( + "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters +) + class CloudRedisTransport(abc.ABC): """Abstract transport class for CloudRedis.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'redis.googleapis.com' + DEFAULT_HOST: str = "redis.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -101,38 +106,47 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._client_options = client_options - # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments - # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility - # with older versions of google-api-core. - self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrap_with_tracing = _WRAP_METHOD_SUPPORTS_TRACING self._wrapped_methods: Dict[Callable, Callable] = {} @@ -145,15 +159,24 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["client_options"] = self._client_options try: kwargs["kind"] = self.kind - # Base transport raises NotImplementedError for abstract kind property. - # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + # The abstract BaseTransport class raises NotImplementedError for the kind property. + # Concrete transport subclasses (gRPC, REST) override kind, so this exception handler + # is unreachable during normal execution. Excluded from coverage check. except NotImplementedError: # pragma: NO COVER pass return gapic_v1.method.wrap_method(func, *args, **kwargs) - # Remove tracing-specific arguments if older google-api-core is installed - for k in ["client_options", "method_name", "is_streaming", "kind"]: - kwargs.pop(k, None) - return gapic_v1.method.wrap_method(func, *args, **kwargs) + # The fallback below strips tracing-specific arguments when an older version + # of google-api-core is installed (which does not accept client_options, etc.). + # Excluded from coverage because our CI and testing environments always install + # a modern version of google-api-core that supports tracing. + for k in [ + "client_options", + "method_name", + "is_streaming", + "kind", + ]: # pragma: NO COVER + kwargs.pop(k, None) # pragma: NO COVER + return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -259,14 +282,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -276,102 +299,107 @@ def operations_client(self): raise NotImplementedError() @property - def list_instances(self) -> Callable[ - [cloud_redis.ListInstancesRequest], - Union[ - cloud_redis.ListInstancesResponse, - Awaitable[cloud_redis.ListInstancesResponse] - ]]: + def list_instances( + self, + ) -> Callable[ + [cloud_redis.ListInstancesRequest], + Union[ + cloud_redis.ListInstancesResponse, + Awaitable[cloud_redis.ListInstancesResponse], + ], + ]: raise NotImplementedError() @property - def get_instance(self) -> Callable[ - [cloud_redis.GetInstanceRequest], - Union[ - cloud_redis.Instance, - Awaitable[cloud_redis.Instance] - ]]: + def get_instance( + self, + ) -> Callable[ + [cloud_redis.GetInstanceRequest], + Union[cloud_redis.Instance, Awaitable[cloud_redis.Instance]], + ]: raise NotImplementedError() @property - def get_instance_auth_string(self) -> Callable[ - [cloud_redis.GetInstanceAuthStringRequest], - Union[ - cloud_redis.InstanceAuthString, - Awaitable[cloud_redis.InstanceAuthString] - ]]: + def get_instance_auth_string( + self, + ) -> Callable[ + [cloud_redis.GetInstanceAuthStringRequest], + Union[ + cloud_redis.InstanceAuthString, Awaitable[cloud_redis.InstanceAuthString] + ], + ]: raise NotImplementedError() @property - def create_instance(self) -> Callable[ - [cloud_redis.CreateInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_instance( + self, + ) -> Callable[ + [cloud_redis.CreateInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_instance(self) -> Callable[ - [cloud_redis.UpdateInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_instance( + self, + ) -> Callable[ + [cloud_redis.UpdateInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def upgrade_instance(self) -> Callable[ - [cloud_redis.UpgradeInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def upgrade_instance( + self, + ) -> Callable[ + [cloud_redis.UpgradeInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def import_instance(self) -> Callable[ - [cloud_redis.ImportInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def import_instance( + self, + ) -> Callable[ + [cloud_redis.ImportInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def export_instance(self) -> Callable[ - [cloud_redis.ExportInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def export_instance( + self, + ) -> Callable[ + [cloud_redis.ExportInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def failover_instance(self) -> Callable[ - [cloud_redis.FailoverInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def failover_instance( + self, + ) -> Callable[ + [cloud_redis.FailoverInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_instance(self) -> Callable[ - [cloud_redis.DeleteInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_instance( + self, + ) -> Callable[ + [cloud_redis.DeleteInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def reschedule_maintenance(self) -> Callable[ - [cloud_redis.RescheduleMaintenanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def reschedule_maintenance( + self, + ) -> Callable[ + [cloud_redis.RescheduleMaintenanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property @@ -379,7 +407,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -420,7 +451,8 @@ def wait_operation( raise NotImplementedError() @property - def get_location(self, + def get_location( + self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -428,10 +460,14 @@ def get_location(self, raise NotImplementedError() @property - def list_locations(self, + def list_locations( + self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], ]: raise NotImplementedError() @@ -440,6 +476,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'CloudRedisTransport', -) +__all__ = ("CloudRedisTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index 0fe6a61d9116..6850f12fd7bc 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -17,17 +17,19 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -from google.api_core import operations_v1 + from google.api_core.grpc_helpers import ( + ClientInterceptor, # type: ignore[attr-defined] + ) from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 + # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -35,21 +37,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore +import google.auth # type: ignore +import google.protobuf.message +import proto # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.redis_v1.types import cloud_redis +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson -import google.protobuf.message -import proto # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore -from .base import CloudRedisTransport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, CloudRedisTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -59,7 +61,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -80,7 +84,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -91,7 +95,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -106,7 +114,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": client_call_details.method, "response": grpc_response, @@ -148,32 +156,35 @@ class CloudRedisGrpcTransport(CloudRedisTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'redis.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], - ] + def __init__( + self, + *, + host: str = "redis.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -310,8 +321,17 @@ def __init__(self, *, channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None and otel_interceptor not in channel_interceptors + and not any( + getattr(i, "_is_otel_interceptor", None) is True + for i in channel_interceptors + ) ): channel_interceptors.append(otel_interceptor) @@ -320,22 +340,28 @@ def __init__(self, *, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) + self._grpc_channel = apply_interceptors( + self._grpc_channel, channel_interceptors + ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'redis.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "redis.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -371,13 +397,12 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property @@ -397,9 +422,11 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def list_instances(self) -> Callable[ - [cloud_redis.ListInstancesRequest], - cloud_redis.ListInstancesResponse]: + def list_instances( + self, + ) -> Callable[ + [cloud_redis.ListInstancesRequest], cloud_redis.ListInstancesResponse + ]: r"""Return a callable for the list instances method over gRPC. Lists all Redis instances owned by a project in either the @@ -423,18 +450,18 @@ def list_instances(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_instances' not in self._stubs: - self._stubs['list_instances'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/ListInstances', + if "list_instances" not in self._stubs: + self._stubs["list_instances"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/ListInstances", request_serializer=cloud_redis.ListInstancesRequest.serialize, response_deserializer=cloud_redis.ListInstancesResponse.deserialize, ) - return self._stubs['list_instances'] + return self._stubs["list_instances"] @property - def get_instance(self) -> Callable[ - [cloud_redis.GetInstanceRequest], - cloud_redis.Instance]: + def get_instance( + self, + ) -> Callable[[cloud_redis.GetInstanceRequest], cloud_redis.Instance]: r"""Return a callable for the get instance method over gRPC. Gets the details of a specific Redis instance. @@ -449,18 +476,20 @@ def get_instance(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_instance' not in self._stubs: - self._stubs['get_instance'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/GetInstance', + if "get_instance" not in self._stubs: + self._stubs["get_instance"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/GetInstance", request_serializer=cloud_redis.GetInstanceRequest.serialize, response_deserializer=cloud_redis.Instance.deserialize, ) - return self._stubs['get_instance'] + return self._stubs["get_instance"] @property - def get_instance_auth_string(self) -> Callable[ - [cloud_redis.GetInstanceAuthStringRequest], - cloud_redis.InstanceAuthString]: + def get_instance_auth_string( + self, + ) -> Callable[ + [cloud_redis.GetInstanceAuthStringRequest], cloud_redis.InstanceAuthString + ]: r"""Return a callable for the get instance auth string method over gRPC. Gets the AUTH string for a Redis instance. If AUTH is @@ -478,18 +507,18 @@ def get_instance_auth_string(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_instance_auth_string' not in self._stubs: - self._stubs['get_instance_auth_string'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/GetInstanceAuthString', + if "get_instance_auth_string" not in self._stubs: + self._stubs["get_instance_auth_string"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/GetInstanceAuthString", request_serializer=cloud_redis.GetInstanceAuthStringRequest.serialize, response_deserializer=cloud_redis.InstanceAuthString.deserialize, ) - return self._stubs['get_instance_auth_string'] + return self._stubs["get_instance_auth_string"] @property - def create_instance(self) -> Callable[ - [cloud_redis.CreateInstanceRequest], - operations_pb2.Operation]: + def create_instance( + self, + ) -> Callable[[cloud_redis.CreateInstanceRequest], operations_pb2.Operation]: r"""Return a callable for the create instance method over gRPC. Creates a Redis instance based on the specified tier and memory @@ -517,18 +546,18 @@ def create_instance(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_instance' not in self._stubs: - self._stubs['create_instance'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/CreateInstance', + if "create_instance" not in self._stubs: + self._stubs["create_instance"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/CreateInstance", request_serializer=cloud_redis.CreateInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_instance'] + return self._stubs["create_instance"] @property - def update_instance(self) -> Callable[ - [cloud_redis.UpdateInstanceRequest], - operations_pb2.Operation]: + def update_instance( + self, + ) -> Callable[[cloud_redis.UpdateInstanceRequest], operations_pb2.Operation]: r"""Return a callable for the update instance method over gRPC. Updates the metadata and configuration of a specific @@ -548,18 +577,18 @@ def update_instance(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_instance' not in self._stubs: - self._stubs['update_instance'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/UpdateInstance', + if "update_instance" not in self._stubs: + self._stubs["update_instance"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/UpdateInstance", request_serializer=cloud_redis.UpdateInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_instance'] + return self._stubs["update_instance"] @property - def upgrade_instance(self) -> Callable[ - [cloud_redis.UpgradeInstanceRequest], - operations_pb2.Operation]: + def upgrade_instance( + self, + ) -> Callable[[cloud_redis.UpgradeInstanceRequest], operations_pb2.Operation]: r"""Return a callable for the upgrade instance method over gRPC. Upgrades Redis instance to the newer Redis version @@ -575,18 +604,18 @@ def upgrade_instance(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'upgrade_instance' not in self._stubs: - self._stubs['upgrade_instance'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/UpgradeInstance', + if "upgrade_instance" not in self._stubs: + self._stubs["upgrade_instance"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/UpgradeInstance", request_serializer=cloud_redis.UpgradeInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['upgrade_instance'] + return self._stubs["upgrade_instance"] @property - def import_instance(self) -> Callable[ - [cloud_redis.ImportInstanceRequest], - operations_pb2.Operation]: + def import_instance( + self, + ) -> Callable[[cloud_redis.ImportInstanceRequest], operations_pb2.Operation]: r"""Return a callable for the import instance method over gRPC. Import a Redis RDB snapshot file from Cloud Storage @@ -609,18 +638,18 @@ def import_instance(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'import_instance' not in self._stubs: - self._stubs['import_instance'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/ImportInstance', + if "import_instance" not in self._stubs: + self._stubs["import_instance"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/ImportInstance", request_serializer=cloud_redis.ImportInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['import_instance'] + return self._stubs["import_instance"] @property - def export_instance(self) -> Callable[ - [cloud_redis.ExportInstanceRequest], - operations_pb2.Operation]: + def export_instance( + self, + ) -> Callable[[cloud_redis.ExportInstanceRequest], operations_pb2.Operation]: r"""Return a callable for the export instance method over gRPC. Export Redis instance data into a Redis RDB format @@ -640,18 +669,18 @@ def export_instance(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'export_instance' not in self._stubs: - self._stubs['export_instance'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/ExportInstance', + if "export_instance" not in self._stubs: + self._stubs["export_instance"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/ExportInstance", request_serializer=cloud_redis.ExportInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['export_instance'] + return self._stubs["export_instance"] @property - def failover_instance(self) -> Callable[ - [cloud_redis.FailoverInstanceRequest], - operations_pb2.Operation]: + def failover_instance( + self, + ) -> Callable[[cloud_redis.FailoverInstanceRequest], operations_pb2.Operation]: r"""Return a callable for the failover instance method over gRPC. Initiates a failover of the primary node to current @@ -668,18 +697,18 @@ def failover_instance(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'failover_instance' not in self._stubs: - self._stubs['failover_instance'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/FailoverInstance', + if "failover_instance" not in self._stubs: + self._stubs["failover_instance"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/FailoverInstance", request_serializer=cloud_redis.FailoverInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['failover_instance'] + return self._stubs["failover_instance"] @property - def delete_instance(self) -> Callable[ - [cloud_redis.DeleteInstanceRequest], - operations_pb2.Operation]: + def delete_instance( + self, + ) -> Callable[[cloud_redis.DeleteInstanceRequest], operations_pb2.Operation]: r"""Return a callable for the delete instance method over gRPC. Deletes a specific Redis instance. Instance stops @@ -695,18 +724,18 @@ def delete_instance(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_instance' not in self._stubs: - self._stubs['delete_instance'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/DeleteInstance', + if "delete_instance" not in self._stubs: + self._stubs["delete_instance"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/DeleteInstance", request_serializer=cloud_redis.DeleteInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_instance'] + return self._stubs["delete_instance"] @property - def reschedule_maintenance(self) -> Callable[ - [cloud_redis.RescheduleMaintenanceRequest], - operations_pb2.Operation]: + def reschedule_maintenance( + self, + ) -> Callable[[cloud_redis.RescheduleMaintenanceRequest], operations_pb2.Operation]: r"""Return a callable for the reschedule maintenance method over gRPC. Reschedule maintenance for a given instance in a @@ -722,13 +751,13 @@ def reschedule_maintenance(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'reschedule_maintenance' not in self._stubs: - self._stubs['reschedule_maintenance'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/RescheduleMaintenance', + if "reschedule_maintenance" not in self._stubs: + self._stubs["reschedule_maintenance"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/RescheduleMaintenance", request_serializer=cloud_redis.RescheduleMaintenanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['reschedule_maintenance'] + return self._stubs["reschedule_maintenance"] def close(self): self._logged_channel.close() @@ -737,8 +766,7 @@ def close(self): def delete_operation( self, ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ + r"""Return a callable for the delete_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -755,8 +783,7 @@ def delete_operation( def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -773,8 +800,7 @@ def cancel_operation( def wait_operation( self, ) -> Callable[[operations_pb2.WaitOperationRequest], None]: - r"""Return a callable for the wait_operation method over gRPC. - """ + r"""Return a callable for the wait_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -791,8 +817,7 @@ def wait_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -808,9 +833,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -826,9 +852,10 @@ def list_operations( @property def list_locations( self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -845,8 +872,7 @@ def list_locations( def get_location( self, ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -864,6 +890,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'CloudRedisGrpcTransport', -) +__all__ = ("CloudRedisGrpcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py index a79874b447b3..b8f416d64e8d 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py @@ -13,29 +13,46 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import inspect import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.redis_v1 import gapic_version as package_version - +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.redis_v1 import gapic_version as package_version +from google.cloud.redis_v1._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -44,6 +61,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -57,24 +75,27 @@ _LOGGER = std_logging.getLogger(__name__) -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.redis_v1.services.cloud_redis import pagers -from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import CloudRedisTransport, DEFAULT_CLIENT_INFO +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.redis_v1.services.cloud_redis import pagers +from google.cloud.redis_v1.types import cloud_redis +from google.longrunning import operations_pb2 # type: ignore + +from .transports.base import DEFAULT_CLIENT_INFO, CloudRedisTransport from .transports.grpc import CloudRedisGrpcTransport from .transports.grpc_asyncio import CloudRedisGrpcAsyncIOTransport from .transports.rest import CloudRedisRestTransport + ASYNC_REST_EXCEPTION = None try: from .transports.rest_asyncio import AsyncCloudRedisRestTransport + HAS_ASYNC_REST_DEPENDENCIES = True -except ImportError as e: # pragma: NO COVER +except ImportError as e: # pragma: NO COVER HAS_ASYNC_REST_DEPENDENCIES = False ASYNC_REST_EXCEPTION = e @@ -86,6 +107,7 @@ class CloudRedisClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[CloudRedisTransport]] _transport_registry["grpc"] = CloudRedisGrpcTransport _transport_registry["grpc_asyncio"] = CloudRedisGrpcAsyncIOTransport @@ -93,9 +115,10 @@ class CloudRedisClientMeta(type): if HAS_ASYNC_REST_DEPENDENCIES: # pragma: NO COVER _transport_registry["rest_asyncio"] = AsyncCloudRedisRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[CloudRedisTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[CloudRedisTransport]: """Returns an appropriate transport class. Args: @@ -106,7 +129,9 @@ def get_transport_class(cls, The transport class to use. """ # If a specific transport is requested, return that one. - if label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES: # pragma: NO COVER + if ( + label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES + ): # pragma: NO COVER raise ASYNC_REST_EXCEPTION if label: return cls._transport_registry[label] @@ -178,8 +203,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CloudRedisClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -196,73 +220,108 @@ def transport(self) -> CloudRedisTransport: return self._transport @staticmethod - def instance_path(project: str,location: str,instance: str,) -> str: + def instance_path( + project: str, + location: str, + instance: str, + ) -> str: """Returns a fully-qualified instance string.""" - return "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) + return "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) @staticmethod - def parse_instance_path(path: str) -> Dict[str,str]: + def parse_instance_path(path: str) -> Dict[str, str]: """Parses a instance path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -294,14 +353,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -314,8 +377,10 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -354,15 +419,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -395,12 +463,16 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the cloud redis client. Args: @@ -458,13 +530,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = CloudRedisClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=CloudRedisClient._DEFAULT_UNIVERSE) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = CloudRedisClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=CloudRedisClient._DEFAULT_UNIVERSE, + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -476,7 +558,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -485,30 +569,31 @@ def __init__(self, *, if transport_provided: # transport is a CloudRedisTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." + "When providing a transport instance, provide its scopes directly." ) self._transport = cast(CloudRedisTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=CloudRedisClient._DEFAULT_UNIVERSE, - default_mtls_endpoint=CloudRedisClient.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=CloudRedisClient._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" or ( - self._use_mtls_endpoint == "auto" and self._client_cert_source - ), - )) + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=CloudRedisClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=CloudRedisClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=CloudRedisClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) if not transport_provided: - transport_init: Union[Type[CloudRedisTransport], Callable[..., CloudRedisTransport]] = ( + transport_init: Union[ + Type[CloudRedisTransport], Callable[..., CloudRedisTransport] + ] = ( CloudRedisClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., CloudRedisTransport], transport) @@ -521,9 +606,12 @@ def __init__(self, *, "google.api_core.client_options.ClientOptions.quota_project_id": self._client_options.quota_project_id, "google.api_core.client_options.ClientOptions.client_cert_source": self._client_options.client_cert_source, "google.api_core.client_options.ClientOptions.api_audience": self._client_options.api_audience, - } - provided_unsupported_params = [name for name, value in unsupported_params.items() if value is not None] + provided_unsupported_params = [ + name + for name, value in unsupported_params.items() + if value is not None + ] if provided_unsupported_params: raise core_exceptions.AsyncRestUnsupportedParameterError( # type: ignore f"The following provided parameters are not supported for `transport=rest_asyncio`: {', '.join(provided_unsupported_params)}" @@ -537,8 +625,12 @@ def __init__(self, *, import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) # When OpenTelemetry tracing is enabled, pass client_options to the transport # so it can wire tracing interceptors and method spans. @@ -564,33 +656,46 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"client_options": client_options} if client_options else {}), + **( + {"client_options": client_options} + if client_options is not None + else {} + ), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.redis_v1.CloudRedisClient`.", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.cloud.redis.v1.CloudRedis", "credentialsType": None, - } + }, ) - def list_instances(self, - request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListInstancesPager: + def list_instances( + self, + request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListInstancesPager: r"""Lists all Redis instances owned by a project in either the specified location (region) or all locations. @@ -663,10 +768,14 @@ def sample_list_instances(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -684,9 +793,7 @@ def sample_list_instances(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -714,14 +821,15 @@ def sample_list_instances(): # Done; return the response. return response - def get_instance(self, - request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_redis.Instance: + def get_instance( + self, + request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.Instance: r"""Gets the details of a specific Redis instance. .. code-block:: python @@ -778,10 +886,14 @@ def sample_get_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -799,9 +911,7 @@ def sample_get_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -818,16 +928,17 @@ def sample_get_instance(): # Done; return the response. return response - def create_instance(self, - request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, - *, - parent: Optional[str] = None, - instance_id: Optional[str] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_instance( + self, + request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance_id: Optional[str] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a Redis instance based on the specified tier and memory size. @@ -933,10 +1044,14 @@ def sample_create_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, instance_id, instance] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -958,9 +1073,7 @@ def sample_create_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -985,15 +1098,16 @@ def sample_create_instance(): # Done; return the response. return response - def update_instance(self, - request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, - *, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_instance( + self, + request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, + *, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates the metadata and configuration of a specific Redis instance. Completed longrunning.Operation will contain the new @@ -1083,10 +1197,14 @@ def sample_update_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [update_mask, instance] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1106,9 +1224,9 @@ def sample_update_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("instance.name", request.instance.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("instance.name", request.instance.name),) + ), ) # Validate the universe domain. @@ -1133,14 +1251,15 @@ def sample_update_instance(): # Done; return the response. return response - def delete_instance(self, - request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_instance( + self, + request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes a specific Redis instance. Instance stops serving and data is deleted. @@ -1214,10 +1333,14 @@ def sample_delete_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1235,9 +1358,7 @@ def sample_delete_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1317,8 +1438,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1327,7 +1447,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1377,8 +1501,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1387,7 +1510,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1441,15 +1568,19 @@ def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def cancel_operation( self, @@ -1496,15 +1627,19 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def wait_operation( self, @@ -1554,8 +1689,7 @@ def wait_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1564,7 +1698,11 @@ def wait_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1614,8 +1752,7 @@ def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1624,7 +1761,11 @@ def get_location( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1674,8 +1815,7 @@ def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1684,7 +1824,11 @@ def list_locations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1693,9 +1837,9 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "CloudRedisClient", -) +__all__ = ("CloudRedisClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py index 3e441f674d6f..fb2d6e770f83 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -17,49 +17,54 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.redis_v1 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core +import google.auth # type: ignore +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.redis_v1 import gapic_version as package_version from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +# Check once at module load time whether google-api-core's wrap_method supports +# OpenTelemetry tracing arguments (client_options, method_name, is_streaming, kind) +# to avoid recurring inspect.signature latency during client instantiation. +_WRAP_METHOD_SUPPORTS_TRACING = ( + "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters +) + class CloudRedisTransport(abc.ABC): """Abstract transport class for CloudRedis.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'redis.googleapis.com' + DEFAULT_HOST: str = "redis.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -101,38 +106,47 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._client_options = client_options - # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments - # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility - # with older versions of google-api-core. - self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrap_with_tracing = _WRAP_METHOD_SUPPORTS_TRACING self._wrapped_methods: Dict[Callable, Callable] = {} @@ -145,15 +159,24 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["client_options"] = self._client_options try: kwargs["kind"] = self.kind - # Base transport raises NotImplementedError for abstract kind property. - # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + # The abstract BaseTransport class raises NotImplementedError for the kind property. + # Concrete transport subclasses (gRPC, REST) override kind, so this exception handler + # is unreachable during normal execution. Excluded from coverage check. except NotImplementedError: # pragma: NO COVER pass return gapic_v1.method.wrap_method(func, *args, **kwargs) - # Remove tracing-specific arguments if older google-api-core is installed - for k in ["client_options", "method_name", "is_streaming", "kind"]: - kwargs.pop(k, None) - return gapic_v1.method.wrap_method(func, *args, **kwargs) + # The fallback below strips tracing-specific arguments when an older version + # of google-api-core is installed (which does not accept client_options, etc.). + # Excluded from coverage because our CI and testing environments always install + # a modern version of google-api-core that supports tracing. + for k in [ + "client_options", + "method_name", + "is_streaming", + "kind", + ]: # pragma: NO COVER + kwargs.pop(k, None) # pragma: NO COVER + return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -223,14 +246,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -240,48 +263,51 @@ def operations_client(self): raise NotImplementedError() @property - def list_instances(self) -> Callable[ - [cloud_redis.ListInstancesRequest], - Union[ - cloud_redis.ListInstancesResponse, - Awaitable[cloud_redis.ListInstancesResponse] - ]]: + def list_instances( + self, + ) -> Callable[ + [cloud_redis.ListInstancesRequest], + Union[ + cloud_redis.ListInstancesResponse, + Awaitable[cloud_redis.ListInstancesResponse], + ], + ]: raise NotImplementedError() @property - def get_instance(self) -> Callable[ - [cloud_redis.GetInstanceRequest], - Union[ - cloud_redis.Instance, - Awaitable[cloud_redis.Instance] - ]]: + def get_instance( + self, + ) -> Callable[ + [cloud_redis.GetInstanceRequest], + Union[cloud_redis.Instance, Awaitable[cloud_redis.Instance]], + ]: raise NotImplementedError() @property - def create_instance(self) -> Callable[ - [cloud_redis.CreateInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_instance( + self, + ) -> Callable[ + [cloud_redis.CreateInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_instance(self) -> Callable[ - [cloud_redis.UpdateInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_instance( + self, + ) -> Callable[ + [cloud_redis.UpdateInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_instance(self) -> Callable[ - [cloud_redis.DeleteInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_instance( + self, + ) -> Callable[ + [cloud_redis.DeleteInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property @@ -289,7 +315,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -330,7 +359,8 @@ def wait_operation( raise NotImplementedError() @property - def get_location(self, + def get_location( + self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -338,10 +368,14 @@ def get_location(self, raise NotImplementedError() @property - def list_locations(self, + def list_locations( + self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], ]: raise NotImplementedError() @@ -350,6 +384,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'CloudRedisTransport', -) +__all__ = ("CloudRedisTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index 17812fecc84d..3af833da0007 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -17,17 +17,19 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -from google.api_core import operations_v1 + from google.api_core.grpc_helpers import ( + ClientInterceptor, # type: ignore[attr-defined] + ) from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 + # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -35,21 +37,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore +import google.auth # type: ignore +import google.protobuf.message +import proto # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.redis_v1.types import cloud_redis +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import proto # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore -from .base import CloudRedisTransport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, CloudRedisTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -59,7 +61,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -80,7 +84,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -91,7 +95,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -106,7 +114,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": client_call_details.method, "response": grpc_response, @@ -148,32 +156,35 @@ class CloudRedisGrpcTransport(CloudRedisTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'redis.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], - ] + def __init__( + self, + *, + host: str = "redis.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -310,8 +321,17 @@ def __init__(self, *, channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None and otel_interceptor not in channel_interceptors + and not any( + getattr(i, "_is_otel_interceptor", None) is True + for i in channel_interceptors + ) ): channel_interceptors.append(otel_interceptor) @@ -320,22 +340,28 @@ def __init__(self, *, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) + self._grpc_channel = apply_interceptors( + self._grpc_channel, channel_interceptors + ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'redis.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "redis.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -371,13 +397,12 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property @@ -397,9 +422,11 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def list_instances(self) -> Callable[ - [cloud_redis.ListInstancesRequest], - cloud_redis.ListInstancesResponse]: + def list_instances( + self, + ) -> Callable[ + [cloud_redis.ListInstancesRequest], cloud_redis.ListInstancesResponse + ]: r"""Return a callable for the list instances method over gRPC. Lists all Redis instances owned by a project in either the @@ -423,18 +450,18 @@ def list_instances(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_instances' not in self._stubs: - self._stubs['list_instances'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/ListInstances', + if "list_instances" not in self._stubs: + self._stubs["list_instances"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/ListInstances", request_serializer=cloud_redis.ListInstancesRequest.serialize, response_deserializer=cloud_redis.ListInstancesResponse.deserialize, ) - return self._stubs['list_instances'] + return self._stubs["list_instances"] @property - def get_instance(self) -> Callable[ - [cloud_redis.GetInstanceRequest], - cloud_redis.Instance]: + def get_instance( + self, + ) -> Callable[[cloud_redis.GetInstanceRequest], cloud_redis.Instance]: r"""Return a callable for the get instance method over gRPC. Gets the details of a specific Redis instance. @@ -449,18 +476,18 @@ def get_instance(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_instance' not in self._stubs: - self._stubs['get_instance'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/GetInstance', + if "get_instance" not in self._stubs: + self._stubs["get_instance"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/GetInstance", request_serializer=cloud_redis.GetInstanceRequest.serialize, response_deserializer=cloud_redis.Instance.deserialize, ) - return self._stubs['get_instance'] + return self._stubs["get_instance"] @property - def create_instance(self) -> Callable[ - [cloud_redis.CreateInstanceRequest], - operations_pb2.Operation]: + def create_instance( + self, + ) -> Callable[[cloud_redis.CreateInstanceRequest], operations_pb2.Operation]: r"""Return a callable for the create instance method over gRPC. Creates a Redis instance based on the specified tier and memory @@ -488,18 +515,18 @@ def create_instance(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_instance' not in self._stubs: - self._stubs['create_instance'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/CreateInstance', + if "create_instance" not in self._stubs: + self._stubs["create_instance"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/CreateInstance", request_serializer=cloud_redis.CreateInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_instance'] + return self._stubs["create_instance"] @property - def update_instance(self) -> Callable[ - [cloud_redis.UpdateInstanceRequest], - operations_pb2.Operation]: + def update_instance( + self, + ) -> Callable[[cloud_redis.UpdateInstanceRequest], operations_pb2.Operation]: r"""Return a callable for the update instance method over gRPC. Updates the metadata and configuration of a specific @@ -519,18 +546,18 @@ def update_instance(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_instance' not in self._stubs: - self._stubs['update_instance'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/UpdateInstance', + if "update_instance" not in self._stubs: + self._stubs["update_instance"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/UpdateInstance", request_serializer=cloud_redis.UpdateInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_instance'] + return self._stubs["update_instance"] @property - def delete_instance(self) -> Callable[ - [cloud_redis.DeleteInstanceRequest], - operations_pb2.Operation]: + def delete_instance( + self, + ) -> Callable[[cloud_redis.DeleteInstanceRequest], operations_pb2.Operation]: r"""Return a callable for the delete instance method over gRPC. Deletes a specific Redis instance. Instance stops @@ -546,13 +573,13 @@ def delete_instance(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_instance' not in self._stubs: - self._stubs['delete_instance'] = self._logged_channel.unary_unary( - '/google.cloud.redis.v1.CloudRedis/DeleteInstance', + if "delete_instance" not in self._stubs: + self._stubs["delete_instance"] = self._logged_channel.unary_unary( + "/google.cloud.redis.v1.CloudRedis/DeleteInstance", request_serializer=cloud_redis.DeleteInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_instance'] + return self._stubs["delete_instance"] def close(self): self._logged_channel.close() @@ -561,8 +588,7 @@ def close(self): def delete_operation( self, ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ + r"""Return a callable for the delete_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -579,8 +605,7 @@ def delete_operation( def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -597,8 +622,7 @@ def cancel_operation( def wait_operation( self, ) -> Callable[[operations_pb2.WaitOperationRequest], None]: - r"""Return a callable for the wait_operation method over gRPC. - """ + r"""Return a callable for the wait_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -615,8 +639,7 @@ def wait_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -632,9 +655,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -650,9 +674,10 @@ def list_operations( @property def list_locations( self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -669,8 +694,7 @@ def list_locations( def get_location( self, ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -688,6 +712,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'CloudRedisGrpcTransport', -) +__all__ = ("CloudRedisGrpcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py index de2135721571..4ef4e9304d0e 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py @@ -13,31 +13,48 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import inspect import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import uuid import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.cloud.storagebatchoperations_v1 import gapic_version as package_version - +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.storagebatchoperations_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables -from google.cloud.storagebatchoperations_v1._compat import setup_request_id from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.storagebatchoperations_v1 import gapic_version as package_version +from google.cloud.storagebatchoperations_v1._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + setup_request_id, + should_use_client_cert, +) +from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +63,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -59,15 +77,20 @@ _LOGGER = std_logging.getLogger(__name__) -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.storagebatchoperations_v1.services.storage_batch_operations import pagers -from google.cloud.storagebatchoperations_v1.types import storage_batch_operations -from google.cloud.storagebatchoperations_v1.types import storage_batch_operations_types -from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import StorageBatchOperationsTransport, DEFAULT_CLIENT_INFO +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.storagebatchoperations_v1.services.storage_batch_operations import ( + pagers, +) +from google.cloud.storagebatchoperations_v1.types import ( + storage_batch_operations, + storage_batch_operations_types, +) +from google.longrunning import operations_pb2 # type: ignore + +from .transports.base import DEFAULT_CLIENT_INFO, StorageBatchOperationsTransport from .transports.grpc import StorageBatchOperationsGrpcTransport from .transports.grpc_asyncio import StorageBatchOperationsGrpcAsyncIOTransport from .transports.rest import StorageBatchOperationsRestTransport @@ -80,14 +103,16 @@ class StorageBatchOperationsClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[StorageBatchOperationsTransport]] _transport_registry["grpc"] = StorageBatchOperationsGrpcTransport _transport_registry["grpc_asyncio"] = StorageBatchOperationsGrpcAsyncIOTransport _transport_registry["rest"] = StorageBatchOperationsRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[StorageBatchOperationsTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[StorageBatchOperationsTransport]: """Returns an appropriate transport class. Args: @@ -152,8 +177,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: StorageBatchOperationsClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -170,95 +194,156 @@ def transport(self) -> StorageBatchOperationsTransport: return self._transport @staticmethod - def bucket_operation_path(project: str,location: str,job: str,bucket_operation: str,) -> str: + def bucket_operation_path( + project: str, + location: str, + job: str, + bucket_operation: str, + ) -> str: """Returns a fully-qualified bucket_operation string.""" - return "projects/{project}/locations/{location}/jobs/{job}/bucketOperations/{bucket_operation}".format(project=project, location=location, job=job, bucket_operation=bucket_operation, ) + return "projects/{project}/locations/{location}/jobs/{job}/bucketOperations/{bucket_operation}".format( + project=project, + location=location, + job=job, + bucket_operation=bucket_operation, + ) @staticmethod - def parse_bucket_operation_path(path: str) -> Dict[str,str]: + def parse_bucket_operation_path(path: str) -> Dict[str, str]: """Parses a bucket_operation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)/bucketOperations/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)/bucketOperations/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: + def crypto_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + ) -> str: """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str,str]: + def parse_crypto_key_path(path: str) -> Dict[str, str]: """Parses a crypto_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def job_path(project: str,location: str,job: str,) -> str: + def job_path( + project: str, + location: str, + job: str, + ) -> str: """Returns a fully-qualified job string.""" - return "projects/{project}/locations/{location}/jobs/{job}".format(project=project, location=location, job=job, ) + return "projects/{project}/locations/{location}/jobs/{job}".format( + project=project, + location=location, + job=job, + ) @staticmethod - def parse_job_path(path: str) -> Dict[str,str]: + def parse_job_path(path: str) -> Dict[str, str]: """Parses a job path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -290,14 +375,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -310,8 +399,10 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -350,15 +441,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -391,12 +485,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, StorageBatchOperationsTransport, Callable[..., StorageBatchOperationsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + StorageBatchOperationsTransport, + Callable[..., StorageBatchOperationsTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the storage batch operations client. Args: @@ -454,13 +556,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = StorageBatchOperationsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=StorageBatchOperationsClient._DEFAULT_UNIVERSE) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = StorageBatchOperationsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=StorageBatchOperationsClient._DEFAULT_UNIVERSE, + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -472,7 +584,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -481,35 +595,41 @@ def __init__(self, *, if transport_provided: # transport is a StorageBatchOperationsTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." + "When providing a transport instance, provide its scopes directly." ) self._transport = cast(StorageBatchOperationsTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=StorageBatchOperationsClient._DEFAULT_UNIVERSE, - default_mtls_endpoint=StorageBatchOperationsClient.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=StorageBatchOperationsClient._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" or ( - self._use_mtls_endpoint == "auto" and self._client_cert_source - ), - )) + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=StorageBatchOperationsClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=StorageBatchOperationsClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=StorageBatchOperationsClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[StorageBatchOperationsTransport], Callable[..., StorageBatchOperationsTransport]] = ( + transport_init: Union[ + Type[StorageBatchOperationsTransport], + Callable[..., StorageBatchOperationsTransport], + ] = ( StorageBatchOperationsClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., StorageBatchOperationsTransport], transport) @@ -538,33 +658,46 @@ def __init__(self, *, "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **({"client_options": client_options} if client_options else {}), + **( + {"client_options": client_options} + if client_options is not None + else {} + ), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient`.", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "credentialsType": None, - } + }, ) - def list_jobs(self, - request: Optional[Union[storage_batch_operations.ListJobsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListJobsPager: + def list_jobs( + self, + request: Optional[Union[storage_batch_operations.ListJobsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListJobsPager: r"""Lists Jobs in a given project. .. code-block:: python @@ -625,10 +758,14 @@ def sample_list_jobs(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -646,9 +783,7 @@ def sample_list_jobs(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -676,14 +811,15 @@ def sample_list_jobs(): # Done; return the response. return response - def get_job(self, - request: Optional[Union[storage_batch_operations.GetJobRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_batch_operations_types.Job: + def get_job( + self, + request: Optional[Union[storage_batch_operations.GetJobRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations_types.Job: r"""Gets a batch job. .. code-block:: python @@ -740,10 +876,14 @@ def sample_get_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -761,9 +901,7 @@ def sample_get_job(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -780,16 +918,19 @@ def sample_get_job(): # Done; return the response. return response - def create_job(self, - request: Optional[Union[storage_batch_operations.CreateJobRequest, dict]] = None, - *, - parent: Optional[str] = None, - job: Optional[storage_batch_operations_types.Job] = None, - job_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_job( + self, + request: Optional[ + Union[storage_batch_operations.CreateJobRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + job: Optional[storage_batch_operations_types.Job] = None, + job_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a batch job. .. code-block:: python @@ -873,10 +1014,14 @@ def sample_create_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, job, job_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -898,12 +1043,10 @@ def sample_create_job(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) - setup_request_id(request, 'request_id', False) + setup_request_id(request, "request_id", False) # Validate the universe domain. self._validate_universe_domain() @@ -927,14 +1070,17 @@ def sample_create_job(): # Done; return the response. return response - def delete_job(self, - request: Optional[Union[storage_batch_operations.DeleteJobRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_job( + self, + request: Optional[ + Union[storage_batch_operations.DeleteJobRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a batch job. .. code-block:: python @@ -982,10 +1128,14 @@ def sample_delete_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1003,12 +1153,10 @@ def sample_delete_job(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) - setup_request_id(request, 'request_id', False) + setup_request_id(request, "request_id", False) # Validate the universe domain. self._validate_universe_domain() @@ -1021,14 +1169,17 @@ def sample_delete_job(): metadata=metadata, ) - def cancel_job(self, - request: Optional[Union[storage_batch_operations.CancelJobRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_batch_operations.CancelJobResponse: + def cancel_job( + self, + request: Optional[ + Union[storage_batch_operations.CancelJobRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations.CancelJobResponse: r"""Cancels a batch job. .. code-block:: python @@ -1083,10 +1234,14 @@ def sample_cancel_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1104,12 +1259,10 @@ def sample_cancel_job(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) - setup_request_id(request, 'request_id', False) + setup_request_id(request, "request_id", False) # Validate the universe domain. self._validate_universe_domain() @@ -1125,14 +1278,17 @@ def sample_cancel_job(): # Done; return the response. return response - def list_bucket_operations(self, - request: Optional[Union[storage_batch_operations.ListBucketOperationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBucketOperationsPager: + def list_bucket_operations( + self, + request: Optional[ + Union[storage_batch_operations.ListBucketOperationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketOperationsPager: r"""Lists BucketOperations in a given project and job. .. code-block:: python @@ -1194,14 +1350,20 @@ def sample_list_bucket_operations(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, storage_batch_operations.ListBucketOperationsRequest): + if not isinstance( + request, storage_batch_operations.ListBucketOperationsRequest + ): request = storage_batch_operations.ListBucketOperationsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -1215,9 +1377,7 @@ def sample_list_bucket_operations(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1245,14 +1405,17 @@ def sample_list_bucket_operations(): # Done; return the response. return response - def get_bucket_operation(self, - request: Optional[Union[storage_batch_operations.GetBucketOperationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_batch_operations_types.BucketOperation: + def get_bucket_operation( + self, + request: Optional[ + Union[storage_batch_operations.GetBucketOperationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations_types.BucketOperation: r"""Gets a BucketOperation. .. code-block:: python @@ -1311,10 +1474,14 @@ def sample_get_bucket_operation(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1332,9 +1499,7 @@ def sample_get_bucket_operation(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1406,8 +1571,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1416,7 +1580,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1466,8 +1634,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1476,7 +1643,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1530,15 +1701,19 @@ def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def cancel_operation( self, @@ -1585,15 +1760,19 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def get_location( self, @@ -1637,8 +1816,7 @@ def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1647,7 +1825,11 @@ def get_location( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1697,8 +1879,7 @@ def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1707,7 +1888,11 @@ def list_locations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1716,9 +1901,9 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "StorageBatchOperationsClient", -) +__all__ = ("StorageBatchOperationsClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py index f7b33ea11619..f5c35519a8ef 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py @@ -17,51 +17,58 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.storagebatchoperations_v1 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.storagebatchoperations_v1.types import storage_batch_operations -from google.cloud.storagebatchoperations_v1.types import storage_batch_operations_types -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.storagebatchoperations_v1 import gapic_version as package_version +from google.cloud.storagebatchoperations_v1.types import ( + storage_batch_operations, + storage_batch_operations_types, +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +# Check once at module load time whether google-api-core's wrap_method supports +# OpenTelemetry tracing arguments (client_options, method_name, is_streaming, kind) +# to avoid recurring inspect.signature latency during client instantiation. +_WRAP_METHOD_SUPPORTS_TRACING = ( + "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters +) + class StorageBatchOperationsTransport(abc.ABC): """Abstract transport class for StorageBatchOperations.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'storagebatchoperations.googleapis.com' + DEFAULT_HOST: str = "storagebatchoperations.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -103,38 +110,47 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._client_options = client_options - # Check whether google-api-core's wrap_method supports OpenTelemetry tracing arguments - # (such as client_options, method_name, is_streaming, kind) to ensure backward compatibility - # with older versions of google-api-core. - self._wrap_with_tracing = "client_options" in inspect.signature(gapic_v1.method.wrap_method).parameters + self._wrap_with_tracing = _WRAP_METHOD_SUPPORTS_TRACING self._wrapped_methods: Dict[Callable, Callable] = {} @@ -147,15 +163,24 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["client_options"] = self._client_options try: kwargs["kind"] = self.kind - # Base transport raises NotImplementedError for abstract kind property. - # Concrete transport subclasses override kind, so this branch is unreachable during live calls. + # The abstract BaseTransport class raises NotImplementedError for the kind property. + # Concrete transport subclasses (gRPC, REST) override kind, so this exception handler + # is unreachable during normal execution. Excluded from coverage check. except NotImplementedError: # pragma: NO COVER pass return gapic_v1.method.wrap_method(func, *args, **kwargs) - # Remove tracing-specific arguments if older google-api-core is installed - for k in ["client_options", "method_name", "is_streaming", "kind"]: - kwargs.pop(k, None) - return gapic_v1.method.wrap_method(func, *args, **kwargs) + # The fallback below strips tracing-specific arguments when an older version + # of google-api-core is installed (which does not accept client_options, etc.). + # Excluded from coverage because our CI and testing environments always install + # a modern version of google-api-core that supports tracing. + for k in [ + "client_options", + "method_name", + "is_streaming", + "kind", + ]: # pragma: NO COVER + kwargs.pop(k, None) # pragma: NO COVER + return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -277,14 +302,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -294,66 +319,81 @@ def operations_client(self): raise NotImplementedError() @property - def list_jobs(self) -> Callable[ - [storage_batch_operations.ListJobsRequest], - Union[ - storage_batch_operations.ListJobsResponse, - Awaitable[storage_batch_operations.ListJobsResponse] - ]]: + def list_jobs( + self, + ) -> Callable[ + [storage_batch_operations.ListJobsRequest], + Union[ + storage_batch_operations.ListJobsResponse, + Awaitable[storage_batch_operations.ListJobsResponse], + ], + ]: raise NotImplementedError() @property - def get_job(self) -> Callable[ - [storage_batch_operations.GetJobRequest], - Union[ - storage_batch_operations_types.Job, - Awaitable[storage_batch_operations_types.Job] - ]]: + def get_job( + self, + ) -> Callable[ + [storage_batch_operations.GetJobRequest], + Union[ + storage_batch_operations_types.Job, + Awaitable[storage_batch_operations_types.Job], + ], + ]: raise NotImplementedError() @property - def create_job(self) -> Callable[ - [storage_batch_operations.CreateJobRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_job( + self, + ) -> Callable[ + [storage_batch_operations.CreateJobRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_job(self) -> Callable[ - [storage_batch_operations.DeleteJobRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_job( + self, + ) -> Callable[ + [storage_batch_operations.DeleteJobRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def cancel_job(self) -> Callable[ - [storage_batch_operations.CancelJobRequest], - Union[ - storage_batch_operations.CancelJobResponse, - Awaitable[storage_batch_operations.CancelJobResponse] - ]]: + def cancel_job( + self, + ) -> Callable[ + [storage_batch_operations.CancelJobRequest], + Union[ + storage_batch_operations.CancelJobResponse, + Awaitable[storage_batch_operations.CancelJobResponse], + ], + ]: raise NotImplementedError() @property - def list_bucket_operations(self) -> Callable[ - [storage_batch_operations.ListBucketOperationsRequest], - Union[ - storage_batch_operations.ListBucketOperationsResponse, - Awaitable[storage_batch_operations.ListBucketOperationsResponse] - ]]: + def list_bucket_operations( + self, + ) -> Callable[ + [storage_batch_operations.ListBucketOperationsRequest], + Union[ + storage_batch_operations.ListBucketOperationsResponse, + Awaitable[storage_batch_operations.ListBucketOperationsResponse], + ], + ]: raise NotImplementedError() @property - def get_bucket_operation(self) -> Callable[ - [storage_batch_operations.GetBucketOperationRequest], - Union[ - storage_batch_operations_types.BucketOperation, - Awaitable[storage_batch_operations_types.BucketOperation] - ]]: + def get_bucket_operation( + self, + ) -> Callable[ + [storage_batch_operations.GetBucketOperationRequest], + Union[ + storage_batch_operations_types.BucketOperation, + Awaitable[storage_batch_operations_types.BucketOperation], + ], + ]: raise NotImplementedError() @property @@ -361,7 +401,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -393,7 +436,8 @@ def delete_operation( raise NotImplementedError() @property - def get_location(self, + def get_location( + self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -401,10 +445,14 @@ def get_location(self, raise NotImplementedError() @property - def list_locations(self, + def list_locations( + self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], ]: raise NotImplementedError() @@ -413,6 +461,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'StorageBatchOperationsTransport', -) +__all__ = ("StorageBatchOperationsTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py index bf4260682085..3a6416a2bf31 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py @@ -17,17 +17,19 @@ import logging as std_logging import pickle import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] -from google.api_core import operations_v1 + from google.api_core.grpc_helpers import ( + ClientInterceptor, # type: ignore[attr-defined] + ) from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 + # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -35,23 +37,25 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import proto # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.storagebatchoperations_v1.types import ( + storage_batch_operations, + storage_batch_operations_types, +) +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import proto # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.storagebatchoperations_v1.types import storage_batch_operations -from google.cloud.storagebatchoperations_v1.types import storage_batch_operations_types -from google.longrunning import operations_pb2 # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -from .base import StorageBatchOperationsTransport, DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO, StorageBatchOperationsTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -61,7 +65,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -82,7 +88,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -93,7 +99,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -108,7 +118,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": client_call_details.method, "response": grpc_response, @@ -134,32 +144,35 @@ class StorageBatchOperationsGrpcTransport(StorageBatchOperationsTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'storagebatchoperations.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], - ] + def __init__( + self, + *, + host: str = "storagebatchoperations.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -296,8 +309,17 @@ def __init__(self, *, channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None + and ( + otel_interceptor := _observability.get_otel_interceptor( + self._client_options + ) + ) + is not None and otel_interceptor not in channel_interceptors + and not any( + getattr(i, "_is_otel_interceptor", None) is True + for i in channel_interceptors + ) ): channel_interceptors.append(otel_interceptor) @@ -306,22 +328,28 @@ def __init__(self, *, "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) + self._grpc_channel = apply_interceptors( + self._grpc_channel, channel_interceptors + ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'storagebatchoperations.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "storagebatchoperations.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -357,13 +385,12 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property @@ -383,9 +410,12 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def list_jobs(self) -> Callable[ - [storage_batch_operations.ListJobsRequest], - storage_batch_operations.ListJobsResponse]: + def list_jobs( + self, + ) -> Callable[ + [storage_batch_operations.ListJobsRequest], + storage_batch_operations.ListJobsResponse, + ]: r"""Return a callable for the list jobs method over gRPC. Lists Jobs in a given project. @@ -400,18 +430,20 @@ def list_jobs(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_jobs' not in self._stubs: - self._stubs['list_jobs'] = self._logged_channel.unary_unary( - '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/ListJobs', + if "list_jobs" not in self._stubs: + self._stubs["list_jobs"] = self._logged_channel.unary_unary( + "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/ListJobs", request_serializer=storage_batch_operations.ListJobsRequest.serialize, response_deserializer=storage_batch_operations.ListJobsResponse.deserialize, ) - return self._stubs['list_jobs'] + return self._stubs["list_jobs"] @property - def get_job(self) -> Callable[ - [storage_batch_operations.GetJobRequest], - storage_batch_operations_types.Job]: + def get_job( + self, + ) -> Callable[ + [storage_batch_operations.GetJobRequest], storage_batch_operations_types.Job + ]: r"""Return a callable for the get job method over gRPC. Gets a batch job. @@ -426,18 +458,20 @@ def get_job(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_job' not in self._stubs: - self._stubs['get_job'] = self._logged_channel.unary_unary( - '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/GetJob', + if "get_job" not in self._stubs: + self._stubs["get_job"] = self._logged_channel.unary_unary( + "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/GetJob", request_serializer=storage_batch_operations.GetJobRequest.serialize, response_deserializer=storage_batch_operations_types.Job.deserialize, ) - return self._stubs['get_job'] + return self._stubs["get_job"] @property - def create_job(self) -> Callable[ - [storage_batch_operations.CreateJobRequest], - operations_pb2.Operation]: + def create_job( + self, + ) -> Callable[ + [storage_batch_operations.CreateJobRequest], operations_pb2.Operation + ]: r"""Return a callable for the create job method over gRPC. Creates a batch job. @@ -452,18 +486,18 @@ def create_job(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_job' not in self._stubs: - self._stubs['create_job'] = self._logged_channel.unary_unary( - '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/CreateJob', + if "create_job" not in self._stubs: + self._stubs["create_job"] = self._logged_channel.unary_unary( + "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/CreateJob", request_serializer=storage_batch_operations.CreateJobRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_job'] + return self._stubs["create_job"] @property - def delete_job(self) -> Callable[ - [storage_batch_operations.DeleteJobRequest], - empty_pb2.Empty]: + def delete_job( + self, + ) -> Callable[[storage_batch_operations.DeleteJobRequest], empty_pb2.Empty]: r"""Return a callable for the delete job method over gRPC. Deletes a batch job. @@ -478,18 +512,21 @@ def delete_job(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_job' not in self._stubs: - self._stubs['delete_job'] = self._logged_channel.unary_unary( - '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/DeleteJob', + if "delete_job" not in self._stubs: + self._stubs["delete_job"] = self._logged_channel.unary_unary( + "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/DeleteJob", request_serializer=storage_batch_operations.DeleteJobRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_job'] + return self._stubs["delete_job"] @property - def cancel_job(self) -> Callable[ - [storage_batch_operations.CancelJobRequest], - storage_batch_operations.CancelJobResponse]: + def cancel_job( + self, + ) -> Callable[ + [storage_batch_operations.CancelJobRequest], + storage_batch_operations.CancelJobResponse, + ]: r"""Return a callable for the cancel job method over gRPC. Cancels a batch job. @@ -504,18 +541,21 @@ def cancel_job(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'cancel_job' not in self._stubs: - self._stubs['cancel_job'] = self._logged_channel.unary_unary( - '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/CancelJob', + if "cancel_job" not in self._stubs: + self._stubs["cancel_job"] = self._logged_channel.unary_unary( + "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/CancelJob", request_serializer=storage_batch_operations.CancelJobRequest.serialize, response_deserializer=storage_batch_operations.CancelJobResponse.deserialize, ) - return self._stubs['cancel_job'] + return self._stubs["cancel_job"] @property - def list_bucket_operations(self) -> Callable[ - [storage_batch_operations.ListBucketOperationsRequest], - storage_batch_operations.ListBucketOperationsResponse]: + def list_bucket_operations( + self, + ) -> Callable[ + [storage_batch_operations.ListBucketOperationsRequest], + storage_batch_operations.ListBucketOperationsResponse, + ]: r"""Return a callable for the list bucket operations method over gRPC. Lists BucketOperations in a given project and job. @@ -530,18 +570,21 @@ def list_bucket_operations(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_bucket_operations' not in self._stubs: - self._stubs['list_bucket_operations'] = self._logged_channel.unary_unary( - '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/ListBucketOperations', + if "list_bucket_operations" not in self._stubs: + self._stubs["list_bucket_operations"] = self._logged_channel.unary_unary( + "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/ListBucketOperations", request_serializer=storage_batch_operations.ListBucketOperationsRequest.serialize, response_deserializer=storage_batch_operations.ListBucketOperationsResponse.deserialize, ) - return self._stubs['list_bucket_operations'] + return self._stubs["list_bucket_operations"] @property - def get_bucket_operation(self) -> Callable[ - [storage_batch_operations.GetBucketOperationRequest], - storage_batch_operations_types.BucketOperation]: + def get_bucket_operation( + self, + ) -> Callable[ + [storage_batch_operations.GetBucketOperationRequest], + storage_batch_operations_types.BucketOperation, + ]: r"""Return a callable for the get bucket operation method over gRPC. Gets a BucketOperation. @@ -556,13 +599,13 @@ def get_bucket_operation(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_bucket_operation' not in self._stubs: - self._stubs['get_bucket_operation'] = self._logged_channel.unary_unary( - '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/GetBucketOperation', + if "get_bucket_operation" not in self._stubs: + self._stubs["get_bucket_operation"] = self._logged_channel.unary_unary( + "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/GetBucketOperation", request_serializer=storage_batch_operations.GetBucketOperationRequest.serialize, response_deserializer=storage_batch_operations_types.BucketOperation.deserialize, ) - return self._stubs['get_bucket_operation'] + return self._stubs["get_bucket_operation"] def close(self): self._logged_channel.close() @@ -571,8 +614,7 @@ def close(self): def delete_operation( self, ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ + r"""Return a callable for the delete_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -589,8 +631,7 @@ def delete_operation( def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -607,8 +648,7 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -624,9 +664,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -642,9 +683,10 @@ def list_operations( @property def list_locations( self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -661,8 +703,7 @@ def list_locations( def get_location( self, ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -680,6 +721,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'StorageBatchOperationsGrpcTransport', -) +__all__ = ("StorageBatchOperationsGrpcTransport",) From d53607b99c489541a377f202bd9b7a83e890a805 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 16 Sep 2026 16:34:31 -0400 Subject: [PATCH 39/43] fix(ci): synchronize goldens with bazel generator and align with main --- .../asset_v1/services/asset_service/client.py | 1061 ++++----- .../services/asset_service/transports/base.py | 419 ++-- .../services/asset_service/transports/grpc.py | 512 ++--- .../services/iam_credentials/client.py | 420 ++-- .../iam_credentials/transports/base.py | 151 +- .../iam_credentials/transports/grpc.py | 181 +- .../eventarc_v1/services/eventarc/client.py | 1966 +++++++---------- .../services/eventarc/transports/base.py | 650 +++--- .../services/eventarc/transports/grpc.py | 767 +++---- .../services/config_service_v2/client.py | 1242 +++++------ .../config_service_v2/transports/base.py | 513 ++--- .../config_service_v2/transports/grpc.py | 601 +++-- .../services/logging_service_v2/client.py | 471 ++-- .../logging_service_v2/transports/base.py | 193 +- .../logging_service_v2/transports/grpc.py | 235 +- .../services/metrics_service_v2/client.py | 471 ++-- .../metrics_service_v2/transports/base.py | 176 +- .../metrics_service_v2/transports/grpc.py | 216 +- .../services/config_service_v2/client.py | 1242 +++++------ .../config_service_v2/transports/base.py | 513 ++--- .../config_service_v2/transports/grpc.py | 601 +++-- .../services/logging_service_v2/client.py | 471 ++-- .../logging_service_v2/transports/base.py | 193 +- .../logging_service_v2/transports/grpc.py | 235 +- .../services/metrics_service_v2/client.py | 471 ++-- .../metrics_service_v2/transports/base.py | 176 +- .../metrics_service_v2/transports/grpc.py | 216 +- .../redis_v1/services/cloud_redis/client.py | 724 +++--- .../services/cloud_redis/transports/base.py | 258 +-- .../services/cloud_redis/transports/grpc.py | 321 ++- .../redis_v1/services/cloud_redis/client.py | 522 ++--- .../services/cloud_redis/transports/base.py | 184 +- .../services/cloud_redis/transports/grpc.py | 235 +- .../storage_batch_operations/client.py | 631 ++---- .../transports/base.py | 228 +- .../transports/grpc.py | 280 +-- .../google/cloud/bigquery/client.py | 10 +- .../google/cloud/bigquery/table.py | 37 +- packages/google-cloud-bigquery/noxfile.py | 2 +- .../tests/unit/test_client.py | 45 +- .../tests/unit/test_table.py | 98 +- .../.cross_sync/generate.py | 14 +- 42 files changed, 7523 insertions(+), 10429 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py index 1fdf9ebd494c..cc1b47b9cb95 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py @@ -13,46 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import inspect import json import logging as std_logging import os import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings -from collections import OrderedDict -from http import HTTPStatus -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import google.protobuf +from google.cloud.asset_v1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 +from google.cloud.asset_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.asset_v1 import gapic_version as package_version -from google.cloud.asset_v1._compat import ( - get_api_endpoint, - get_default_mtls_endpoint, - get_universe_domain, - read_environment_variables, - should_use_client_cert, -) -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -61,7 +44,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -75,17 +57,17 @@ _LOGGER = std_logging.getLogger(__name__) +from google.cloud.asset_v1.services.asset_service import pagers +from google.cloud.asset_v1.types import asset_service +from google.cloud.asset_v1.types import assets +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.rpc.status_pb2 as status_pb2 # type: ignore import google.type.expr_pb2 as expr_pb2 # type: ignore -from google.cloud.asset_v1.services.asset_service import pagers -from google.cloud.asset_v1.types import asset_service, assets -from google.longrunning import operations_pb2 # type: ignore - -from .transports.base import DEFAULT_CLIENT_INFO, AssetServiceTransport +from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetServiceGrpcTransport from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport from .transports.rest import AssetServiceRestTransport @@ -98,16 +80,14 @@ class AssetServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] _transport_registry["grpc"] = AssetServiceGrpcTransport _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport _transport_registry["rest"] = AssetServiceRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[AssetServiceTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AssetServiceTransport]: """Returns an appropriate transport class. Args: @@ -167,7 +147,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetServiceClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -184,36 +165,23 @@ def transport(self) -> AssetServiceTransport: return self._transport @staticmethod - def access_level_path( - access_policy: str, - access_level: str, - ) -> str: + def access_level_path(access_policy: str,access_level: str,) -> str: """Returns a fully-qualified access_level string.""" - return "accessPolicies/{access_policy}/accessLevels/{access_level}".format( - access_policy=access_policy, - access_level=access_level, - ) + return "accessPolicies/{access_policy}/accessLevels/{access_level}".format(access_policy=access_policy, access_level=access_level, ) @staticmethod - def parse_access_level_path(path: str) -> Dict[str, str]: + def parse_access_level_path(path: str) -> Dict[str,str]: """Parses a access_level path into its component segments.""" - m = re.match( - r"^accessPolicies/(?P.+?)/accessLevels/(?P.+?)$", - path, - ) + m = re.match(r"^accessPolicies/(?P.+?)/accessLevels/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def access_policy_path( - access_policy: str, - ) -> str: + def access_policy_path(access_policy: str,) -> str: """Returns a fully-qualified access_policy string.""" - return "accessPolicies/{access_policy}".format( - access_policy=access_policy, - ) + return "accessPolicies/{access_policy}".format(access_policy=access_policy, ) @staticmethod - def parse_access_policy_path(path: str) -> Dict[str, str]: + def parse_access_policy_path(path: str) -> Dict[str,str]: """Parses a access_policy path into its component segments.""" m = re.match(r"^accessPolicies/(?P.+?)$", path) return m.groupdict() if m else {} @@ -224,170 +192,112 @@ def asset_path() -> str: return "*".format() @staticmethod - def parse_asset_path(path: str) -> Dict[str, str]: + def parse_asset_path(path: str) -> Dict[str,str]: """Parses a asset path into its component segments.""" m = re.match(r"^.*$", path) return m.groupdict() if m else {} @staticmethod - def feed_path( - project: str, - feed: str, - ) -> str: + def feed_path(project: str,feed: str,) -> str: """Returns a fully-qualified feed string.""" - return "projects/{project}/feeds/{feed}".format( - project=project, - feed=feed, - ) + return "projects/{project}/feeds/{feed}".format(project=project, feed=feed, ) @staticmethod - def parse_feed_path(path: str) -> Dict[str, str]: + def parse_feed_path(path: str) -> Dict[str,str]: """Parses a feed path into its component segments.""" m = re.match(r"^projects/(?P.+?)/feeds/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def inventory_path( - project: str, - location: str, - instance: str, - ) -> str: + def inventory_path(project: str,location: str,instance: str,) -> str: """Returns a fully-qualified inventory string.""" - return "projects/{project}/locations/{location}/instances/{instance}/inventory".format( - project=project, - location=location, - instance=instance, - ) + return "projects/{project}/locations/{location}/instances/{instance}/inventory".format(project=project, location=location, instance=instance, ) @staticmethod - def parse_inventory_path(path: str) -> Dict[str, str]: + def parse_inventory_path(path: str) -> Dict[str,str]: """Parses a inventory path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/inventory$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/inventory$", path) return m.groupdict() if m else {} @staticmethod - def saved_query_path( - project: str, - saved_query: str, - ) -> str: + def saved_query_path(project: str,saved_query: str,) -> str: """Returns a fully-qualified saved_query string.""" - return "projects/{project}/savedQueries/{saved_query}".format( - project=project, - saved_query=saved_query, - ) + return "projects/{project}/savedQueries/{saved_query}".format(project=project, saved_query=saved_query, ) @staticmethod - def parse_saved_query_path(path: str) -> Dict[str, str]: + def parse_saved_query_path(path: str) -> Dict[str,str]: """Parses a saved_query path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/savedQueries/(?P.+?)$", path - ) + m = re.match(r"^projects/(?P.+?)/savedQueries/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def service_perimeter_path( - access_policy: str, - service_perimeter: str, - ) -> str: + def service_perimeter_path(access_policy: str,service_perimeter: str,) -> str: """Returns a fully-qualified service_perimeter string.""" - return "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format( - access_policy=access_policy, - service_perimeter=service_perimeter, - ) + return "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format(access_policy=access_policy, service_perimeter=service_perimeter, ) @staticmethod - def parse_service_perimeter_path(path: str) -> Dict[str, str]: + def parse_service_perimeter_path(path: str) -> Dict[str,str]: """Parses a service_perimeter path into its component segments.""" - m = re.match( - r"^accessPolicies/(?P.+?)/servicePerimeters/(?P.+?)$", - path, - ) + m = re.match(r"^accessPolicies/(?P.+?)/servicePerimeters/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -419,18 +329,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -443,10 +349,8 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -485,18 +389,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -529,16 +430,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, AssetServiceTransport, Callable[..., AssetServiceTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AssetServiceTransport, Callable[..., AssetServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the asset service client. Args: @@ -596,23 +493,13 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - read_environment_variables() - ) - self._client_cert_source = AssetServiceClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = get_universe_domain( - universe_domain_opt, - self._universe_domain_env, - default_universe=AssetServiceClient._DEFAULT_UNIVERSE, - ) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() + self._client_cert_source = AssetServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=AssetServiceClient._DEFAULT_UNIVERSE) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -624,9 +511,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -635,40 +520,35 @@ def __init__( if transport_provided: # transport is a AssetServiceTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = cast(AssetServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = self._api_endpoint or get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=AssetServiceClient._DEFAULT_UNIVERSE, - default_mtls_endpoint=AssetServiceClient.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=AssetServiceClient._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" - or (self._use_mtls_endpoint == "auto" and self._client_cert_source), - ) + self._api_endpoint = (self._api_endpoint or + get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=AssetServiceClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=AssetServiceClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=AssetServiceClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" or ( + self._use_mtls_endpoint == "auto" and self._client_cert_source + ), + )) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[AssetServiceTransport], Callable[..., AssetServiceTransport] - ] = ( + transport_init: Union[Type[AssetServiceTransport], Callable[..., AssetServiceTransport]] = ( AssetServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., AssetServiceTransport], transport) @@ -697,45 +577,32 @@ def __init__( "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **( - {"client_options": client_options} - if client_options is not None - else {} - ), + **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.asset_v1.AssetServiceClient`.", - extra={ + extra = { "serviceName": "google.cloud.asset.v1.AssetService", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.cloud.asset.v1.AssetService", "credentialsType": None, - }, + } ) - def export_assets( - self, - request: Optional[Union[asset_service.ExportAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def export_assets(self, + request: Optional[Union[asset_service.ExportAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Exports assets with time and resource types to a given Cloud Storage location/BigQuery table. For Cloud Storage location destinations, the output format is newline-delimited JSON. Each @@ -819,7 +686,9 @@ def sample_export_assets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -844,15 +713,14 @@ def sample_export_assets(): # Done; return the response. return response - def list_assets( - self, - request: Optional[Union[asset_service.ListAssetsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAssetsPager: + def list_assets(self, + request: Optional[Union[asset_service.ListAssetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAssetsPager: r"""Lists assets with time and resource types and returns paged results in response. @@ -919,14 +787,10 @@ def sample_list_assets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -944,7 +808,9 @@ def sample_list_assets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -972,16 +838,13 @@ def sample_list_assets(): # Done; return the response. return response - def batch_get_assets_history( - self, - request: Optional[ - Union[asset_service.BatchGetAssetsHistoryRequest, dict] - ] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.BatchGetAssetsHistoryResponse: + def batch_get_assets_history(self, + request: Optional[Union[asset_service.BatchGetAssetsHistoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.BatchGetAssetsHistoryResponse: r"""Batch gets the update history of assets that overlap a time window. For IAM_POLICY content, this API outputs history when the asset and its attached IAM POLICY both exist. This can @@ -1044,7 +907,9 @@ def sample_batch_get_assets_history(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1061,15 +926,14 @@ def sample_batch_get_assets_history(): # Done; return the response. return response - def create_feed( - self, - request: Optional[Union[asset_service.CreateFeedRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.Feed: + def create_feed(self, + request: Optional[Union[asset_service.CreateFeedRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Creates a feed in a parent project/folder/organization to listen to its asset updates. @@ -1146,14 +1010,10 @@ def sample_create_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1171,7 +1031,9 @@ def sample_create_feed(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1188,15 +1050,14 @@ def sample_create_feed(): # Done; return the response. return response - def get_feed( - self, - request: Optional[Union[asset_service.GetFeedRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.Feed: + def get_feed(self, + request: Optional[Union[asset_service.GetFeedRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Gets details about an asset feed. .. code-block:: python @@ -1261,14 +1122,10 @@ def sample_get_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1286,7 +1143,9 @@ def sample_get_feed(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1303,15 +1162,14 @@ def sample_get_feed(): # Done; return the response. return response - def list_feeds( - self, - request: Optional[Union[asset_service.ListFeedsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.ListFeedsResponse: + def list_feeds(self, + request: Optional[Union[asset_service.ListFeedsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.ListFeedsResponse: r"""Lists all asset feeds in a parent project/folder/organization. @@ -1371,14 +1229,10 @@ def sample_list_feeds(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1396,7 +1250,9 @@ def sample_list_feeds(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1413,15 +1269,14 @@ def sample_list_feeds(): # Done; return the response. return response - def update_feed( - self, - request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, - *, - feed: Optional[asset_service.Feed] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.Feed: + def update_feed(self, + request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, + *, + feed: Optional[asset_service.Feed] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Updates an asset feed configuration. .. code-block:: python @@ -1490,14 +1345,10 @@ def sample_update_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [feed] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1515,9 +1366,9 @@ def sample_update_feed(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("feed.name", request.feed.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("feed.name", request.feed.name), + )), ) # Validate the universe domain. @@ -1534,15 +1385,14 @@ def sample_update_feed(): # Done; return the response. return response - def delete_feed( - self, - request: Optional[Union[asset_service.DeleteFeedRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_feed(self, + request: Optional[Union[asset_service.DeleteFeedRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes an asset feed. .. code-block:: python @@ -1592,14 +1442,10 @@ def sample_delete_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1617,7 +1463,9 @@ def sample_delete_feed(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1631,17 +1479,16 @@ def sample_delete_feed(): metadata=metadata, ) - def search_all_resources( - self, - request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - asset_types: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.SearchAllResourcesPager: + def search_all_resources(self, + request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + asset_types: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchAllResourcesPager: r"""Searches all Google Cloud resources within the specified scope, such as a project, folder, or organization. The caller must be granted the ``cloudasset.assets.searchAllResources`` permission @@ -1844,14 +1691,10 @@ def sample_search_all_resources(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, query, asset_types] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1873,7 +1716,9 @@ def sample_search_all_resources(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), ) # Validate the universe domain. @@ -1901,18 +1746,15 @@ def sample_search_all_resources(): # Done; return the response. return response - def search_all_iam_policies( - self, - request: Optional[ - Union[asset_service.SearchAllIamPoliciesRequest, dict] - ] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.SearchAllIamPoliciesPager: + def search_all_iam_policies(self, + request: Optional[Union[asset_service.SearchAllIamPoliciesRequest, dict]] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchAllIamPoliciesPager: r"""Searches all IAM policies within the specified scope, such as a project, folder, or organization. The caller must be granted the ``cloudasset.assets.searchAllIamPolicies`` permission on the @@ -2042,14 +1884,10 @@ def sample_search_all_iam_policies(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, query] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2069,7 +1907,9 @@ def sample_search_all_iam_policies(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), ) # Validate the universe domain. @@ -2097,14 +1937,13 @@ def sample_search_all_iam_policies(): # Done; return the response. return response - def analyze_iam_policy( - self, - request: Optional[Union[asset_service.AnalyzeIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.AnalyzeIamPolicyResponse: + def analyze_iam_policy(self, + request: Optional[Union[asset_service.AnalyzeIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.AnalyzeIamPolicyResponse: r"""Analyzes IAM policies to answer which identities have what accesses on which resources. @@ -2168,9 +2007,9 @@ def sample_analyze_iam_policy(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("analysis_query.scope", request.analysis_query.scope),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("analysis_query.scope", request.analysis_query.scope), + )), ) # Validate the universe domain. @@ -2187,16 +2026,13 @@ def sample_analyze_iam_policy(): # Done; return the response. return response - def analyze_iam_policy_longrunning( - self, - request: Optional[ - Union[asset_service.AnalyzeIamPolicyLongrunningRequest, dict] - ] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def analyze_iam_policy_longrunning(self, + request: Optional[Union[asset_service.AnalyzeIamPolicyLongrunningRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Analyzes IAM policies asynchronously to answer which identities have what accesses on which resources, and writes the analysis results to a Google Cloud Storage or a BigQuery destination. For @@ -2275,16 +2111,14 @@ def sample_analyze_iam_policy_longrunning(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.analyze_iam_policy_longrunning - ] + rpc = self._transport._wrapped_methods[self._transport.analyze_iam_policy_longrunning] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("analysis_query.scope", request.analysis_query.scope),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("analysis_query.scope", request.analysis_query.scope), + )), ) # Validate the universe domain. @@ -2309,14 +2143,13 @@ def sample_analyze_iam_policy_longrunning(): # Done; return the response. return response - def analyze_move( - self, - request: Optional[Union[asset_service.AnalyzeMoveRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.AnalyzeMoveResponse: + def analyze_move(self, + request: Optional[Union[asset_service.AnalyzeMoveRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.AnalyzeMoveResponse: r"""Analyze moving a resource to a specified destination without kicking off the actual move. The analysis is best effort depending on the user's permissions of @@ -2383,7 +2216,9 @@ def sample_analyze_move(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), ) # Validate the universe domain. @@ -2400,14 +2235,13 @@ def sample_analyze_move(): # Done; return the response. return response - def query_assets( - self, - request: Optional[Union[asset_service.QueryAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.QueryAssetsResponse: + def query_assets(self, + request: Optional[Union[asset_service.QueryAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.QueryAssetsResponse: r"""Issue a job that queries assets using a SQL statement compatible with `BigQuery SQL `__. @@ -2480,7 +2314,9 @@ def sample_query_assets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2497,17 +2333,16 @@ def sample_query_assets(): # Done; return the response. return response - def create_saved_query( - self, - request: Optional[Union[asset_service.CreateSavedQueryRequest, dict]] = None, - *, - parent: Optional[str] = None, - saved_query: Optional[asset_service.SavedQuery] = None, - saved_query_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.SavedQuery: + def create_saved_query(self, + request: Optional[Union[asset_service.CreateSavedQueryRequest, dict]] = None, + *, + parent: Optional[str] = None, + saved_query: Optional[asset_service.SavedQuery] = None, + saved_query_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Creates a saved query in a parent project/folder/organization. @@ -2593,14 +2428,10 @@ def sample_create_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, saved_query, saved_query_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2622,7 +2453,9 @@ def sample_create_saved_query(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2639,15 +2472,14 @@ def sample_create_saved_query(): # Done; return the response. return response - def get_saved_query( - self, - request: Optional[Union[asset_service.GetSavedQueryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.SavedQuery: + def get_saved_query(self, + request: Optional[Union[asset_service.GetSavedQueryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Gets details about a saved query. .. code-block:: python @@ -2708,14 +2540,10 @@ def sample_get_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2733,7 +2561,9 @@ def sample_get_saved_query(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2750,15 +2580,14 @@ def sample_get_saved_query(): # Done; return the response. return response - def list_saved_queries( - self, - request: Optional[Union[asset_service.ListSavedQueriesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListSavedQueriesPager: + def list_saved_queries(self, + request: Optional[Union[asset_service.ListSavedQueriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSavedQueriesPager: r"""Lists all saved queries in a parent project/folder/organization. @@ -2825,14 +2654,10 @@ def sample_list_saved_queries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2850,7 +2675,9 @@ def sample_list_saved_queries(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2878,16 +2705,15 @@ def sample_list_saved_queries(): # Done; return the response. return response - def update_saved_query( - self, - request: Optional[Union[asset_service.UpdateSavedQueryRequest, dict]] = None, - *, - saved_query: Optional[asset_service.SavedQuery] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.SavedQuery: + def update_saved_query(self, + request: Optional[Union[asset_service.UpdateSavedQueryRequest, dict]] = None, + *, + saved_query: Optional[asset_service.SavedQuery] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Updates a saved query. .. code-block:: python @@ -2956,14 +2782,10 @@ def sample_update_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [saved_query, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2983,9 +2805,9 @@ def sample_update_saved_query(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("saved_query.name", request.saved_query.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("saved_query.name", request.saved_query.name), + )), ) # Validate the universe domain. @@ -3002,15 +2824,14 @@ def sample_update_saved_query(): # Done; return the response. return response - def delete_saved_query( - self, - request: Optional[Union[asset_service.DeleteSavedQueryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_saved_query(self, + request: Optional[Union[asset_service.DeleteSavedQueryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a saved query. .. code-block:: python @@ -3062,14 +2883,10 @@ def sample_delete_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3087,7 +2904,9 @@ def sample_delete_saved_query(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3101,16 +2920,13 @@ def sample_delete_saved_query(): metadata=metadata, ) - def batch_get_effective_iam_policies( - self, - request: Optional[ - Union[asset_service.BatchGetEffectiveIamPoliciesRequest, dict] - ] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: + def batch_get_effective_iam_policies(self, + request: Optional[Union[asset_service.BatchGetEffectiveIamPoliciesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: r"""Gets effective IAM policies for a batch of resources. .. code-block:: python @@ -3166,14 +2982,14 @@ def sample_batch_get_effective_iam_policies(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.batch_get_effective_iam_policies - ] + rpc = self._transport._wrapped_methods[self._transport.batch_get_effective_iam_policies] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), ) # Validate the universe domain. @@ -3190,17 +3006,16 @@ def sample_batch_get_effective_iam_policies(): # Done; return the response. return response - def analyze_org_policies( - self, - request: Optional[Union[asset_service.AnalyzeOrgPoliciesRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.AnalyzeOrgPoliciesPager: + def analyze_org_policies(self, + request: Optional[Union[asset_service.AnalyzeOrgPoliciesRequest, dict]] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AnalyzeOrgPoliciesPager: r"""Analyzes organization policies under a scope. .. code-block:: python @@ -3294,14 +3109,10 @@ def sample_analyze_org_policies(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, constraint, filter] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3323,7 +3134,9 @@ def sample_analyze_org_policies(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), ) # Validate the universe domain. @@ -3351,19 +3164,16 @@ def sample_analyze_org_policies(): # Done; return the response. return response - def analyze_org_policy_governed_containers( - self, - request: Optional[ - Union[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, dict] - ] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.AnalyzeOrgPolicyGovernedContainersPager: + def analyze_org_policy_governed_containers(self, + request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, dict]] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AnalyzeOrgPolicyGovernedContainersPager: r"""Analyzes organization policies governed containers (projects, folders or organization) under a scope. @@ -3458,20 +3268,14 @@ def sample_analyze_org_policy_governed_containers(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, constraint, filter] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, asset_service.AnalyzeOrgPolicyGovernedContainersRequest - ): + if not isinstance(request, asset_service.AnalyzeOrgPolicyGovernedContainersRequest): request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -3484,14 +3288,14 @@ def sample_analyze_org_policy_governed_containers(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.analyze_org_policy_governed_containers - ] + rpc = self._transport._wrapped_methods[self._transport.analyze_org_policy_governed_containers] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), ) # Validate the universe domain. @@ -3519,19 +3323,16 @@ def sample_analyze_org_policy_governed_containers(): # Done; return the response. return response - def analyze_org_policy_governed_assets( - self, - request: Optional[ - Union[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, dict] - ] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.AnalyzeOrgPolicyGovernedAssetsPager: + def analyze_org_policy_governed_assets(self, + request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, dict]] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AnalyzeOrgPolicyGovernedAssetsPager: r"""Analyzes organization policies governed assets (Google Cloud resources or policies) under a scope. This RPC supports custom constraints and the following canned constraints: @@ -3697,14 +3498,10 @@ def sample_analyze_org_policy_governed_assets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, constraint, filter] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3721,14 +3518,14 @@ def sample_analyze_org_policy_governed_assets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.analyze_org_policy_governed_assets - ] + rpc = self._transport._wrapped_methods[self._transport.analyze_org_policy_governed_assets] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), ) # Validate the universe domain. @@ -3811,7 +3608,8 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -3820,11 +3618,7 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -3833,9 +3627,16 @@ def get_operation( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("AssetServiceClient",) +__all__ = ( + "AssetServiceClient", +) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py index 8fba875bffb2..644327ceeac1 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py @@ -17,23 +17,24 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import google.api_core +from google.cloud.asset_v1 import gapic_version as package_version + import google.auth # type: ignore -import google.protobuf -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.api_core from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.cloud.asset_v1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore +import google.protobuf + from google.cloud.asset_v1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ # Check once at module load time whether google-api-core's wrap_method supports @@ -47,24 +48,25 @@ class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) - DEFAULT_HOST: str = "cloudasset.googleapis.com" + DEFAULT_HOST: str = 'cloudasset.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -106,43 +108,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host self._client_options = client_options @@ -169,12 +159,7 @@ def _wrap_method(self, func, *args, **kwargs): # of google-api-core is installed (which does not accept client_options, etc.). # Excluded from coverage because our CI and testing environments always install # a modern version of google-api-core that supports tracing. - for k in [ - "client_options", - "method_name", - "is_streaming", - "kind", - ]: # pragma: NO COVER + for k in ["client_options", "method_name", "is_streaming", "kind"]: # pragma: NO COVER kwargs.pop(k, None) # pragma: NO COVER return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER @@ -393,14 +378,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -410,248 +395,210 @@ def operations_client(self): raise NotImplementedError() @property - def export_assets( - self, - ) -> Callable[ - [asset_service.ExportAssetsRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def export_assets(self) -> Callable[ + [asset_service.ExportAssetsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def list_assets( - self, - ) -> Callable[ - [asset_service.ListAssetsRequest], - Union[ - asset_service.ListAssetsResponse, - Awaitable[asset_service.ListAssetsResponse], - ], - ]: + def list_assets(self) -> Callable[ + [asset_service.ListAssetsRequest], + Union[ + asset_service.ListAssetsResponse, + Awaitable[asset_service.ListAssetsResponse] + ]]: raise NotImplementedError() @property - def batch_get_assets_history( - self, - ) -> Callable[ - [asset_service.BatchGetAssetsHistoryRequest], - Union[ - asset_service.BatchGetAssetsHistoryResponse, - Awaitable[asset_service.BatchGetAssetsHistoryResponse], - ], - ]: + def batch_get_assets_history(self) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + Union[ + asset_service.BatchGetAssetsHistoryResponse, + Awaitable[asset_service.BatchGetAssetsHistoryResponse] + ]]: raise NotImplementedError() @property - def create_feed( - self, - ) -> Callable[ - [asset_service.CreateFeedRequest], - Union[asset_service.Feed, Awaitable[asset_service.Feed]], - ]: + def create_feed(self) -> Callable[ + [asset_service.CreateFeedRequest], + Union[ + asset_service.Feed, + Awaitable[asset_service.Feed] + ]]: raise NotImplementedError() @property - def get_feed( - self, - ) -> Callable[ - [asset_service.GetFeedRequest], - Union[asset_service.Feed, Awaitable[asset_service.Feed]], - ]: + def get_feed(self) -> Callable[ + [asset_service.GetFeedRequest], + Union[ + asset_service.Feed, + Awaitable[asset_service.Feed] + ]]: raise NotImplementedError() @property - def list_feeds( - self, - ) -> Callable[ - [asset_service.ListFeedsRequest], - Union[ - asset_service.ListFeedsResponse, Awaitable[asset_service.ListFeedsResponse] - ], - ]: + def list_feeds(self) -> Callable[ + [asset_service.ListFeedsRequest], + Union[ + asset_service.ListFeedsResponse, + Awaitable[asset_service.ListFeedsResponse] + ]]: raise NotImplementedError() @property - def update_feed( - self, - ) -> Callable[ - [asset_service.UpdateFeedRequest], - Union[asset_service.Feed, Awaitable[asset_service.Feed]], - ]: + def update_feed(self) -> Callable[ + [asset_service.UpdateFeedRequest], + Union[ + asset_service.Feed, + Awaitable[asset_service.Feed] + ]]: raise NotImplementedError() @property - def delete_feed( - self, - ) -> Callable[ - [asset_service.DeleteFeedRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_feed(self) -> Callable[ + [asset_service.DeleteFeedRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def search_all_resources( - self, - ) -> Callable[ - [asset_service.SearchAllResourcesRequest], - Union[ - asset_service.SearchAllResourcesResponse, - Awaitable[asset_service.SearchAllResourcesResponse], - ], - ]: + def search_all_resources(self) -> Callable[ + [asset_service.SearchAllResourcesRequest], + Union[ + asset_service.SearchAllResourcesResponse, + Awaitable[asset_service.SearchAllResourcesResponse] + ]]: raise NotImplementedError() @property - def search_all_iam_policies( - self, - ) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - Union[ - asset_service.SearchAllIamPoliciesResponse, - Awaitable[asset_service.SearchAllIamPoliciesResponse], - ], - ]: + def search_all_iam_policies(self) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + Union[ + asset_service.SearchAllIamPoliciesResponse, + Awaitable[asset_service.SearchAllIamPoliciesResponse] + ]]: raise NotImplementedError() @property - def analyze_iam_policy( - self, - ) -> Callable[ - [asset_service.AnalyzeIamPolicyRequest], - Union[ - asset_service.AnalyzeIamPolicyResponse, - Awaitable[asset_service.AnalyzeIamPolicyResponse], - ], - ]: + def analyze_iam_policy(self) -> Callable[ + [asset_service.AnalyzeIamPolicyRequest], + Union[ + asset_service.AnalyzeIamPolicyResponse, + Awaitable[asset_service.AnalyzeIamPolicyResponse] + ]]: raise NotImplementedError() @property - def analyze_iam_policy_longrunning( - self, - ) -> Callable[ - [asset_service.AnalyzeIamPolicyLongrunningRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def analyze_iam_policy_longrunning(self) -> Callable[ + [asset_service.AnalyzeIamPolicyLongrunningRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def analyze_move( - self, - ) -> Callable[ - [asset_service.AnalyzeMoveRequest], - Union[ - asset_service.AnalyzeMoveResponse, - Awaitable[asset_service.AnalyzeMoveResponse], - ], - ]: + def analyze_move(self) -> Callable[ + [asset_service.AnalyzeMoveRequest], + Union[ + asset_service.AnalyzeMoveResponse, + Awaitable[asset_service.AnalyzeMoveResponse] + ]]: raise NotImplementedError() @property - def query_assets( - self, - ) -> Callable[ - [asset_service.QueryAssetsRequest], - Union[ - asset_service.QueryAssetsResponse, - Awaitable[asset_service.QueryAssetsResponse], - ], - ]: + def query_assets(self) -> Callable[ + [asset_service.QueryAssetsRequest], + Union[ + asset_service.QueryAssetsResponse, + Awaitable[asset_service.QueryAssetsResponse] + ]]: raise NotImplementedError() @property - def create_saved_query( - self, - ) -> Callable[ - [asset_service.CreateSavedQueryRequest], - Union[asset_service.SavedQuery, Awaitable[asset_service.SavedQuery]], - ]: + def create_saved_query(self) -> Callable[ + [asset_service.CreateSavedQueryRequest], + Union[ + asset_service.SavedQuery, + Awaitable[asset_service.SavedQuery] + ]]: raise NotImplementedError() @property - def get_saved_query( - self, - ) -> Callable[ - [asset_service.GetSavedQueryRequest], - Union[asset_service.SavedQuery, Awaitable[asset_service.SavedQuery]], - ]: + def get_saved_query(self) -> Callable[ + [asset_service.GetSavedQueryRequest], + Union[ + asset_service.SavedQuery, + Awaitable[asset_service.SavedQuery] + ]]: raise NotImplementedError() @property - def list_saved_queries( - self, - ) -> Callable[ - [asset_service.ListSavedQueriesRequest], - Union[ - asset_service.ListSavedQueriesResponse, - Awaitable[asset_service.ListSavedQueriesResponse], - ], - ]: + def list_saved_queries(self) -> Callable[ + [asset_service.ListSavedQueriesRequest], + Union[ + asset_service.ListSavedQueriesResponse, + Awaitable[asset_service.ListSavedQueriesResponse] + ]]: raise NotImplementedError() @property - def update_saved_query( - self, - ) -> Callable[ - [asset_service.UpdateSavedQueryRequest], - Union[asset_service.SavedQuery, Awaitable[asset_service.SavedQuery]], - ]: + def update_saved_query(self) -> Callable[ + [asset_service.UpdateSavedQueryRequest], + Union[ + asset_service.SavedQuery, + Awaitable[asset_service.SavedQuery] + ]]: raise NotImplementedError() @property - def delete_saved_query( - self, - ) -> Callable[ - [asset_service.DeleteSavedQueryRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_saved_query(self) -> Callable[ + [asset_service.DeleteSavedQueryRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def batch_get_effective_iam_policies( - self, - ) -> Callable[ - [asset_service.BatchGetEffectiveIamPoliciesRequest], - Union[ - asset_service.BatchGetEffectiveIamPoliciesResponse, - Awaitable[asset_service.BatchGetEffectiveIamPoliciesResponse], - ], - ]: + def batch_get_effective_iam_policies(self) -> Callable[ + [asset_service.BatchGetEffectiveIamPoliciesRequest], + Union[ + asset_service.BatchGetEffectiveIamPoliciesResponse, + Awaitable[asset_service.BatchGetEffectiveIamPoliciesResponse] + ]]: raise NotImplementedError() @property - def analyze_org_policies( - self, - ) -> Callable[ - [asset_service.AnalyzeOrgPoliciesRequest], - Union[ - asset_service.AnalyzeOrgPoliciesResponse, - Awaitable[asset_service.AnalyzeOrgPoliciesResponse], - ], - ]: + def analyze_org_policies(self) -> Callable[ + [asset_service.AnalyzeOrgPoliciesRequest], + Union[ + asset_service.AnalyzeOrgPoliciesResponse, + Awaitable[asset_service.AnalyzeOrgPoliciesResponse] + ]]: raise NotImplementedError() @property - def analyze_org_policy_governed_containers( - self, - ) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], - Union[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse, - Awaitable[asset_service.AnalyzeOrgPolicyGovernedContainersResponse], - ], - ]: + def analyze_org_policy_governed_containers(self) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], + Union[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse, + Awaitable[asset_service.AnalyzeOrgPolicyGovernedContainersResponse] + ]]: raise NotImplementedError() @property - def analyze_org_policy_governed_assets( - self, - ) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], - Union[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, - Awaitable[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse], - ], - ]: + def analyze_org_policy_governed_assets(self) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], + Union[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, + Awaitable[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse] + ]]: raise NotImplementedError() @property @@ -668,4 +615,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("AssetServiceTransport",) +__all__ = ( + 'AssetServiceTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py index ea3a12319655..8189eaeb88c4 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -17,19 +17,17 @@ import logging as std_logging import pickle import warnings -from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ( - ClientInterceptor, # type: ignore[attr-defined] - ) + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1, operations_v1 - +from google.api_core import gapic_v1 # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -37,21 +35,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -import google.protobuf.message -import proto # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.asset_v1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message -from .base import DEFAULT_CLIENT_INFO, AssetServiceTransport +import proto # type: ignore + +from google.cloud.asset_v1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -61,9 +59,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -84,7 +80,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -95,11 +91,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -114,7 +106,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": client_call_details.method, "response": grpc_response, @@ -136,35 +128,32 @@ class AssetServiceGrpcTransport(AssetServiceTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "cloudasset.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], + def __init__(self, *, + host: str = 'cloudasset.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], + ] ] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -301,17 +290,9 @@ def __init__( channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) - ) - is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None and otel_interceptor not in channel_interceptors - and not any( - getattr(i, "_is_otel_interceptor", None) is True - for i in channel_interceptors - ) + and not any(getattr(i, "_is_otel_interceptor", None) is True for i in channel_interceptors) ): channel_interceptors.append(otel_interceptor) @@ -320,28 +301,22 @@ def __init__( "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors( - self._grpc_channel, channel_interceptors - ) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "cloudasset.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'cloudasset.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -377,12 +352,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -402,9 +378,9 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def export_assets( - self, - ) -> Callable[[asset_service.ExportAssetsRequest], operations_pb2.Operation]: + def export_assets(self) -> Callable[ + [asset_service.ExportAssetsRequest], + operations_pb2.Operation]: r"""Return a callable for the export assets method over gRPC. Exports assets with time and resource types to a given Cloud @@ -431,18 +407,18 @@ def export_assets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "export_assets" not in self._stubs: - self._stubs["export_assets"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/ExportAssets", + if 'export_assets' not in self._stubs: + self._stubs['export_assets'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/ExportAssets', request_serializer=asset_service.ExportAssetsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["export_assets"] + return self._stubs['export_assets'] @property - def list_assets( - self, - ) -> Callable[[asset_service.ListAssetsRequest], asset_service.ListAssetsResponse]: + def list_assets(self) -> Callable[ + [asset_service.ListAssetsRequest], + asset_service.ListAssetsResponse]: r"""Return a callable for the list assets method over gRPC. Lists assets with time and resource types and returns @@ -458,21 +434,18 @@ def list_assets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_assets" not in self._stubs: - self._stubs["list_assets"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/ListAssets", + if 'list_assets' not in self._stubs: + self._stubs['list_assets'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/ListAssets', request_serializer=asset_service.ListAssetsRequest.serialize, response_deserializer=asset_service.ListAssetsResponse.deserialize, ) - return self._stubs["list_assets"] + return self._stubs['list_assets'] @property - def batch_get_assets_history( - self, - ) -> Callable[ - [asset_service.BatchGetAssetsHistoryRequest], - asset_service.BatchGetAssetsHistoryResponse, - ]: + def batch_get_assets_history(self) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + asset_service.BatchGetAssetsHistoryResponse]: r"""Return a callable for the batch get assets history method over gRPC. Batch gets the update history of assets that overlap a time @@ -493,18 +466,18 @@ def batch_get_assets_history( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_get_assets_history" not in self._stubs: - self._stubs["batch_get_assets_history"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/BatchGetAssetsHistory", + if 'batch_get_assets_history' not in self._stubs: + self._stubs['batch_get_assets_history'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/BatchGetAssetsHistory', request_serializer=asset_service.BatchGetAssetsHistoryRequest.serialize, response_deserializer=asset_service.BatchGetAssetsHistoryResponse.deserialize, ) - return self._stubs["batch_get_assets_history"] + return self._stubs['batch_get_assets_history'] @property - def create_feed( - self, - ) -> Callable[[asset_service.CreateFeedRequest], asset_service.Feed]: + def create_feed(self) -> Callable[ + [asset_service.CreateFeedRequest], + asset_service.Feed]: r"""Return a callable for the create feed method over gRPC. Creates a feed in a parent @@ -521,16 +494,18 @@ def create_feed( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_feed" not in self._stubs: - self._stubs["create_feed"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/CreateFeed", + if 'create_feed' not in self._stubs: + self._stubs['create_feed'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/CreateFeed', request_serializer=asset_service.CreateFeedRequest.serialize, response_deserializer=asset_service.Feed.deserialize, ) - return self._stubs["create_feed"] + return self._stubs['create_feed'] @property - def get_feed(self) -> Callable[[asset_service.GetFeedRequest], asset_service.Feed]: + def get_feed(self) -> Callable[ + [asset_service.GetFeedRequest], + asset_service.Feed]: r"""Return a callable for the get feed method over gRPC. Gets details about an asset feed. @@ -545,18 +520,18 @@ def get_feed(self) -> Callable[[asset_service.GetFeedRequest], asset_service.Fee # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_feed" not in self._stubs: - self._stubs["get_feed"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/GetFeed", + if 'get_feed' not in self._stubs: + self._stubs['get_feed'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/GetFeed', request_serializer=asset_service.GetFeedRequest.serialize, response_deserializer=asset_service.Feed.deserialize, ) - return self._stubs["get_feed"] + return self._stubs['get_feed'] @property - def list_feeds( - self, - ) -> Callable[[asset_service.ListFeedsRequest], asset_service.ListFeedsResponse]: + def list_feeds(self) -> Callable[ + [asset_service.ListFeedsRequest], + asset_service.ListFeedsResponse]: r"""Return a callable for the list feeds method over gRPC. Lists all asset feeds in a parent @@ -572,18 +547,18 @@ def list_feeds( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_feeds" not in self._stubs: - self._stubs["list_feeds"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/ListFeeds", + if 'list_feeds' not in self._stubs: + self._stubs['list_feeds'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/ListFeeds', request_serializer=asset_service.ListFeedsRequest.serialize, response_deserializer=asset_service.ListFeedsResponse.deserialize, ) - return self._stubs["list_feeds"] + return self._stubs['list_feeds'] @property - def update_feed( - self, - ) -> Callable[[asset_service.UpdateFeedRequest], asset_service.Feed]: + def update_feed(self) -> Callable[ + [asset_service.UpdateFeedRequest], + asset_service.Feed]: r"""Return a callable for the update feed method over gRPC. Updates an asset feed configuration. @@ -598,18 +573,18 @@ def update_feed( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_feed" not in self._stubs: - self._stubs["update_feed"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/UpdateFeed", + if 'update_feed' not in self._stubs: + self._stubs['update_feed'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/UpdateFeed', request_serializer=asset_service.UpdateFeedRequest.serialize, response_deserializer=asset_service.Feed.deserialize, ) - return self._stubs["update_feed"] + return self._stubs['update_feed'] @property - def delete_feed( - self, - ) -> Callable[[asset_service.DeleteFeedRequest], empty_pb2.Empty]: + def delete_feed(self) -> Callable[ + [asset_service.DeleteFeedRequest], + empty_pb2.Empty]: r"""Return a callable for the delete feed method over gRPC. Deletes an asset feed. @@ -624,21 +599,18 @@ def delete_feed( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_feed" not in self._stubs: - self._stubs["delete_feed"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/DeleteFeed", + if 'delete_feed' not in self._stubs: + self._stubs['delete_feed'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/DeleteFeed', request_serializer=asset_service.DeleteFeedRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_feed"] + return self._stubs['delete_feed'] @property - def search_all_resources( - self, - ) -> Callable[ - [asset_service.SearchAllResourcesRequest], - asset_service.SearchAllResourcesResponse, - ]: + def search_all_resources(self) -> Callable[ + [asset_service.SearchAllResourcesRequest], + asset_service.SearchAllResourcesResponse]: r"""Return a callable for the search all resources method over gRPC. Searches all Google Cloud resources within the specified scope, @@ -656,21 +628,18 @@ def search_all_resources( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "search_all_resources" not in self._stubs: - self._stubs["search_all_resources"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/SearchAllResources", + if 'search_all_resources' not in self._stubs: + self._stubs['search_all_resources'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/SearchAllResources', request_serializer=asset_service.SearchAllResourcesRequest.serialize, response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, ) - return self._stubs["search_all_resources"] + return self._stubs['search_all_resources'] @property - def search_all_iam_policies( - self, - ) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - asset_service.SearchAllIamPoliciesResponse, - ]: + def search_all_iam_policies(self) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + asset_service.SearchAllIamPoliciesResponse]: r"""Return a callable for the search all iam policies method over gRPC. Searches all IAM policies within the specified scope, such as a @@ -688,20 +657,18 @@ def search_all_iam_policies( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "search_all_iam_policies" not in self._stubs: - self._stubs["search_all_iam_policies"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/SearchAllIamPolicies", + if 'search_all_iam_policies' not in self._stubs: + self._stubs['search_all_iam_policies'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/SearchAllIamPolicies', request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, ) - return self._stubs["search_all_iam_policies"] + return self._stubs['search_all_iam_policies'] @property - def analyze_iam_policy( - self, - ) -> Callable[ - [asset_service.AnalyzeIamPolicyRequest], asset_service.AnalyzeIamPolicyResponse - ]: + def analyze_iam_policy(self) -> Callable[ + [asset_service.AnalyzeIamPolicyRequest], + asset_service.AnalyzeIamPolicyResponse]: r"""Return a callable for the analyze iam policy method over gRPC. Analyzes IAM policies to answer which identities have @@ -717,20 +684,18 @@ def analyze_iam_policy( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "analyze_iam_policy" not in self._stubs: - self._stubs["analyze_iam_policy"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/AnalyzeIamPolicy", + if 'analyze_iam_policy' not in self._stubs: + self._stubs['analyze_iam_policy'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeIamPolicy', request_serializer=asset_service.AnalyzeIamPolicyRequest.serialize, response_deserializer=asset_service.AnalyzeIamPolicyResponse.deserialize, ) - return self._stubs["analyze_iam_policy"] + return self._stubs['analyze_iam_policy'] @property - def analyze_iam_policy_longrunning( - self, - ) -> Callable[ - [asset_service.AnalyzeIamPolicyLongrunningRequest], operations_pb2.Operation - ]: + def analyze_iam_policy_longrunning(self) -> Callable[ + [asset_service.AnalyzeIamPolicyLongrunningRequest], + operations_pb2.Operation]: r"""Return a callable for the analyze iam policy longrunning method over gRPC. Analyzes IAM policies asynchronously to answer which identities @@ -756,22 +721,18 @@ def analyze_iam_policy_longrunning( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "analyze_iam_policy_longrunning" not in self._stubs: - self._stubs["analyze_iam_policy_longrunning"] = ( - self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/AnalyzeIamPolicyLongrunning", - request_serializer=asset_service.AnalyzeIamPolicyLongrunningRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) + if 'analyze_iam_policy_longrunning' not in self._stubs: + self._stubs['analyze_iam_policy_longrunning'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeIamPolicyLongrunning', + request_serializer=asset_service.AnalyzeIamPolicyLongrunningRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["analyze_iam_policy_longrunning"] + return self._stubs['analyze_iam_policy_longrunning'] @property - def analyze_move( - self, - ) -> Callable[ - [asset_service.AnalyzeMoveRequest], asset_service.AnalyzeMoveResponse - ]: + def analyze_move(self) -> Callable[ + [asset_service.AnalyzeMoveRequest], + asset_service.AnalyzeMoveResponse]: r"""Return a callable for the analyze move method over gRPC. Analyze moving a resource to a specified destination @@ -792,20 +753,18 @@ def analyze_move( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "analyze_move" not in self._stubs: - self._stubs["analyze_move"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/AnalyzeMove", + if 'analyze_move' not in self._stubs: + self._stubs['analyze_move'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeMove', request_serializer=asset_service.AnalyzeMoveRequest.serialize, response_deserializer=asset_service.AnalyzeMoveResponse.deserialize, ) - return self._stubs["analyze_move"] + return self._stubs['analyze_move'] @property - def query_assets( - self, - ) -> Callable[ - [asset_service.QueryAssetsRequest], asset_service.QueryAssetsResponse - ]: + def query_assets(self) -> Callable[ + [asset_service.QueryAssetsRequest], + asset_service.QueryAssetsResponse]: r"""Return a callable for the query assets method over gRPC. Issue a job that queries assets using a SQL statement compatible @@ -835,18 +794,18 @@ def query_assets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "query_assets" not in self._stubs: - self._stubs["query_assets"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/QueryAssets", + if 'query_assets' not in self._stubs: + self._stubs['query_assets'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/QueryAssets', request_serializer=asset_service.QueryAssetsRequest.serialize, response_deserializer=asset_service.QueryAssetsResponse.deserialize, ) - return self._stubs["query_assets"] + return self._stubs['query_assets'] @property - def create_saved_query( - self, - ) -> Callable[[asset_service.CreateSavedQueryRequest], asset_service.SavedQuery]: + def create_saved_query(self) -> Callable[ + [asset_service.CreateSavedQueryRequest], + asset_service.SavedQuery]: r"""Return a callable for the create saved query method over gRPC. Creates a saved query in a parent @@ -862,18 +821,18 @@ def create_saved_query( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_saved_query" not in self._stubs: - self._stubs["create_saved_query"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/CreateSavedQuery", + if 'create_saved_query' not in self._stubs: + self._stubs['create_saved_query'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/CreateSavedQuery', request_serializer=asset_service.CreateSavedQueryRequest.serialize, response_deserializer=asset_service.SavedQuery.deserialize, ) - return self._stubs["create_saved_query"] + return self._stubs['create_saved_query'] @property - def get_saved_query( - self, - ) -> Callable[[asset_service.GetSavedQueryRequest], asset_service.SavedQuery]: + def get_saved_query(self) -> Callable[ + [asset_service.GetSavedQueryRequest], + asset_service.SavedQuery]: r"""Return a callable for the get saved query method over gRPC. Gets details about a saved query. @@ -888,20 +847,18 @@ def get_saved_query( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_saved_query" not in self._stubs: - self._stubs["get_saved_query"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/GetSavedQuery", + if 'get_saved_query' not in self._stubs: + self._stubs['get_saved_query'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/GetSavedQuery', request_serializer=asset_service.GetSavedQueryRequest.serialize, response_deserializer=asset_service.SavedQuery.deserialize, ) - return self._stubs["get_saved_query"] + return self._stubs['get_saved_query'] @property - def list_saved_queries( - self, - ) -> Callable[ - [asset_service.ListSavedQueriesRequest], asset_service.ListSavedQueriesResponse - ]: + def list_saved_queries(self) -> Callable[ + [asset_service.ListSavedQueriesRequest], + asset_service.ListSavedQueriesResponse]: r"""Return a callable for the list saved queries method over gRPC. Lists all saved queries in a parent @@ -917,18 +874,18 @@ def list_saved_queries( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_saved_queries" not in self._stubs: - self._stubs["list_saved_queries"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/ListSavedQueries", + if 'list_saved_queries' not in self._stubs: + self._stubs['list_saved_queries'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/ListSavedQueries', request_serializer=asset_service.ListSavedQueriesRequest.serialize, response_deserializer=asset_service.ListSavedQueriesResponse.deserialize, ) - return self._stubs["list_saved_queries"] + return self._stubs['list_saved_queries'] @property - def update_saved_query( - self, - ) -> Callable[[asset_service.UpdateSavedQueryRequest], asset_service.SavedQuery]: + def update_saved_query(self) -> Callable[ + [asset_service.UpdateSavedQueryRequest], + asset_service.SavedQuery]: r"""Return a callable for the update saved query method over gRPC. Updates a saved query. @@ -943,18 +900,18 @@ def update_saved_query( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_saved_query" not in self._stubs: - self._stubs["update_saved_query"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/UpdateSavedQuery", + if 'update_saved_query' not in self._stubs: + self._stubs['update_saved_query'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/UpdateSavedQuery', request_serializer=asset_service.UpdateSavedQueryRequest.serialize, response_deserializer=asset_service.SavedQuery.deserialize, ) - return self._stubs["update_saved_query"] + return self._stubs['update_saved_query'] @property - def delete_saved_query( - self, - ) -> Callable[[asset_service.DeleteSavedQueryRequest], empty_pb2.Empty]: + def delete_saved_query(self) -> Callable[ + [asset_service.DeleteSavedQueryRequest], + empty_pb2.Empty]: r"""Return a callable for the delete saved query method over gRPC. Deletes a saved query. @@ -969,21 +926,18 @@ def delete_saved_query( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_saved_query" not in self._stubs: - self._stubs["delete_saved_query"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/DeleteSavedQuery", + if 'delete_saved_query' not in self._stubs: + self._stubs['delete_saved_query'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/DeleteSavedQuery', request_serializer=asset_service.DeleteSavedQueryRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_saved_query"] + return self._stubs['delete_saved_query'] @property - def batch_get_effective_iam_policies( - self, - ) -> Callable[ - [asset_service.BatchGetEffectiveIamPoliciesRequest], - asset_service.BatchGetEffectiveIamPoliciesResponse, - ]: + def batch_get_effective_iam_policies(self) -> Callable[ + [asset_service.BatchGetEffectiveIamPoliciesRequest], + asset_service.BatchGetEffectiveIamPoliciesResponse]: r"""Return a callable for the batch get effective iam policies method over gRPC. @@ -999,23 +953,18 @@ def batch_get_effective_iam_policies( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_get_effective_iam_policies" not in self._stubs: - self._stubs["batch_get_effective_iam_policies"] = ( - self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/BatchGetEffectiveIamPolicies", - request_serializer=asset_service.BatchGetEffectiveIamPoliciesRequest.serialize, - response_deserializer=asset_service.BatchGetEffectiveIamPoliciesResponse.deserialize, - ) + if 'batch_get_effective_iam_policies' not in self._stubs: + self._stubs['batch_get_effective_iam_policies'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/BatchGetEffectiveIamPolicies', + request_serializer=asset_service.BatchGetEffectiveIamPoliciesRequest.serialize, + response_deserializer=asset_service.BatchGetEffectiveIamPoliciesResponse.deserialize, ) - return self._stubs["batch_get_effective_iam_policies"] + return self._stubs['batch_get_effective_iam_policies'] @property - def analyze_org_policies( - self, - ) -> Callable[ - [asset_service.AnalyzeOrgPoliciesRequest], - asset_service.AnalyzeOrgPoliciesResponse, - ]: + def analyze_org_policies(self) -> Callable[ + [asset_service.AnalyzeOrgPoliciesRequest], + asset_service.AnalyzeOrgPoliciesResponse]: r"""Return a callable for the analyze org policies method over gRPC. Analyzes organization policies under a scope. @@ -1030,21 +979,18 @@ def analyze_org_policies( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "analyze_org_policies" not in self._stubs: - self._stubs["analyze_org_policies"] = self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicies", + if 'analyze_org_policies' not in self._stubs: + self._stubs['analyze_org_policies'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicies', request_serializer=asset_service.AnalyzeOrgPoliciesRequest.serialize, response_deserializer=asset_service.AnalyzeOrgPoliciesResponse.deserialize, ) - return self._stubs["analyze_org_policies"] + return self._stubs['analyze_org_policies'] @property - def analyze_org_policy_governed_containers( - self, - ) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], - asset_service.AnalyzeOrgPolicyGovernedContainersResponse, - ]: + def analyze_org_policy_governed_containers(self) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], + asset_service.AnalyzeOrgPolicyGovernedContainersResponse]: r"""Return a callable for the analyze org policy governed containers method over gRPC. @@ -1061,23 +1007,18 @@ def analyze_org_policy_governed_containers( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "analyze_org_policy_governed_containers" not in self._stubs: - self._stubs["analyze_org_policy_governed_containers"] = ( - self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedContainers", - request_serializer=asset_service.AnalyzeOrgPolicyGovernedContainersRequest.serialize, - response_deserializer=asset_service.AnalyzeOrgPolicyGovernedContainersResponse.deserialize, - ) + if 'analyze_org_policy_governed_containers' not in self._stubs: + self._stubs['analyze_org_policy_governed_containers'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedContainers', + request_serializer=asset_service.AnalyzeOrgPolicyGovernedContainersRequest.serialize, + response_deserializer=asset_service.AnalyzeOrgPolicyGovernedContainersResponse.deserialize, ) - return self._stubs["analyze_org_policy_governed_containers"] + return self._stubs['analyze_org_policy_governed_containers'] @property - def analyze_org_policy_governed_assets( - self, - ) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, - ]: + def analyze_org_policy_governed_assets(self) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]: r"""Return a callable for the analyze org policy governed assets method over gRPC. @@ -1142,15 +1083,13 @@ def analyze_org_policy_governed_assets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "analyze_org_policy_governed_assets" not in self._stubs: - self._stubs["analyze_org_policy_governed_assets"] = ( - self._logged_channel.unary_unary( - "/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedAssets", - request_serializer=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest.serialize, - response_deserializer=asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.deserialize, - ) + if 'analyze_org_policy_governed_assets' not in self._stubs: + self._stubs['analyze_org_policy_governed_assets'] = self._logged_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedAssets', + request_serializer=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest.serialize, + response_deserializer=asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.deserialize, ) - return self._stubs["analyze_org_policy_governed_assets"] + return self._stubs['analyze_org_policy_governed_assets'] def close(self): self._logged_channel.close() @@ -1159,7 +1098,8 @@ def close(self): def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1177,4 +1117,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("AssetServiceGrpcTransport",) +__all__ = ( + 'AssetServiceGrpcTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index 28da012086f2..217e3c0792c0 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -13,46 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import inspect import json import logging as std_logging import os import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings -from collections import OrderedDict -from http import HTTPStatus -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import google.protobuf +from google.iam.credentials_v1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 +from google.iam.credentials_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.iam.credentials_v1 import gapic_version as package_version -from google.iam.credentials_v1._compat import ( - get_api_endpoint, - get_default_mtls_endpoint, - get_universe_domain, - read_environment_variables, - should_use_client_cert, -) -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -61,7 +44,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -75,11 +57,10 @@ _LOGGER = std_logging.getLogger(__name__) +from google.iam.credentials_v1.types import common import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from google.iam.credentials_v1.types import common - -from .transports.base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport +from .transports.base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import IAMCredentialsGrpcTransport from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport from .transports.rest import IAMCredentialsRestTransport @@ -92,16 +73,14 @@ class IAMCredentialsClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[IAMCredentialsTransport]] _transport_registry["grpc"] = IAMCredentialsGrpcTransport _transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport _transport_registry["rest"] = IAMCredentialsRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[IAMCredentialsTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[IAMCredentialsTransport]: """Returns an appropriate transport class. Args: @@ -171,7 +150,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: IAMCredentialsClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -188,106 +168,73 @@ def transport(self) -> IAMCredentialsTransport: return self._transport @staticmethod - def service_account_path( - project: str, - service_account: str, - ) -> str: + def service_account_path(project: str,service_account: str,) -> str: """Returns a fully-qualified service_account string.""" - return "projects/{project}/serviceAccounts/{service_account}".format( - project=project, - service_account=service_account, - ) + return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) @staticmethod - def parse_service_account_path(path: str) -> Dict[str, str]: + def parse_service_account_path(path: str) -> Dict[str,str]: """Parses a service_account path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -319,18 +266,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -343,10 +286,8 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -385,18 +326,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -429,16 +367,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the iam credentials client. Args: @@ -496,23 +430,13 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - read_environment_variables() - ) - self._client_cert_source = IAMCredentialsClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = get_universe_domain( - universe_domain_opt, - self._universe_domain_env, - default_universe=IAMCredentialsClient._DEFAULT_UNIVERSE, - ) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() + self._client_cert_source = IAMCredentialsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=IAMCredentialsClient._DEFAULT_UNIVERSE) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -524,9 +448,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -535,40 +457,35 @@ def __init__( if transport_provided: # transport is a IAMCredentialsTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = cast(IAMCredentialsTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = self._api_endpoint or get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=IAMCredentialsClient._DEFAULT_UNIVERSE, - default_mtls_endpoint=IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" - or (self._use_mtls_endpoint == "auto" and self._client_cert_source), - ) + self._api_endpoint = (self._api_endpoint or + get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=IAMCredentialsClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" or ( + self._use_mtls_endpoint == "auto" and self._client_cert_source + ), + )) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[IAMCredentialsTransport], Callable[..., IAMCredentialsTransport] - ] = ( + transport_init: Union[Type[IAMCredentialsTransport], Callable[..., IAMCredentialsTransport]] = ( IAMCredentialsClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., IAMCredentialsTransport], transport) @@ -597,49 +514,36 @@ def __init__( "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **( - {"client_options": client_options} - if client_options is not None - else {} - ), + **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.iam.credentials_v1.IAMCredentialsClient`.", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.iam.credentials.v1.IAMCredentials", "credentialsType": None, - }, + } ) - def generate_access_token( - self, - request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - scope: Optional[MutableSequence[str]] = None, - lifetime: Optional[duration_pb2.Duration] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateAccessTokenResponse: + def generate_access_token(self, + request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + scope: Optional[MutableSequence[str]] = None, + lifetime: Optional[duration_pb2.Duration] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateAccessTokenResponse: r"""Generates an OAuth 2.0 access token for a service account. @@ -740,14 +644,10 @@ def sample_generate_access_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, scope, lifetime] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -771,7 +671,9 @@ def sample_generate_access_token(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -788,18 +690,17 @@ def sample_generate_access_token(): # Done; return the response. return response - def generate_id_token( - self, - request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - audience: Optional[str] = None, - include_email: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateIdTokenResponse: + def generate_id_token(self, + request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + audience: Optional[str] = None, + include_email: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateIdTokenResponse: r"""Generates an OpenID Connect ID token for a service account. @@ -894,14 +795,10 @@ def sample_generate_id_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, audience, include_email] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -925,7 +822,9 @@ def sample_generate_id_token(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -942,17 +841,16 @@ def sample_generate_id_token(): # Done; return the response. return response - def sign_blob( - self, - request: Optional[Union[common.SignBlobRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignBlobResponse: + def sign_blob(self, + request: Optional[Union[common.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignBlobResponse: r"""Signs a blob using a service account's system-managed private key. @@ -1036,14 +934,10 @@ def sample_sign_blob(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1065,7 +959,9 @@ def sample_sign_blob(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1082,17 +978,16 @@ def sample_sign_blob(): # Done; return the response. return response - def sign_jwt( - self, - request: Optional[Union[common.SignJwtRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignJwtResponse: + def sign_jwt(self, + request: Optional[Union[common.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignJwtResponse: r"""Signs a JWT using a service account's system-managed private key. @@ -1179,14 +1074,10 @@ def sample_sign_jwt(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1208,7 +1099,9 @@ def sample_sign_jwt(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1239,9 +1132,14 @@ def __exit__(self, type, value, traceback): self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("IAMCredentialsClient",) +__all__ = ( + "IAMCredentialsClient", +) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py index a00063e535d0..86402773c2f6 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py @@ -17,21 +17,21 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import google.api_core +from google.iam.credentials_v1 import gapic_version as package_version + import google.auth # type: ignore -import google.protobuf +import google.api_core from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.iam.credentials_v1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore +import google.protobuf + from google.iam.credentials_v1.types import common -from google.oauth2 import service_account # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ # Check once at module load time whether google-api-core's wrap_method supports @@ -45,24 +45,25 @@ class IAMCredentialsTransport(abc.ABC): """Abstract transport class for IAMCredentials.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) - DEFAULT_HOST: str = "iamcredentials.googleapis.com" + DEFAULT_HOST: str = 'iamcredentials.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -104,43 +105,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host self._client_options = client_options @@ -167,12 +156,7 @@ def _wrap_method(self, func, *args, **kwargs): # of google-api-core is installed (which does not accept client_options, etc.). # Excluded from coverage because our CI and testing environments always install # a modern version of google-api-core that supports tracing. - for k in [ - "client_options", - "method_name", - "is_streaming", - "kind", - ]: # pragma: NO COVER + for k in ["client_options", "method_name", "is_streaming", "kind"]: # pragma: NO COVER kwargs.pop(k, None) # pragma: NO COVER return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER @@ -243,56 +227,51 @@ def _prep_wrapped_messages(self, client_info): client_info=client_info, method_name="google.iam.credentials.v1.IAMCredentials/SignJwt", ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def generate_access_token( - self, - ) -> Callable[ - [common.GenerateAccessTokenRequest], - Union[ - common.GenerateAccessTokenResponse, - Awaitable[common.GenerateAccessTokenResponse], - ], - ]: + def generate_access_token(self) -> Callable[ + [common.GenerateAccessTokenRequest], + Union[ + common.GenerateAccessTokenResponse, + Awaitable[common.GenerateAccessTokenResponse] + ]]: raise NotImplementedError() @property - def generate_id_token( - self, - ) -> Callable[ - [common.GenerateIdTokenRequest], - Union[ - common.GenerateIdTokenResponse, Awaitable[common.GenerateIdTokenResponse] - ], - ]: + def generate_id_token(self) -> Callable[ + [common.GenerateIdTokenRequest], + Union[ + common.GenerateIdTokenResponse, + Awaitable[common.GenerateIdTokenResponse] + ]]: raise NotImplementedError() @property - def sign_blob( - self, - ) -> Callable[ - [common.SignBlobRequest], - Union[common.SignBlobResponse, Awaitable[common.SignBlobResponse]], - ]: + def sign_blob(self) -> Callable[ + [common.SignBlobRequest], + Union[ + common.SignBlobResponse, + Awaitable[common.SignBlobResponse] + ]]: raise NotImplementedError() @property - def sign_jwt( - self, - ) -> Callable[ - [common.SignJwtRequest], - Union[common.SignJwtResponse, Awaitable[common.SignJwtResponse]], - ]: + def sign_jwt(self) -> Callable[ + [common.SignJwtRequest], + Union[ + common.SignJwtResponse, + Awaitable[common.SignJwtResponse] + ]]: raise NotImplementedError() @property @@ -300,4 +279,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("IAMCredentialsTransport",) +__all__ = ( + 'IAMCredentialsTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py index 7c4b7421ee56..22d4c7239e2e 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py @@ -17,19 +17,16 @@ import logging as std_logging import pickle import warnings -from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ( - ClientInterceptor, # type: ignore[attr-defined] - ) + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 - # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -37,19 +34,19 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore -import google.protobuf.message -import proto # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.iam.credentials_v1.types import common from google.protobuf.json_format import MessageToJson +import google.protobuf.message -from .base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport +import proto # type: ignore + +from google.iam.credentials_v1.types import common +from .base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -59,9 +56,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -82,7 +77,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -93,11 +88,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -112,7 +103,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": client_call_details.method, "response": grpc_response, @@ -143,35 +134,32 @@ class IAMCredentialsGrpcTransport(IAMCredentialsTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "iamcredentials.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], + def __init__(self, *, + host: str = 'iamcredentials.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], + ] ] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -307,17 +295,9 @@ def __init__( channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) - ) - is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None and otel_interceptor not in channel_interceptors - and not any( - getattr(i, "_is_otel_interceptor", None) is True - for i in channel_interceptors - ) + and not any(getattr(i, "_is_otel_interceptor", None) is True for i in channel_interceptors) ): channel_interceptors.append(otel_interceptor) @@ -326,28 +306,22 @@ def __init__( "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors( - self._grpc_channel, channel_interceptors - ) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "iamcredentials.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'iamcredentials.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -383,20 +357,19 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property - def generate_access_token( - self, - ) -> Callable[ - [common.GenerateAccessTokenRequest], common.GenerateAccessTokenResponse - ]: + def generate_access_token(self) -> Callable[ + [common.GenerateAccessTokenRequest], + common.GenerateAccessTokenResponse]: r"""Return a callable for the generate access token method over gRPC. Generates an OAuth 2.0 access token for a service @@ -412,18 +385,18 @@ def generate_access_token( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "generate_access_token" not in self._stubs: - self._stubs["generate_access_token"] = self._logged_channel.unary_unary( - "/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken", + if 'generate_access_token' not in self._stubs: + self._stubs['generate_access_token'] = self._logged_channel.unary_unary( + '/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken', request_serializer=common.GenerateAccessTokenRequest.serialize, response_deserializer=common.GenerateAccessTokenResponse.deserialize, ) - return self._stubs["generate_access_token"] + return self._stubs['generate_access_token'] @property - def generate_id_token( - self, - ) -> Callable[[common.GenerateIdTokenRequest], common.GenerateIdTokenResponse]: + def generate_id_token(self) -> Callable[ + [common.GenerateIdTokenRequest], + common.GenerateIdTokenResponse]: r"""Return a callable for the generate id token method over gRPC. Generates an OpenID Connect ID token for a service @@ -439,16 +412,18 @@ def generate_id_token( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "generate_id_token" not in self._stubs: - self._stubs["generate_id_token"] = self._logged_channel.unary_unary( - "/google.iam.credentials.v1.IAMCredentials/GenerateIdToken", + if 'generate_id_token' not in self._stubs: + self._stubs['generate_id_token'] = self._logged_channel.unary_unary( + '/google.iam.credentials.v1.IAMCredentials/GenerateIdToken', request_serializer=common.GenerateIdTokenRequest.serialize, response_deserializer=common.GenerateIdTokenResponse.deserialize, ) - return self._stubs["generate_id_token"] + return self._stubs['generate_id_token'] @property - def sign_blob(self) -> Callable[[common.SignBlobRequest], common.SignBlobResponse]: + def sign_blob(self) -> Callable[ + [common.SignBlobRequest], + common.SignBlobResponse]: r"""Return a callable for the sign blob method over gRPC. Signs a blob using a service account's system-managed @@ -464,16 +439,18 @@ def sign_blob(self) -> Callable[[common.SignBlobRequest], common.SignBlobRespons # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "sign_blob" not in self._stubs: - self._stubs["sign_blob"] = self._logged_channel.unary_unary( - "/google.iam.credentials.v1.IAMCredentials/SignBlob", + if 'sign_blob' not in self._stubs: + self._stubs['sign_blob'] = self._logged_channel.unary_unary( + '/google.iam.credentials.v1.IAMCredentials/SignBlob', request_serializer=common.SignBlobRequest.serialize, response_deserializer=common.SignBlobResponse.deserialize, ) - return self._stubs["sign_blob"] + return self._stubs['sign_blob'] @property - def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]: + def sign_jwt(self) -> Callable[ + [common.SignJwtRequest], + common.SignJwtResponse]: r"""Return a callable for the sign jwt method over gRPC. Signs a JWT using a service account's system-managed @@ -489,13 +466,13 @@ def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]: # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "sign_jwt" not in self._stubs: - self._stubs["sign_jwt"] = self._logged_channel.unary_unary( - "/google.iam.credentials.v1.IAMCredentials/SignJwt", + if 'sign_jwt' not in self._stubs: + self._stubs['sign_jwt'] = self._logged_channel.unary_unary( + '/google.iam.credentials.v1.IAMCredentials/SignJwt', request_serializer=common.SignJwtRequest.serialize, response_deserializer=common.SignJwtResponse.deserialize, ) - return self._stubs["sign_jwt"] + return self._stubs['sign_jwt'] def close(self): self._logged_channel.close() @@ -505,4 +482,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("IAMCredentialsGrpcTransport",) +__all__ = ( + 'IAMCredentialsGrpcTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index eb1371fa8494..52adfbed65e4 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -13,46 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import inspect import json import logging as std_logging import os import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings -from collections import OrderedDict -from http import HTTPStatus -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import google.protobuf +from google.cloud.eventarc_v1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 +from google.cloud.eventarc_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.eventarc_v1 import gapic_version as package_version -from google.cloud.eventarc_v1._compat import ( - get_api_endpoint, - get_default_mtls_endpoint, - get_universe_domain, - read_environment_variables, - should_use_client_cert, -) -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -61,7 +44,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -75,42 +57,35 @@ _LOGGER = std_logging.getLogger(__name__) -import google.api_core.operation as operation # type: ignore -import google.api_core.operation_async as operation_async # type: ignore -import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.eventarc_v1.services.eventarc import pagers -from google.cloud.eventarc_v1.types import ( - channel, - channel_connection, - discovery, - enrollment, - eventarc, - google_api_source, - google_channel_config, - logging_config, - message_bus, - pipeline, - trigger, -) +from google.cloud.eventarc_v1.types import channel from google.cloud.eventarc_v1.types import channel as gce_channel +from google.cloud.eventarc_v1.types import channel_connection from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment from google.cloud.eventarc_v1.types import enrollment as gce_enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source -from google.cloud.eventarc_v1.types import ( - google_channel_config as gce_google_channel_config, -) +from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import logging_config +from google.cloud.eventarc_v1.types import message_bus from google.cloud.eventarc_v1.types import message_bus as gce_message_bus +from google.cloud.eventarc_v1.types import pipeline from google.cloud.eventarc_v1.types import pipeline as gce_pipeline +from google.cloud.eventarc_v1.types import trigger from google.cloud.eventarc_v1.types import trigger as gce_trigger -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import ( - iam_policy_pb2, # type: ignore - policy_pb2, # type: ignore -) -from google.longrunning import operations_pb2 # type: ignore - -from .transports.base import DEFAULT_CLIENT_INFO, EventarcTransport +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from .transports.base import EventarcTransport, DEFAULT_CLIENT_INFO from .transports.grpc import EventarcGrpcTransport from .transports.grpc_asyncio import EventarcGrpcAsyncIOTransport from .transports.rest import EventarcRestTransport @@ -123,16 +98,14 @@ class EventarcClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[EventarcTransport]] _transport_registry["grpc"] = EventarcGrpcTransport _transport_registry["grpc_asyncio"] = EventarcGrpcAsyncIOTransport _transport_registry["rest"] = EventarcRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[EventarcTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[EventarcTransport]: """Returns an appropriate transport class. Args: @@ -195,7 +168,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: EventarcClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -212,249 +186,124 @@ def transport(self) -> EventarcTransport: return self._transport @staticmethod - def channel_path( - project: str, - location: str, - channel: str, - ) -> str: + def channel_path(project: str,location: str,channel: str,) -> str: """Returns a fully-qualified channel string.""" - return "projects/{project}/locations/{location}/channels/{channel}".format( - project=project, - location=location, - channel=channel, - ) + return "projects/{project}/locations/{location}/channels/{channel}".format(project=project, location=location, channel=channel, ) @staticmethod - def parse_channel_path(path: str) -> Dict[str, str]: + def parse_channel_path(path: str) -> Dict[str,str]: """Parses a channel path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/channels/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/channels/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def channel_connection_path( - project: str, - location: str, - channel_connection: str, - ) -> str: + def channel_connection_path(project: str,location: str,channel_connection: str,) -> str: """Returns a fully-qualified channel_connection string.""" - return "projects/{project}/locations/{location}/channelConnections/{channel_connection}".format( - project=project, - location=location, - channel_connection=channel_connection, - ) + return "projects/{project}/locations/{location}/channelConnections/{channel_connection}".format(project=project, location=location, channel_connection=channel_connection, ) @staticmethod - def parse_channel_connection_path(path: str) -> Dict[str, str]: + def parse_channel_connection_path(path: str) -> Dict[str,str]: """Parses a channel_connection path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/channelConnections/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/channelConnections/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def cloud_function_path( - project: str, - location: str, - function: str, - ) -> str: + def cloud_function_path(project: str,location: str,function: str,) -> str: """Returns a fully-qualified cloud_function string.""" - return "projects/{project}/locations/{location}/functions/{function}".format( - project=project, - location=location, - function=function, - ) + return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) @staticmethod - def parse_cloud_function_path(path: str) -> Dict[str, str]: + def parse_cloud_function_path(path: str) -> Dict[str,str]: """Parses a cloud_function path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def crypto_key_path( - project: str, - location: str, - key_ring: str, - crypto_key: str, - ) -> str: + def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( - project=project, - location=location, - key_ring=key_ring, - crypto_key=crypto_key, - ) + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str, str]: + def parse_crypto_key_path(path: str) -> Dict[str,str]: """Parses a crypto_key path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def enrollment_path( - project: str, - location: str, - enrollment: str, - ) -> str: + def enrollment_path(project: str,location: str,enrollment: str,) -> str: """Returns a fully-qualified enrollment string.""" - return ( - "projects/{project}/locations/{location}/enrollments/{enrollment}".format( - project=project, - location=location, - enrollment=enrollment, - ) - ) + return "projects/{project}/locations/{location}/enrollments/{enrollment}".format(project=project, location=location, enrollment=enrollment, ) @staticmethod - def parse_enrollment_path(path: str) -> Dict[str, str]: + def parse_enrollment_path(path: str) -> Dict[str,str]: """Parses a enrollment path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/enrollments/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/enrollments/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def google_api_source_path( - project: str, - location: str, - google_api_source: str, - ) -> str: + def google_api_source_path(project: str,location: str,google_api_source: str,) -> str: """Returns a fully-qualified google_api_source string.""" - return "projects/{project}/locations/{location}/googleApiSources/{google_api_source}".format( - project=project, - location=location, - google_api_source=google_api_source, - ) + return "projects/{project}/locations/{location}/googleApiSources/{google_api_source}".format(project=project, location=location, google_api_source=google_api_source, ) @staticmethod - def parse_google_api_source_path(path: str) -> Dict[str, str]: + def parse_google_api_source_path(path: str) -> Dict[str,str]: """Parses a google_api_source path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/googleApiSources/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/googleApiSources/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def google_channel_config_path( - project: str, - location: str, - ) -> str: + def google_channel_config_path(project: str,location: str,) -> str: """Returns a fully-qualified google_channel_config string.""" - return "projects/{project}/locations/{location}/googleChannelConfig".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}/googleChannelConfig".format(project=project, location=location, ) @staticmethod - def parse_google_channel_config_path(path: str) -> Dict[str, str]: + def parse_google_channel_config_path(path: str) -> Dict[str,str]: """Parses a google_channel_config path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/googleChannelConfig$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/googleChannelConfig$", path) return m.groupdict() if m else {} @staticmethod - def message_bus_path( - project: str, - location: str, - message_bus: str, - ) -> str: + def message_bus_path(project: str,location: str,message_bus: str,) -> str: """Returns a fully-qualified message_bus string.""" - return ( - "projects/{project}/locations/{location}/messageBuses/{message_bus}".format( - project=project, - location=location, - message_bus=message_bus, - ) - ) + return "projects/{project}/locations/{location}/messageBuses/{message_bus}".format(project=project, location=location, message_bus=message_bus, ) @staticmethod - def parse_message_bus_path(path: str) -> Dict[str, str]: + def parse_message_bus_path(path: str) -> Dict[str,str]: """Parses a message_bus path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/messageBuses/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/messageBuses/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def network_attachment_path( - project: str, - region: str, - networkattachment: str, - ) -> str: + def network_attachment_path(project: str,region: str,networkattachment: str,) -> str: """Returns a fully-qualified network_attachment string.""" - return "projects/{project}/regions/{region}/networkAttachments/{networkattachment}".format( - project=project, - region=region, - networkattachment=networkattachment, - ) + return "projects/{project}/regions/{region}/networkAttachments/{networkattachment}".format(project=project, region=region, networkattachment=networkattachment, ) @staticmethod - def parse_network_attachment_path(path: str) -> Dict[str, str]: + def parse_network_attachment_path(path: str) -> Dict[str,str]: """Parses a network_attachment path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/regions/(?P.+?)/networkAttachments/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/regions/(?P.+?)/networkAttachments/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def pipeline_path( - project: str, - location: str, - pipeline: str, - ) -> str: + def pipeline_path(project: str,location: str,pipeline: str,) -> str: """Returns a fully-qualified pipeline string.""" - return "projects/{project}/locations/{location}/pipelines/{pipeline}".format( - project=project, - location=location, - pipeline=pipeline, - ) + return "projects/{project}/locations/{location}/pipelines/{pipeline}".format(project=project, location=location, pipeline=pipeline, ) @staticmethod - def parse_pipeline_path(path: str) -> Dict[str, str]: + def parse_pipeline_path(path: str) -> Dict[str,str]: """Parses a pipeline path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/pipelines/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/pipelines/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def provider_path( - project: str, - location: str, - provider: str, - ) -> str: + def provider_path(project: str,location: str,provider: str,) -> str: """Returns a fully-qualified provider string.""" - return "projects/{project}/locations/{location}/providers/{provider}".format( - project=project, - location=location, - provider=provider, - ) + return "projects/{project}/locations/{location}/providers/{provider}".format(project=project, location=location, provider=provider, ) @staticmethod - def parse_provider_path(path: str) -> Dict[str, str]: + def parse_provider_path(path: str) -> Dict[str,str]: """Parses a provider path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/providers/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/providers/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod @@ -463,173 +312,112 @@ def service_path() -> str: return "*".format() @staticmethod - def parse_service_path(path: str) -> Dict[str, str]: + def parse_service_path(path: str) -> Dict[str,str]: """Parses a service path into its component segments.""" m = re.match(r"^.*$", path) return m.groupdict() if m else {} @staticmethod - def service_account_path( - project: str, - service_account: str, - ) -> str: + def service_account_path(project: str,service_account: str,) -> str: """Returns a fully-qualified service_account string.""" - return "projects/{project}/serviceAccounts/{service_account}".format( - project=project, - service_account=service_account, - ) + return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) @staticmethod - def parse_service_account_path(path: str) -> Dict[str, str]: + def parse_service_account_path(path: str) -> Dict[str,str]: """Parses a service_account path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def topic_path( - project: str, - topic: str, - ) -> str: + def topic_path(project: str,topic: str,) -> str: """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format( - project=project, - topic=topic, - ) + return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) @staticmethod - def parse_topic_path(path: str) -> Dict[str, str]: + def parse_topic_path(path: str) -> Dict[str,str]: """Parses a topic path into its component segments.""" m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def trigger_path( - project: str, - location: str, - trigger: str, - ) -> str: + def trigger_path(project: str,location: str,trigger: str,) -> str: """Returns a fully-qualified trigger string.""" - return "projects/{project}/locations/{location}/triggers/{trigger}".format( - project=project, - location=location, - trigger=trigger, - ) + return "projects/{project}/locations/{location}/triggers/{trigger}".format(project=project, location=location, trigger=trigger, ) @staticmethod - def parse_trigger_path(path: str) -> Dict[str, str]: + def parse_trigger_path(path: str) -> Dict[str,str]: """Parses a trigger path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/triggers/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/triggers/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def workflow_path( - project: str, - location: str, - workflow: str, - ) -> str: + def workflow_path(project: str,location: str,workflow: str,) -> str: """Returns a fully-qualified workflow string.""" - return "projects/{project}/locations/{location}/workflows/{workflow}".format( - project=project, - location=location, - workflow=workflow, - ) + return "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) @staticmethod - def parse_workflow_path(path: str) -> Dict[str, str]: + def parse_workflow_path(path: str) -> Dict[str,str]: """Parses a workflow path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -661,18 +449,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -685,10 +469,8 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -727,18 +509,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -771,16 +550,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, EventarcTransport, Callable[..., EventarcTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, EventarcTransport, Callable[..., EventarcTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the eventarc client. Args: @@ -838,23 +613,13 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - read_environment_variables() - ) - self._client_cert_source = EventarcClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = get_universe_domain( - universe_domain_opt, - self._universe_domain_env, - default_universe=EventarcClient._DEFAULT_UNIVERSE, - ) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() + self._client_cert_source = EventarcClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=EventarcClient._DEFAULT_UNIVERSE) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -866,9 +631,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -877,40 +640,35 @@ def __init__( if transport_provided: # transport is a EventarcTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = cast(EventarcTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = self._api_endpoint or get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=EventarcClient._DEFAULT_UNIVERSE, - default_mtls_endpoint=EventarcClient.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=EventarcClient._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" - or (self._use_mtls_endpoint == "auto" and self._client_cert_source), - ) + self._api_endpoint = (self._api_endpoint or + get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=EventarcClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=EventarcClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=EventarcClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" or ( + self._use_mtls_endpoint == "auto" and self._client_cert_source + ), + )) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[EventarcTransport], Callable[..., EventarcTransport] - ] = ( + transport_init: Union[Type[EventarcTransport], Callable[..., EventarcTransport]] = ( EventarcClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., EventarcTransport], transport) @@ -939,46 +697,33 @@ def __init__( "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **( - {"client_options": client_options} - if client_options is not None - else {} - ), + **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.eventarc_v1.EventarcClient`.", - extra={ + extra = { "serviceName": "google.cloud.eventarc.v1.Eventarc", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.cloud.eventarc.v1.Eventarc", "credentialsType": None, - }, + } ) - def get_trigger( - self, - request: Optional[Union[eventarc.GetTriggerRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> trigger.Trigger: + def get_trigger(self, + request: Optional[Union[eventarc.GetTriggerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> trigger.Trigger: r"""Get a single trigger. .. code-block:: python @@ -1036,14 +781,10 @@ def sample_get_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1061,7 +802,9 @@ def sample_get_trigger(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1078,15 +821,14 @@ def sample_get_trigger(): # Done; return the response. return response - def list_triggers( - self, - request: Optional[Union[eventarc.ListTriggersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListTriggersPager: + def list_triggers(self, + request: Optional[Union[eventarc.ListTriggersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTriggersPager: r"""List triggers. .. code-block:: python @@ -1147,14 +889,10 @@ def sample_list_triggers(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1172,7 +910,9 @@ def sample_list_triggers(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1200,17 +940,16 @@ def sample_list_triggers(): # Done; return the response. return response - def create_trigger( - self, - request: Optional[Union[eventarc.CreateTriggerRequest, dict]] = None, - *, - parent: Optional[str] = None, - trigger: Optional[gce_trigger.Trigger] = None, - trigger_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_trigger(self, + request: Optional[Union[eventarc.CreateTriggerRequest, dict]] = None, + *, + parent: Optional[str] = None, + trigger: Optional[gce_trigger.Trigger] = None, + trigger_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new trigger in a particular project and location. @@ -1297,14 +1036,10 @@ def sample_create_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, trigger, trigger_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1326,7 +1061,9 @@ def sample_create_trigger(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1351,17 +1088,16 @@ def sample_create_trigger(): # Done; return the response. return response - def update_trigger( - self, - request: Optional[Union[eventarc.UpdateTriggerRequest, dict]] = None, - *, - trigger: Optional[gce_trigger.Trigger] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - allow_missing: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_trigger(self, + request: Optional[Union[eventarc.UpdateTriggerRequest, dict]] = None, + *, + trigger: Optional[gce_trigger.Trigger] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + allow_missing: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single trigger. .. code-block:: python @@ -1440,14 +1176,10 @@ def sample_update_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [trigger, update_mask, allow_missing] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1469,9 +1201,9 @@ def sample_update_trigger(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("trigger.name", request.trigger.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("trigger.name", request.trigger.name), + )), ) # Validate the universe domain. @@ -1496,16 +1228,15 @@ def sample_update_trigger(): # Done; return the response. return response - def delete_trigger( - self, - request: Optional[Union[eventarc.DeleteTriggerRequest, dict]] = None, - *, - name: Optional[str] = None, - allow_missing: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_trigger(self, + request: Optional[Union[eventarc.DeleteTriggerRequest, dict]] = None, + *, + name: Optional[str] = None, + allow_missing: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single trigger. .. code-block:: python @@ -1578,14 +1309,10 @@ def sample_delete_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, allow_missing] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1605,7 +1332,9 @@ def sample_delete_trigger(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1630,15 +1359,14 @@ def sample_delete_trigger(): # Done; return the response. return response - def get_channel( - self, - request: Optional[Union[eventarc.GetChannelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> channel.Channel: + def get_channel(self, + request: Optional[Union[eventarc.GetChannelRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> channel.Channel: r"""Get a single Channel. .. code-block:: python @@ -1702,14 +1430,10 @@ def sample_get_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1727,7 +1451,9 @@ def sample_get_channel(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1744,15 +1470,14 @@ def sample_get_channel(): # Done; return the response. return response - def list_channels( - self, - request: Optional[Union[eventarc.ListChannelsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListChannelsPager: + def list_channels(self, + request: Optional[Union[eventarc.ListChannelsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListChannelsPager: r"""List channels. .. code-block:: python @@ -1813,14 +1538,10 @@ def sample_list_channels(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1838,7 +1559,9 @@ def sample_list_channels(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1866,17 +1589,16 @@ def sample_list_channels(): # Done; return the response. return response - def create_channel( - self, - request: Optional[Union[eventarc.CreateChannelRequest, dict]] = None, - *, - parent: Optional[str] = None, - channel: Optional[gce_channel.Channel] = None, - channel_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_channel(self, + request: Optional[Union[eventarc.CreateChannelRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel: Optional[gce_channel.Channel] = None, + channel_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new channel in a particular project and location. @@ -1963,14 +1685,10 @@ def sample_create_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, channel, channel_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1992,7 +1710,9 @@ def sample_create_channel(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2017,16 +1737,15 @@ def sample_create_channel(): # Done; return the response. return response - def update_channel( - self, - request: Optional[Union[eventarc.UpdateChannelRequest, dict]] = None, - *, - channel: Optional[gce_channel.Channel] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_channel(self, + request: Optional[Union[eventarc.UpdateChannelRequest, dict]] = None, + *, + channel: Optional[gce_channel.Channel] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single channel. .. code-block:: python @@ -2100,14 +1819,10 @@ def sample_update_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [channel, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2127,9 +1842,9 @@ def sample_update_channel(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("channel.name", request.channel.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("channel.name", request.channel.name), + )), ) # Validate the universe domain. @@ -2154,15 +1869,14 @@ def sample_update_channel(): # Done; return the response. return response - def delete_channel( - self, - request: Optional[Union[eventarc.DeleteChannelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_channel(self, + request: Optional[Union[eventarc.DeleteChannelRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single channel. .. code-block:: python @@ -2230,14 +1944,10 @@ def sample_delete_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2255,7 +1965,9 @@ def sample_delete_channel(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2280,15 +1992,14 @@ def sample_delete_channel(): # Done; return the response. return response - def get_provider( - self, - request: Optional[Union[eventarc.GetProviderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> discovery.Provider: + def get_provider(self, + request: Optional[Union[eventarc.GetProviderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> discovery.Provider: r"""Get a single Provider. .. code-block:: python @@ -2346,14 +2057,10 @@ def sample_get_provider(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2371,7 +2078,9 @@ def sample_get_provider(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2388,15 +2097,14 @@ def sample_get_provider(): # Done; return the response. return response - def list_providers( - self, - request: Optional[Union[eventarc.ListProvidersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProvidersPager: + def list_providers(self, + request: Optional[Union[eventarc.ListProvidersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProvidersPager: r"""List providers. .. code-block:: python @@ -2457,14 +2165,10 @@ def sample_list_providers(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2482,7 +2186,9 @@ def sample_list_providers(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2510,15 +2216,14 @@ def sample_list_providers(): # Done; return the response. return response - def get_channel_connection( - self, - request: Optional[Union[eventarc.GetChannelConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> channel_connection.ChannelConnection: + def get_channel_connection(self, + request: Optional[Union[eventarc.GetChannelConnectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> channel_connection.ChannelConnection: r"""Get a single ChannelConnection. .. code-block:: python @@ -2581,14 +2286,10 @@ def sample_get_channel_connection(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2606,7 +2307,9 @@ def sample_get_channel_connection(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2623,15 +2326,14 @@ def sample_get_channel_connection(): # Done; return the response. return response - def list_channel_connections( - self, - request: Optional[Union[eventarc.ListChannelConnectionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListChannelConnectionsPager: + def list_channel_connections(self, + request: Optional[Union[eventarc.ListChannelConnectionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListChannelConnectionsPager: r"""List channel connections. .. code-block:: python @@ -2693,14 +2395,10 @@ def sample_list_channel_connections(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2718,7 +2416,9 @@ def sample_list_channel_connections(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2746,17 +2446,16 @@ def sample_list_channel_connections(): # Done; return the response. return response - def create_channel_connection( - self, - request: Optional[Union[eventarc.CreateChannelConnectionRequest, dict]] = None, - *, - parent: Optional[str] = None, - channel_connection: Optional[gce_channel_connection.ChannelConnection] = None, - channel_connection_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_channel_connection(self, + request: Optional[Union[eventarc.CreateChannelConnectionRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel_connection: Optional[gce_channel_connection.ChannelConnection] = None, + channel_connection_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new ChannelConnection in a particular project and location. @@ -2844,14 +2543,10 @@ def sample_create_channel_connection(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, channel_connection, channel_connection_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2868,14 +2563,14 @@ def sample_create_channel_connection(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.create_channel_connection - ] + rpc = self._transport._wrapped_methods[self._transport.create_channel_connection] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2900,15 +2595,14 @@ def sample_create_channel_connection(): # Done; return the response. return response - def delete_channel_connection( - self, - request: Optional[Union[eventarc.DeleteChannelConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_channel_connection(self, + request: Optional[Union[eventarc.DeleteChannelConnectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single ChannelConnection. .. code-block:: python @@ -2975,14 +2669,10 @@ def sample_delete_channel_connection(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2995,14 +2685,14 @@ def sample_delete_channel_connection(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.delete_channel_connection - ] + rpc = self._transport._wrapped_methods[self._transport.delete_channel_connection] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3027,15 +2717,14 @@ def sample_delete_channel_connection(): # Done; return the response. return response - def get_google_channel_config( - self, - request: Optional[Union[eventarc.GetGoogleChannelConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> google_channel_config.GoogleChannelConfig: + def get_google_channel_config(self, + request: Optional[Union[eventarc.GetGoogleChannelConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> google_channel_config.GoogleChannelConfig: r"""Get a GoogleChannelConfig. The name of the GoogleChannelConfig in the response is ALWAYS coded with projectID. @@ -3101,14 +2790,10 @@ def sample_get_google_channel_config(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3121,14 +2806,14 @@ def sample_get_google_channel_config(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.get_google_channel_config - ] + rpc = self._transport._wrapped_methods[self._transport.get_google_channel_config] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3145,20 +2830,15 @@ def sample_get_google_channel_config(): # Done; return the response. return response - def update_google_channel_config( - self, - request: Optional[ - Union[eventarc.UpdateGoogleChannelConfigRequest, dict] - ] = None, - *, - google_channel_config: Optional[ - gce_google_channel_config.GoogleChannelConfig - ] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gce_google_channel_config.GoogleChannelConfig: + def update_google_channel_config(self, + request: Optional[Union[eventarc.UpdateGoogleChannelConfigRequest, dict]] = None, + *, + google_channel_config: Optional[gce_google_channel_config.GoogleChannelConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gce_google_channel_config.GoogleChannelConfig: r"""Update a single GoogleChannelConfig .. code-block:: python @@ -3232,14 +2912,10 @@ def sample_update_google_channel_config(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [google_channel_config, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3254,16 +2930,14 @@ def sample_update_google_channel_config(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.update_google_channel_config - ] + rpc = self._transport._wrapped_methods[self._transport.update_google_channel_config] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("google_channel_config.name", request.google_channel_config.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("google_channel_config.name", request.google_channel_config.name), + )), ) # Validate the universe domain. @@ -3280,15 +2954,14 @@ def sample_update_google_channel_config(): # Done; return the response. return response - def get_message_bus( - self, - request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> message_bus.MessageBus: + def get_message_bus(self, + request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> message_bus.MessageBus: r"""Get a single MessageBus. .. code-block:: python @@ -3352,14 +3025,10 @@ def sample_get_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3377,7 +3046,9 @@ def sample_get_message_bus(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3394,15 +3065,14 @@ def sample_get_message_bus(): # Done; return the response. return response - def list_message_buses( - self, - request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMessageBusesPager: + def list_message_buses(self, + request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMessageBusesPager: r"""List message buses. .. code-block:: python @@ -3463,14 +3133,10 @@ def sample_list_message_buses(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3488,7 +3154,9 @@ def sample_list_message_buses(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3516,17 +3184,14 @@ def sample_list_message_buses(): # Done; return the response. return response - def list_message_bus_enrollments( - self, - request: Optional[ - Union[eventarc.ListMessageBusEnrollmentsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMessageBusEnrollmentsPager: + def list_message_bus_enrollments(self, + request: Optional[Union[eventarc.ListMessageBusEnrollmentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMessageBusEnrollmentsPager: r"""List message bus enrollments. .. code-block:: python @@ -3588,14 +3253,10 @@ def sample_list_message_bus_enrollments(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3608,14 +3269,14 @@ def sample_list_message_bus_enrollments(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.list_message_bus_enrollments - ] + rpc = self._transport._wrapped_methods[self._transport.list_message_bus_enrollments] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3643,17 +3304,16 @@ def sample_list_message_bus_enrollments(): # Done; return the response. return response - def create_message_bus( - self, - request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, - *, - parent: Optional[str] = None, - message_bus: Optional[gce_message_bus.MessageBus] = None, - message_bus_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_message_bus(self, + request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, + *, + parent: Optional[str] = None, + message_bus: Optional[gce_message_bus.MessageBus] = None, + message_bus_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new MessageBus in a particular project and location. @@ -3735,14 +3395,10 @@ def sample_create_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, message_bus, message_bus_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3764,7 +3420,9 @@ def sample_create_message_bus(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3789,16 +3447,15 @@ def sample_create_message_bus(): # Done; return the response. return response - def update_message_bus( - self, - request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, - *, - message_bus: Optional[gce_message_bus.MessageBus] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_message_bus(self, + request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, + *, + message_bus: Optional[gce_message_bus.MessageBus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single message bus. .. code-block:: python @@ -3874,14 +3531,10 @@ def sample_update_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [message_bus, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3901,9 +3554,9 @@ def sample_update_message_bus(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("message_bus.name", request.message_bus.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("message_bus.name", request.message_bus.name), + )), ) # Validate the universe domain. @@ -3928,16 +3581,15 @@ def sample_update_message_bus(): # Done; return the response. return response - def delete_message_bus( - self, - request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_message_bus(self, + request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single message bus. .. code-block:: python @@ -4012,14 +3664,10 @@ def sample_delete_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4039,7 +3687,9 @@ def sample_delete_message_bus(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -4064,15 +3714,14 @@ def sample_delete_message_bus(): # Done; return the response. return response - def get_enrollment( - self, - request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> enrollment.Enrollment: + def get_enrollment(self, + request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> enrollment.Enrollment: r"""Get a single Enrollment. .. code-block:: python @@ -4134,14 +3783,10 @@ def sample_get_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4159,7 +3804,9 @@ def sample_get_enrollment(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -4176,15 +3823,14 @@ def sample_get_enrollment(): # Done; return the response. return response - def list_enrollments( - self, - request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListEnrollmentsPager: + def list_enrollments(self, + request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEnrollmentsPager: r"""List Enrollments. .. code-block:: python @@ -4245,14 +3891,10 @@ def sample_list_enrollments(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4270,7 +3912,9 @@ def sample_list_enrollments(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -4298,17 +3942,16 @@ def sample_list_enrollments(): # Done; return the response. return response - def create_enrollment( - self, - request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, - *, - parent: Optional[str] = None, - enrollment: Optional[gce_enrollment.Enrollment] = None, - enrollment_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_enrollment(self, + request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + enrollment: Optional[gce_enrollment.Enrollment] = None, + enrollment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new Enrollment in a particular project and location. @@ -4395,14 +4038,10 @@ def sample_create_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, enrollment, enrollment_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4424,7 +4063,9 @@ def sample_create_enrollment(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -4449,16 +4090,15 @@ def sample_create_enrollment(): # Done; return the response. return response - def update_enrollment( - self, - request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, - *, - enrollment: Optional[gce_enrollment.Enrollment] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_enrollment(self, + request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, + *, + enrollment: Optional[gce_enrollment.Enrollment] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single Enrollment. .. code-block:: python @@ -4539,14 +4179,10 @@ def sample_update_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [enrollment, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4566,9 +4202,9 @@ def sample_update_enrollment(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("enrollment.name", request.enrollment.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("enrollment.name", request.enrollment.name), + )), ) # Validate the universe domain. @@ -4593,16 +4229,15 @@ def sample_update_enrollment(): # Done; return the response. return response - def delete_enrollment( - self, - request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_enrollment(self, + request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single Enrollment. .. code-block:: python @@ -4676,14 +4311,10 @@ def sample_delete_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4703,7 +4334,9 @@ def sample_delete_enrollment(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -4728,15 +4361,14 @@ def sample_delete_enrollment(): # Done; return the response. return response - def get_pipeline( - self, - request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pipeline.Pipeline: + def get_pipeline(self, + request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pipeline.Pipeline: r"""Get a single Pipeline. .. code-block:: python @@ -4794,14 +4426,10 @@ def sample_get_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4819,7 +4447,9 @@ def sample_get_pipeline(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -4836,15 +4466,14 @@ def sample_get_pipeline(): # Done; return the response. return response - def list_pipelines( - self, - request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListPipelinesPager: + def list_pipelines(self, + request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPipelinesPager: r"""List pipelines. .. code-block:: python @@ -4906,14 +4535,10 @@ def sample_list_pipelines(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4931,7 +4556,9 @@ def sample_list_pipelines(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -4959,17 +4586,16 @@ def sample_list_pipelines(): # Done; return the response. return response - def create_pipeline( - self, - request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, - *, - parent: Optional[str] = None, - pipeline: Optional[gce_pipeline.Pipeline] = None, - pipeline_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_pipeline(self, + request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, + *, + parent: Optional[str] = None, + pipeline: Optional[gce_pipeline.Pipeline] = None, + pipeline_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new Pipeline in a particular project and location. @@ -5053,14 +4679,10 @@ def sample_create_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, pipeline, pipeline_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5082,7 +4704,9 @@ def sample_create_pipeline(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -5107,16 +4731,15 @@ def sample_create_pipeline(): # Done; return the response. return response - def update_pipeline( - self, - request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, - *, - pipeline: Optional[gce_pipeline.Pipeline] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_pipeline(self, + request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, + *, + pipeline: Optional[gce_pipeline.Pipeline] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single pipeline. .. code-block:: python @@ -5192,14 +4815,10 @@ def sample_update_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [pipeline, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5219,9 +4838,9 @@ def sample_update_pipeline(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("pipeline.name", request.pipeline.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("pipeline.name", request.pipeline.name), + )), ) # Validate the universe domain. @@ -5246,16 +4865,15 @@ def sample_update_pipeline(): # Done; return the response. return response - def delete_pipeline( - self, - request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_pipeline(self, + request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single pipeline. .. code-block:: python @@ -5328,14 +4946,10 @@ def sample_delete_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5355,7 +4969,9 @@ def sample_delete_pipeline(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -5380,15 +4996,14 @@ def sample_delete_pipeline(): # Done; return the response. return response - def get_google_api_source( - self, - request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> google_api_source.GoogleApiSource: + def get_google_api_source(self, + request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> google_api_source.GoogleApiSource: r"""Get a single GoogleApiSource. .. code-block:: python @@ -5447,14 +5062,10 @@ def sample_get_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5472,7 +5083,9 @@ def sample_get_google_api_source(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -5489,15 +5102,14 @@ def sample_get_google_api_source(): # Done; return the response. return response - def list_google_api_sources( - self, - request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListGoogleApiSourcesPager: + def list_google_api_sources(self, + request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListGoogleApiSourcesPager: r"""List GoogleApiSources. .. code-block:: python @@ -5559,14 +5171,10 @@ def sample_list_google_api_sources(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5584,7 +5192,9 @@ def sample_list_google_api_sources(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -5612,17 +5222,16 @@ def sample_list_google_api_sources(): # Done; return the response. return response - def create_google_api_source( - self, - request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, - google_api_source_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_google_api_source(self, + request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + google_api_source_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new GoogleApiSource in a particular project and location. @@ -5710,14 +5319,10 @@ def sample_create_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, google_api_source, google_api_source_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5739,7 +5344,9 @@ def sample_create_google_api_source(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -5764,16 +5371,15 @@ def sample_create_google_api_source(): # Done; return the response. return response - def update_google_api_source( - self, - request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, - *, - google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_google_api_source(self, + request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, + *, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single GoogleApiSource. .. code-block:: python @@ -5853,14 +5459,10 @@ def sample_update_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [google_api_source, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5880,9 +5482,9 @@ def sample_update_google_api_source(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("google_api_source.name", request.google_api_source.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("google_api_source.name", request.google_api_source.name), + )), ) # Validate the universe domain. @@ -5907,16 +5509,15 @@ def sample_update_google_api_source(): # Done; return the response. return response - def delete_google_api_source( - self, - request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_google_api_source(self, + request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single GoogleApiSource. .. code-block:: python @@ -5990,14 +5591,10 @@ def sample_delete_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -6017,7 +5614,9 @@ def sample_delete_google_api_source(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -6097,7 +5696,8 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -6106,11 +5706,7 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -6160,7 +5756,8 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -6169,11 +5766,7 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -6227,19 +5820,15 @@ def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def cancel_operation( self, @@ -6286,19 +5875,15 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def set_iam_policy( self, @@ -6409,8 +5994,7 @@ def set_iam_policy( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request_pb.resource),) - ), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -6419,11 +6003,7 @@ def set_iam_policy( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -6541,8 +6121,7 @@ def get_iam_policy( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request_pb.resource),) - ), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -6551,11 +6130,7 @@ def get_iam_policy( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -6611,8 +6186,7 @@ def test_iam_permissions( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request_pb.resource),) - ), + (("resource", request_pb.resource),)), ) # Validate the universe domain. @@ -6621,11 +6195,7 @@ def test_iam_permissions( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -6675,7 +6245,8 @@ def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -6684,11 +6255,7 @@ def get_location( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -6738,7 +6305,8 @@ def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -6747,11 +6315,7 @@ def list_locations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -6760,9 +6324,9 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("EventarcClient",) +__all__ = ( + "EventarcClient", +) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py index 96fb7810b76a..af33d16a7beb 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py @@ -17,41 +17,36 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import google.api_core +from google.cloud.eventarc_v1 import gapic_version as package_version + import google.auth # type: ignore -import google.protobuf +import google.api_core from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.cloud.eventarc_v1 import gapic_version as package_version -from google.cloud.eventarc_v1.types import ( - channel, - channel_connection, - discovery, - enrollment, - eventarc, - google_api_source, - google_channel_config, - message_bus, - pipeline, - trigger, -) -from google.cloud.eventarc_v1.types import ( - google_channel_config as gce_google_channel_config, -) -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import ( - iam_policy_pb2, # type: ignore - policy_pb2, # type: ignore -) -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +from google.cloud.eventarc_v1.types import channel +from google.cloud.eventarc_v1.types import channel_connection +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source +from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import trigger +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ # Check once at module load time whether google-api-core's wrap_method supports @@ -65,24 +60,25 @@ class EventarcTransport(abc.ABC): """Abstract transport class for Eventarc.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) - DEFAULT_HOST: str = "eventarc.googleapis.com" + DEFAULT_HOST: str = 'eventarc.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -124,43 +120,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host self._client_options = client_options @@ -187,12 +171,7 @@ def _wrap_method(self, func, *args, **kwargs): # of google-api-core is installed (which does not accept client_options, etc.). # Excluded from coverage because our CI and testing environments always install # a modern version of google-api-core that supports tracing. - for k in [ - "client_options", - "method_name", - "is_streaming", - "kind", - ]: # pragma: NO COVER + for k in ["client_options", "method_name", "is_streaming", "kind"]: # pragma: NO COVER kwargs.pop(k, None) # pragma: NO COVER return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER @@ -478,14 +457,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -495,383 +474,354 @@ def operations_client(self): raise NotImplementedError() @property - def get_trigger( - self, - ) -> Callable[ - [eventarc.GetTriggerRequest], Union[trigger.Trigger, Awaitable[trigger.Trigger]] - ]: + def get_trigger(self) -> Callable[ + [eventarc.GetTriggerRequest], + Union[ + trigger.Trigger, + Awaitable[trigger.Trigger] + ]]: raise NotImplementedError() @property - def list_triggers( - self, - ) -> Callable[ - [eventarc.ListTriggersRequest], - Union[eventarc.ListTriggersResponse, Awaitable[eventarc.ListTriggersResponse]], - ]: + def list_triggers(self) -> Callable[ + [eventarc.ListTriggersRequest], + Union[ + eventarc.ListTriggersResponse, + Awaitable[eventarc.ListTriggersResponse] + ]]: raise NotImplementedError() @property - def create_trigger( - self, - ) -> Callable[ - [eventarc.CreateTriggerRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_trigger(self) -> Callable[ + [eventarc.CreateTriggerRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def update_trigger( - self, - ) -> Callable[ - [eventarc.UpdateTriggerRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def update_trigger(self) -> Callable[ + [eventarc.UpdateTriggerRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def delete_trigger( - self, - ) -> Callable[ - [eventarc.DeleteTriggerRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def delete_trigger(self) -> Callable[ + [eventarc.DeleteTriggerRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def get_channel( - self, - ) -> Callable[ - [eventarc.GetChannelRequest], Union[channel.Channel, Awaitable[channel.Channel]] - ]: + def get_channel(self) -> Callable[ + [eventarc.GetChannelRequest], + Union[ + channel.Channel, + Awaitable[channel.Channel] + ]]: raise NotImplementedError() @property - def list_channels( - self, - ) -> Callable[ - [eventarc.ListChannelsRequest], - Union[eventarc.ListChannelsResponse, Awaitable[eventarc.ListChannelsResponse]], - ]: + def list_channels(self) -> Callable[ + [eventarc.ListChannelsRequest], + Union[ + eventarc.ListChannelsResponse, + Awaitable[eventarc.ListChannelsResponse] + ]]: raise NotImplementedError() @property - def create_channel_( - self, - ) -> Callable[ - [eventarc.CreateChannelRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_channel_(self) -> Callable[ + [eventarc.CreateChannelRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def update_channel( - self, - ) -> Callable[ - [eventarc.UpdateChannelRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def update_channel(self) -> Callable[ + [eventarc.UpdateChannelRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def delete_channel( - self, - ) -> Callable[ - [eventarc.DeleteChannelRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def delete_channel(self) -> Callable[ + [eventarc.DeleteChannelRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def get_provider( - self, - ) -> Callable[ - [eventarc.GetProviderRequest], - Union[discovery.Provider, Awaitable[discovery.Provider]], - ]: + def get_provider(self) -> Callable[ + [eventarc.GetProviderRequest], + Union[ + discovery.Provider, + Awaitable[discovery.Provider] + ]]: raise NotImplementedError() @property - def list_providers( - self, - ) -> Callable[ - [eventarc.ListProvidersRequest], - Union[ - eventarc.ListProvidersResponse, Awaitable[eventarc.ListProvidersResponse] - ], - ]: + def list_providers(self) -> Callable[ + [eventarc.ListProvidersRequest], + Union[ + eventarc.ListProvidersResponse, + Awaitable[eventarc.ListProvidersResponse] + ]]: raise NotImplementedError() @property - def get_channel_connection( - self, - ) -> Callable[ - [eventarc.GetChannelConnectionRequest], - Union[ - channel_connection.ChannelConnection, - Awaitable[channel_connection.ChannelConnection], - ], - ]: + def get_channel_connection(self) -> Callable[ + [eventarc.GetChannelConnectionRequest], + Union[ + channel_connection.ChannelConnection, + Awaitable[channel_connection.ChannelConnection] + ]]: raise NotImplementedError() @property - def list_channel_connections( - self, - ) -> Callable[ - [eventarc.ListChannelConnectionsRequest], - Union[ - eventarc.ListChannelConnectionsResponse, - Awaitable[eventarc.ListChannelConnectionsResponse], - ], - ]: + def list_channel_connections(self) -> Callable[ + [eventarc.ListChannelConnectionsRequest], + Union[ + eventarc.ListChannelConnectionsResponse, + Awaitable[eventarc.ListChannelConnectionsResponse] + ]]: raise NotImplementedError() @property - def create_channel_connection( - self, - ) -> Callable[ - [eventarc.CreateChannelConnectionRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_channel_connection(self) -> Callable[ + [eventarc.CreateChannelConnectionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def delete_channel_connection( - self, - ) -> Callable[ - [eventarc.DeleteChannelConnectionRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def delete_channel_connection(self) -> Callable[ + [eventarc.DeleteChannelConnectionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def get_google_channel_config( - self, - ) -> Callable[ - [eventarc.GetGoogleChannelConfigRequest], - Union[ - google_channel_config.GoogleChannelConfig, - Awaitable[google_channel_config.GoogleChannelConfig], - ], - ]: + def get_google_channel_config(self) -> Callable[ + [eventarc.GetGoogleChannelConfigRequest], + Union[ + google_channel_config.GoogleChannelConfig, + Awaitable[google_channel_config.GoogleChannelConfig] + ]]: raise NotImplementedError() @property - def update_google_channel_config( - self, - ) -> Callable[ - [eventarc.UpdateGoogleChannelConfigRequest], - Union[ - gce_google_channel_config.GoogleChannelConfig, - Awaitable[gce_google_channel_config.GoogleChannelConfig], - ], - ]: + def update_google_channel_config(self) -> Callable[ + [eventarc.UpdateGoogleChannelConfigRequest], + Union[ + gce_google_channel_config.GoogleChannelConfig, + Awaitable[gce_google_channel_config.GoogleChannelConfig] + ]]: raise NotImplementedError() @property - def get_message_bus( - self, - ) -> Callable[ - [eventarc.GetMessageBusRequest], - Union[message_bus.MessageBus, Awaitable[message_bus.MessageBus]], - ]: + def get_message_bus(self) -> Callable[ + [eventarc.GetMessageBusRequest], + Union[ + message_bus.MessageBus, + Awaitable[message_bus.MessageBus] + ]]: raise NotImplementedError() @property - def list_message_buses( - self, - ) -> Callable[ - [eventarc.ListMessageBusesRequest], - Union[ - eventarc.ListMessageBusesResponse, - Awaitable[eventarc.ListMessageBusesResponse], - ], - ]: + def list_message_buses(self) -> Callable[ + [eventarc.ListMessageBusesRequest], + Union[ + eventarc.ListMessageBusesResponse, + Awaitable[eventarc.ListMessageBusesResponse] + ]]: raise NotImplementedError() @property - def list_message_bus_enrollments( - self, - ) -> Callable[ - [eventarc.ListMessageBusEnrollmentsRequest], - Union[ - eventarc.ListMessageBusEnrollmentsResponse, - Awaitable[eventarc.ListMessageBusEnrollmentsResponse], - ], - ]: + def list_message_bus_enrollments(self) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + Union[ + eventarc.ListMessageBusEnrollmentsResponse, + Awaitable[eventarc.ListMessageBusEnrollmentsResponse] + ]]: raise NotImplementedError() @property - def create_message_bus( - self, - ) -> Callable[ - [eventarc.CreateMessageBusRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_message_bus(self) -> Callable[ + [eventarc.CreateMessageBusRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def update_message_bus( - self, - ) -> Callable[ - [eventarc.UpdateMessageBusRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def update_message_bus(self) -> Callable[ + [eventarc.UpdateMessageBusRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def delete_message_bus( - self, - ) -> Callable[ - [eventarc.DeleteMessageBusRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def delete_message_bus(self) -> Callable[ + [eventarc.DeleteMessageBusRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def get_enrollment( - self, - ) -> Callable[ - [eventarc.GetEnrollmentRequest], - Union[enrollment.Enrollment, Awaitable[enrollment.Enrollment]], - ]: + def get_enrollment(self) -> Callable[ + [eventarc.GetEnrollmentRequest], + Union[ + enrollment.Enrollment, + Awaitable[enrollment.Enrollment] + ]]: raise NotImplementedError() @property - def list_enrollments( - self, - ) -> Callable[ - [eventarc.ListEnrollmentsRequest], - Union[ - eventarc.ListEnrollmentsResponse, - Awaitable[eventarc.ListEnrollmentsResponse], - ], - ]: + def list_enrollments(self) -> Callable[ + [eventarc.ListEnrollmentsRequest], + Union[ + eventarc.ListEnrollmentsResponse, + Awaitable[eventarc.ListEnrollmentsResponse] + ]]: raise NotImplementedError() @property - def create_enrollment( - self, - ) -> Callable[ - [eventarc.CreateEnrollmentRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_enrollment(self) -> Callable[ + [eventarc.CreateEnrollmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def update_enrollment( - self, - ) -> Callable[ - [eventarc.UpdateEnrollmentRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def update_enrollment(self) -> Callable[ + [eventarc.UpdateEnrollmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def delete_enrollment( - self, - ) -> Callable[ - [eventarc.DeleteEnrollmentRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def delete_enrollment(self) -> Callable[ + [eventarc.DeleteEnrollmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def get_pipeline( - self, - ) -> Callable[ - [eventarc.GetPipelineRequest], - Union[pipeline.Pipeline, Awaitable[pipeline.Pipeline]], - ]: + def get_pipeline(self) -> Callable[ + [eventarc.GetPipelineRequest], + Union[ + pipeline.Pipeline, + Awaitable[pipeline.Pipeline] + ]]: raise NotImplementedError() @property - def list_pipelines( - self, - ) -> Callable[ - [eventarc.ListPipelinesRequest], - Union[ - eventarc.ListPipelinesResponse, Awaitable[eventarc.ListPipelinesResponse] - ], - ]: + def list_pipelines(self) -> Callable[ + [eventarc.ListPipelinesRequest], + Union[ + eventarc.ListPipelinesResponse, + Awaitable[eventarc.ListPipelinesResponse] + ]]: raise NotImplementedError() @property - def create_pipeline( - self, - ) -> Callable[ - [eventarc.CreatePipelineRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_pipeline(self) -> Callable[ + [eventarc.CreatePipelineRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def update_pipeline( - self, - ) -> Callable[ - [eventarc.UpdatePipelineRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def update_pipeline(self) -> Callable[ + [eventarc.UpdatePipelineRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def delete_pipeline( - self, - ) -> Callable[ - [eventarc.DeletePipelineRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def delete_pipeline(self) -> Callable[ + [eventarc.DeletePipelineRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def get_google_api_source( - self, - ) -> Callable[ - [eventarc.GetGoogleApiSourceRequest], - Union[ - google_api_source.GoogleApiSource, - Awaitable[google_api_source.GoogleApiSource], - ], - ]: + def get_google_api_source(self) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], + Union[ + google_api_source.GoogleApiSource, + Awaitable[google_api_source.GoogleApiSource] + ]]: raise NotImplementedError() @property - def list_google_api_sources( - self, - ) -> Callable[ - [eventarc.ListGoogleApiSourcesRequest], - Union[ - eventarc.ListGoogleApiSourcesResponse, - Awaitable[eventarc.ListGoogleApiSourcesResponse], - ], - ]: + def list_google_api_sources(self) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], + Union[ + eventarc.ListGoogleApiSourcesResponse, + Awaitable[eventarc.ListGoogleApiSourcesResponse] + ]]: raise NotImplementedError() @property - def create_google_api_source( - self, - ) -> Callable[ - [eventarc.CreateGoogleApiSourceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_google_api_source(self) -> Callable[ + [eventarc.CreateGoogleApiSourceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def update_google_api_source( - self, - ) -> Callable[ - [eventarc.UpdateGoogleApiSourceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def update_google_api_source(self) -> Callable[ + [eventarc.UpdateGoogleApiSourceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def delete_google_api_source( - self, - ) -> Callable[ - [eventarc.DeleteGoogleApiSourceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def delete_google_api_source(self) -> Callable[ + [eventarc.DeleteGoogleApiSourceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property @@ -879,10 +829,7 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[ - operations_pb2.ListOperationsResponse, - Awaitable[operations_pb2.ListOperationsResponse], - ], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], ]: raise NotImplementedError() @@ -944,8 +891,7 @@ def test_iam_permissions( raise NotImplementedError() @property - def get_location( - self, + def get_location(self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -953,14 +899,10 @@ def get_location( raise NotImplementedError() @property - def list_locations( - self, + def list_locations(self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[ - locations_pb2.ListLocationsResponse, - Awaitable[locations_pb2.ListLocationsResponse], - ], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], ]: raise NotImplementedError() @@ -969,4 +911,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("EventarcTransport",) +__all__ = ( + 'EventarcTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py index 65dc139d76d4..be9025f227be 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py @@ -17,19 +17,17 @@ import logging as std_logging import pickle import warnings -from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ( - ClientInterceptor, # type: ignore[attr-defined] - ) + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1, operations_v1 - +from google.api_core import gapic_v1 # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -37,39 +35,33 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore -import google.protobuf.message -import proto # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.eventarc_v1.types import ( - channel, - channel_connection, - discovery, - enrollment, - eventarc, - google_api_source, - google_channel_config, - message_bus, - pipeline, - trigger, -) -from google.cloud.eventarc_v1.types import ( - google_channel_config as gce_google_channel_config, -) -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import ( - iam_policy_pb2, # type: ignore - policy_pb2, # type: ignore -) -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import proto # type: ignore -from .base import DEFAULT_CLIENT_INFO, EventarcTransport +from google.cloud.eventarc_v1.types import channel +from google.cloud.eventarc_v1.types import channel_connection +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source +from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import trigger +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import EventarcTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -79,9 +71,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -102,7 +92,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -113,11 +103,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -132,7 +118,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": client_call_details.method, "response": grpc_response, @@ -156,35 +142,32 @@ class EventarcGrpcTransport(EventarcTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "eventarc.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], + def __init__(self, *, + host: str = 'eventarc.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], + ] ] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -321,17 +304,9 @@ def __init__( channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) - ) - is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None and otel_interceptor not in channel_interceptors - and not any( - getattr(i, "_is_otel_interceptor", None) is True - for i in channel_interceptors - ) + and not any(getattr(i, "_is_otel_interceptor", None) is True for i in channel_interceptors) ): channel_interceptors.append(otel_interceptor) @@ -340,28 +315,22 @@ def __init__( "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors( - self._grpc_channel, channel_interceptors - ) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "eventarc.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'eventarc.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -397,12 +366,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -422,7 +392,9 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def get_trigger(self) -> Callable[[eventarc.GetTriggerRequest], trigger.Trigger]: + def get_trigger(self) -> Callable[ + [eventarc.GetTriggerRequest], + trigger.Trigger]: r"""Return a callable for the get trigger method over gRPC. Get a single trigger. @@ -437,18 +409,18 @@ def get_trigger(self) -> Callable[[eventarc.GetTriggerRequest], trigger.Trigger] # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_trigger" not in self._stubs: - self._stubs["get_trigger"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/GetTrigger", + if 'get_trigger' not in self._stubs: + self._stubs['get_trigger'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetTrigger', request_serializer=eventarc.GetTriggerRequest.serialize, response_deserializer=trigger.Trigger.deserialize, ) - return self._stubs["get_trigger"] + return self._stubs['get_trigger'] @property - def list_triggers( - self, - ) -> Callable[[eventarc.ListTriggersRequest], eventarc.ListTriggersResponse]: + def list_triggers(self) -> Callable[ + [eventarc.ListTriggersRequest], + eventarc.ListTriggersResponse]: r"""Return a callable for the list triggers method over gRPC. List triggers. @@ -463,18 +435,18 @@ def list_triggers( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_triggers" not in self._stubs: - self._stubs["list_triggers"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/ListTriggers", + if 'list_triggers' not in self._stubs: + self._stubs['list_triggers'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListTriggers', request_serializer=eventarc.ListTriggersRequest.serialize, response_deserializer=eventarc.ListTriggersResponse.deserialize, ) - return self._stubs["list_triggers"] + return self._stubs['list_triggers'] @property - def create_trigger( - self, - ) -> Callable[[eventarc.CreateTriggerRequest], operations_pb2.Operation]: + def create_trigger(self) -> Callable[ + [eventarc.CreateTriggerRequest], + operations_pb2.Operation]: r"""Return a callable for the create trigger method over gRPC. Create a new trigger in a particular project and @@ -490,18 +462,18 @@ def create_trigger( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_trigger" not in self._stubs: - self._stubs["create_trigger"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/CreateTrigger", + if 'create_trigger' not in self._stubs: + self._stubs['create_trigger'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateTrigger', request_serializer=eventarc.CreateTriggerRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_trigger"] + return self._stubs['create_trigger'] @property - def update_trigger( - self, - ) -> Callable[[eventarc.UpdateTriggerRequest], operations_pb2.Operation]: + def update_trigger(self) -> Callable[ + [eventarc.UpdateTriggerRequest], + operations_pb2.Operation]: r"""Return a callable for the update trigger method over gRPC. Update a single trigger. @@ -516,18 +488,18 @@ def update_trigger( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_trigger" not in self._stubs: - self._stubs["update_trigger"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/UpdateTrigger", + if 'update_trigger' not in self._stubs: + self._stubs['update_trigger'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateTrigger', request_serializer=eventarc.UpdateTriggerRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["update_trigger"] + return self._stubs['update_trigger'] @property - def delete_trigger( - self, - ) -> Callable[[eventarc.DeleteTriggerRequest], operations_pb2.Operation]: + def delete_trigger(self) -> Callable[ + [eventarc.DeleteTriggerRequest], + operations_pb2.Operation]: r"""Return a callable for the delete trigger method over gRPC. Delete a single trigger. @@ -542,16 +514,18 @@ def delete_trigger( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_trigger" not in self._stubs: - self._stubs["delete_trigger"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/DeleteTrigger", + if 'delete_trigger' not in self._stubs: + self._stubs['delete_trigger'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteTrigger', request_serializer=eventarc.DeleteTriggerRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["delete_trigger"] + return self._stubs['delete_trigger'] @property - def get_channel(self) -> Callable[[eventarc.GetChannelRequest], channel.Channel]: + def get_channel(self) -> Callable[ + [eventarc.GetChannelRequest], + channel.Channel]: r"""Return a callable for the get channel method over gRPC. Get a single Channel. @@ -566,18 +540,18 @@ def get_channel(self) -> Callable[[eventarc.GetChannelRequest], channel.Channel] # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_channel" not in self._stubs: - self._stubs["get_channel"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/GetChannel", + if 'get_channel' not in self._stubs: + self._stubs['get_channel'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetChannel', request_serializer=eventarc.GetChannelRequest.serialize, response_deserializer=channel.Channel.deserialize, ) - return self._stubs["get_channel"] + return self._stubs['get_channel'] @property - def list_channels( - self, - ) -> Callable[[eventarc.ListChannelsRequest], eventarc.ListChannelsResponse]: + def list_channels(self) -> Callable[ + [eventarc.ListChannelsRequest], + eventarc.ListChannelsResponse]: r"""Return a callable for the list channels method over gRPC. List channels. @@ -592,18 +566,18 @@ def list_channels( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_channels" not in self._stubs: - self._stubs["list_channels"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/ListChannels", + if 'list_channels' not in self._stubs: + self._stubs['list_channels'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListChannels', request_serializer=eventarc.ListChannelsRequest.serialize, response_deserializer=eventarc.ListChannelsResponse.deserialize, ) - return self._stubs["list_channels"] + return self._stubs['list_channels'] @property - def create_channel_( - self, - ) -> Callable[[eventarc.CreateChannelRequest], operations_pb2.Operation]: + def create_channel_(self) -> Callable[ + [eventarc.CreateChannelRequest], + operations_pb2.Operation]: r"""Return a callable for the create channel method over gRPC. Create a new channel in a particular project and @@ -619,18 +593,18 @@ def create_channel_( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_channel_" not in self._stubs: - self._stubs["create_channel_"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/CreateChannel", + if 'create_channel_' not in self._stubs: + self._stubs['create_channel_'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateChannel', request_serializer=eventarc.CreateChannelRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_channel_"] + return self._stubs['create_channel_'] @property - def update_channel( - self, - ) -> Callable[[eventarc.UpdateChannelRequest], operations_pb2.Operation]: + def update_channel(self) -> Callable[ + [eventarc.UpdateChannelRequest], + operations_pb2.Operation]: r"""Return a callable for the update channel method over gRPC. Update a single channel. @@ -645,18 +619,18 @@ def update_channel( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_channel" not in self._stubs: - self._stubs["update_channel"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/UpdateChannel", + if 'update_channel' not in self._stubs: + self._stubs['update_channel'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateChannel', request_serializer=eventarc.UpdateChannelRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["update_channel"] + return self._stubs['update_channel'] @property - def delete_channel( - self, - ) -> Callable[[eventarc.DeleteChannelRequest], operations_pb2.Operation]: + def delete_channel(self) -> Callable[ + [eventarc.DeleteChannelRequest], + operations_pb2.Operation]: r"""Return a callable for the delete channel method over gRPC. Delete a single channel. @@ -671,18 +645,18 @@ def delete_channel( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_channel" not in self._stubs: - self._stubs["delete_channel"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/DeleteChannel", + if 'delete_channel' not in self._stubs: + self._stubs['delete_channel'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteChannel', request_serializer=eventarc.DeleteChannelRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["delete_channel"] + return self._stubs['delete_channel'] @property - def get_provider( - self, - ) -> Callable[[eventarc.GetProviderRequest], discovery.Provider]: + def get_provider(self) -> Callable[ + [eventarc.GetProviderRequest], + discovery.Provider]: r"""Return a callable for the get provider method over gRPC. Get a single Provider. @@ -697,18 +671,18 @@ def get_provider( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_provider" not in self._stubs: - self._stubs["get_provider"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/GetProvider", + if 'get_provider' not in self._stubs: + self._stubs['get_provider'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetProvider', request_serializer=eventarc.GetProviderRequest.serialize, response_deserializer=discovery.Provider.deserialize, ) - return self._stubs["get_provider"] + return self._stubs['get_provider'] @property - def list_providers( - self, - ) -> Callable[[eventarc.ListProvidersRequest], eventarc.ListProvidersResponse]: + def list_providers(self) -> Callable[ + [eventarc.ListProvidersRequest], + eventarc.ListProvidersResponse]: r"""Return a callable for the list providers method over gRPC. List providers. @@ -723,20 +697,18 @@ def list_providers( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_providers" not in self._stubs: - self._stubs["list_providers"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/ListProviders", + if 'list_providers' not in self._stubs: + self._stubs['list_providers'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListProviders', request_serializer=eventarc.ListProvidersRequest.serialize, response_deserializer=eventarc.ListProvidersResponse.deserialize, ) - return self._stubs["list_providers"] + return self._stubs['list_providers'] @property - def get_channel_connection( - self, - ) -> Callable[ - [eventarc.GetChannelConnectionRequest], channel_connection.ChannelConnection - ]: + def get_channel_connection(self) -> Callable[ + [eventarc.GetChannelConnectionRequest], + channel_connection.ChannelConnection]: r"""Return a callable for the get channel connection method over gRPC. Get a single ChannelConnection. @@ -751,21 +723,18 @@ def get_channel_connection( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_channel_connection" not in self._stubs: - self._stubs["get_channel_connection"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/GetChannelConnection", + if 'get_channel_connection' not in self._stubs: + self._stubs['get_channel_connection'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetChannelConnection', request_serializer=eventarc.GetChannelConnectionRequest.serialize, response_deserializer=channel_connection.ChannelConnection.deserialize, ) - return self._stubs["get_channel_connection"] + return self._stubs['get_channel_connection'] @property - def list_channel_connections( - self, - ) -> Callable[ - [eventarc.ListChannelConnectionsRequest], - eventarc.ListChannelConnectionsResponse, - ]: + def list_channel_connections(self) -> Callable[ + [eventarc.ListChannelConnectionsRequest], + eventarc.ListChannelConnectionsResponse]: r"""Return a callable for the list channel connections method over gRPC. List channel connections. @@ -780,18 +749,18 @@ def list_channel_connections( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_channel_connections" not in self._stubs: - self._stubs["list_channel_connections"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/ListChannelConnections", + if 'list_channel_connections' not in self._stubs: + self._stubs['list_channel_connections'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListChannelConnections', request_serializer=eventarc.ListChannelConnectionsRequest.serialize, response_deserializer=eventarc.ListChannelConnectionsResponse.deserialize, ) - return self._stubs["list_channel_connections"] + return self._stubs['list_channel_connections'] @property - def create_channel_connection( - self, - ) -> Callable[[eventarc.CreateChannelConnectionRequest], operations_pb2.Operation]: + def create_channel_connection(self) -> Callable[ + [eventarc.CreateChannelConnectionRequest], + operations_pb2.Operation]: r"""Return a callable for the create channel connection method over gRPC. Create a new ChannelConnection in a particular @@ -807,18 +776,18 @@ def create_channel_connection( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_channel_connection" not in self._stubs: - self._stubs["create_channel_connection"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/CreateChannelConnection", + if 'create_channel_connection' not in self._stubs: + self._stubs['create_channel_connection'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateChannelConnection', request_serializer=eventarc.CreateChannelConnectionRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_channel_connection"] + return self._stubs['create_channel_connection'] @property - def delete_channel_connection( - self, - ) -> Callable[[eventarc.DeleteChannelConnectionRequest], operations_pb2.Operation]: + def delete_channel_connection(self) -> Callable[ + [eventarc.DeleteChannelConnectionRequest], + operations_pb2.Operation]: r"""Return a callable for the delete channel connection method over gRPC. Delete a single ChannelConnection. @@ -833,21 +802,18 @@ def delete_channel_connection( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_channel_connection" not in self._stubs: - self._stubs["delete_channel_connection"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/DeleteChannelConnection", + if 'delete_channel_connection' not in self._stubs: + self._stubs['delete_channel_connection'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteChannelConnection', request_serializer=eventarc.DeleteChannelConnectionRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["delete_channel_connection"] + return self._stubs['delete_channel_connection'] @property - def get_google_channel_config( - self, - ) -> Callable[ - [eventarc.GetGoogleChannelConfigRequest], - google_channel_config.GoogleChannelConfig, - ]: + def get_google_channel_config(self) -> Callable[ + [eventarc.GetGoogleChannelConfigRequest], + google_channel_config.GoogleChannelConfig]: r"""Return a callable for the get google channel config method over gRPC. Get a GoogleChannelConfig. @@ -864,21 +830,18 @@ def get_google_channel_config( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_google_channel_config" not in self._stubs: - self._stubs["get_google_channel_config"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/GetGoogleChannelConfig", + if 'get_google_channel_config' not in self._stubs: + self._stubs['get_google_channel_config'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetGoogleChannelConfig', request_serializer=eventarc.GetGoogleChannelConfigRequest.serialize, response_deserializer=google_channel_config.GoogleChannelConfig.deserialize, ) - return self._stubs["get_google_channel_config"] + return self._stubs['get_google_channel_config'] @property - def update_google_channel_config( - self, - ) -> Callable[ - [eventarc.UpdateGoogleChannelConfigRequest], - gce_google_channel_config.GoogleChannelConfig, - ]: + def update_google_channel_config(self) -> Callable[ + [eventarc.UpdateGoogleChannelConfigRequest], + gce_google_channel_config.GoogleChannelConfig]: r"""Return a callable for the update google channel config method over gRPC. Update a single GoogleChannelConfig @@ -893,20 +856,18 @@ def update_google_channel_config( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_google_channel_config" not in self._stubs: - self._stubs["update_google_channel_config"] = ( - self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/UpdateGoogleChannelConfig", - request_serializer=eventarc.UpdateGoogleChannelConfigRequest.serialize, - response_deserializer=gce_google_channel_config.GoogleChannelConfig.deserialize, - ) + if 'update_google_channel_config' not in self._stubs: + self._stubs['update_google_channel_config'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateGoogleChannelConfig', + request_serializer=eventarc.UpdateGoogleChannelConfigRequest.serialize, + response_deserializer=gce_google_channel_config.GoogleChannelConfig.deserialize, ) - return self._stubs["update_google_channel_config"] + return self._stubs['update_google_channel_config'] @property - def get_message_bus( - self, - ) -> Callable[[eventarc.GetMessageBusRequest], message_bus.MessageBus]: + def get_message_bus(self) -> Callable[ + [eventarc.GetMessageBusRequest], + message_bus.MessageBus]: r"""Return a callable for the get message bus method over gRPC. Get a single MessageBus. @@ -921,20 +882,18 @@ def get_message_bus( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_message_bus" not in self._stubs: - self._stubs["get_message_bus"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/GetMessageBus", + if 'get_message_bus' not in self._stubs: + self._stubs['get_message_bus'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetMessageBus', request_serializer=eventarc.GetMessageBusRequest.serialize, response_deserializer=message_bus.MessageBus.deserialize, ) - return self._stubs["get_message_bus"] + return self._stubs['get_message_bus'] @property - def list_message_buses( - self, - ) -> Callable[ - [eventarc.ListMessageBusesRequest], eventarc.ListMessageBusesResponse - ]: + def list_message_buses(self) -> Callable[ + [eventarc.ListMessageBusesRequest], + eventarc.ListMessageBusesResponse]: r"""Return a callable for the list message buses method over gRPC. List message buses. @@ -949,21 +908,18 @@ def list_message_buses( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_message_buses" not in self._stubs: - self._stubs["list_message_buses"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/ListMessageBuses", + if 'list_message_buses' not in self._stubs: + self._stubs['list_message_buses'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListMessageBuses', request_serializer=eventarc.ListMessageBusesRequest.serialize, response_deserializer=eventarc.ListMessageBusesResponse.deserialize, ) - return self._stubs["list_message_buses"] + return self._stubs['list_message_buses'] @property - def list_message_bus_enrollments( - self, - ) -> Callable[ - [eventarc.ListMessageBusEnrollmentsRequest], - eventarc.ListMessageBusEnrollmentsResponse, - ]: + def list_message_bus_enrollments(self) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + eventarc.ListMessageBusEnrollmentsResponse]: r"""Return a callable for the list message bus enrollments method over gRPC. List message bus enrollments. @@ -978,20 +934,18 @@ def list_message_bus_enrollments( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_message_bus_enrollments" not in self._stubs: - self._stubs["list_message_bus_enrollments"] = ( - self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/ListMessageBusEnrollments", - request_serializer=eventarc.ListMessageBusEnrollmentsRequest.serialize, - response_deserializer=eventarc.ListMessageBusEnrollmentsResponse.deserialize, - ) + if 'list_message_bus_enrollments' not in self._stubs: + self._stubs['list_message_bus_enrollments'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListMessageBusEnrollments', + request_serializer=eventarc.ListMessageBusEnrollmentsRequest.serialize, + response_deserializer=eventarc.ListMessageBusEnrollmentsResponse.deserialize, ) - return self._stubs["list_message_bus_enrollments"] + return self._stubs['list_message_bus_enrollments'] @property - def create_message_bus( - self, - ) -> Callable[[eventarc.CreateMessageBusRequest], operations_pb2.Operation]: + def create_message_bus(self) -> Callable[ + [eventarc.CreateMessageBusRequest], + operations_pb2.Operation]: r"""Return a callable for the create message bus method over gRPC. Create a new MessageBus in a particular project and @@ -1007,18 +961,18 @@ def create_message_bus( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_message_bus" not in self._stubs: - self._stubs["create_message_bus"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/CreateMessageBus", + if 'create_message_bus' not in self._stubs: + self._stubs['create_message_bus'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateMessageBus', request_serializer=eventarc.CreateMessageBusRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_message_bus"] + return self._stubs['create_message_bus'] @property - def update_message_bus( - self, - ) -> Callable[[eventarc.UpdateMessageBusRequest], operations_pb2.Operation]: + def update_message_bus(self) -> Callable[ + [eventarc.UpdateMessageBusRequest], + operations_pb2.Operation]: r"""Return a callable for the update message bus method over gRPC. Update a single message bus. @@ -1033,18 +987,18 @@ def update_message_bus( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_message_bus" not in self._stubs: - self._stubs["update_message_bus"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/UpdateMessageBus", + if 'update_message_bus' not in self._stubs: + self._stubs['update_message_bus'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateMessageBus', request_serializer=eventarc.UpdateMessageBusRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["update_message_bus"] + return self._stubs['update_message_bus'] @property - def delete_message_bus( - self, - ) -> Callable[[eventarc.DeleteMessageBusRequest], operations_pb2.Operation]: + def delete_message_bus(self) -> Callable[ + [eventarc.DeleteMessageBusRequest], + operations_pb2.Operation]: r"""Return a callable for the delete message bus method over gRPC. Delete a single message bus. @@ -1059,18 +1013,18 @@ def delete_message_bus( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_message_bus" not in self._stubs: - self._stubs["delete_message_bus"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/DeleteMessageBus", + if 'delete_message_bus' not in self._stubs: + self._stubs['delete_message_bus'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteMessageBus', request_serializer=eventarc.DeleteMessageBusRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["delete_message_bus"] + return self._stubs['delete_message_bus'] @property - def get_enrollment( - self, - ) -> Callable[[eventarc.GetEnrollmentRequest], enrollment.Enrollment]: + def get_enrollment(self) -> Callable[ + [eventarc.GetEnrollmentRequest], + enrollment.Enrollment]: r"""Return a callable for the get enrollment method over gRPC. Get a single Enrollment. @@ -1085,18 +1039,18 @@ def get_enrollment( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_enrollment" not in self._stubs: - self._stubs["get_enrollment"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/GetEnrollment", + if 'get_enrollment' not in self._stubs: + self._stubs['get_enrollment'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetEnrollment', request_serializer=eventarc.GetEnrollmentRequest.serialize, response_deserializer=enrollment.Enrollment.deserialize, ) - return self._stubs["get_enrollment"] + return self._stubs['get_enrollment'] @property - def list_enrollments( - self, - ) -> Callable[[eventarc.ListEnrollmentsRequest], eventarc.ListEnrollmentsResponse]: + def list_enrollments(self) -> Callable[ + [eventarc.ListEnrollmentsRequest], + eventarc.ListEnrollmentsResponse]: r"""Return a callable for the list enrollments method over gRPC. List Enrollments. @@ -1111,18 +1065,18 @@ def list_enrollments( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_enrollments" not in self._stubs: - self._stubs["list_enrollments"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/ListEnrollments", + if 'list_enrollments' not in self._stubs: + self._stubs['list_enrollments'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListEnrollments', request_serializer=eventarc.ListEnrollmentsRequest.serialize, response_deserializer=eventarc.ListEnrollmentsResponse.deserialize, ) - return self._stubs["list_enrollments"] + return self._stubs['list_enrollments'] @property - def create_enrollment( - self, - ) -> Callable[[eventarc.CreateEnrollmentRequest], operations_pb2.Operation]: + def create_enrollment(self) -> Callable[ + [eventarc.CreateEnrollmentRequest], + operations_pb2.Operation]: r"""Return a callable for the create enrollment method over gRPC. Create a new Enrollment in a particular project and @@ -1138,18 +1092,18 @@ def create_enrollment( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_enrollment" not in self._stubs: - self._stubs["create_enrollment"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/CreateEnrollment", + if 'create_enrollment' not in self._stubs: + self._stubs['create_enrollment'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateEnrollment', request_serializer=eventarc.CreateEnrollmentRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_enrollment"] + return self._stubs['create_enrollment'] @property - def update_enrollment( - self, - ) -> Callable[[eventarc.UpdateEnrollmentRequest], operations_pb2.Operation]: + def update_enrollment(self) -> Callable[ + [eventarc.UpdateEnrollmentRequest], + operations_pb2.Operation]: r"""Return a callable for the update enrollment method over gRPC. Update a single Enrollment. @@ -1164,18 +1118,18 @@ def update_enrollment( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_enrollment" not in self._stubs: - self._stubs["update_enrollment"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/UpdateEnrollment", + if 'update_enrollment' not in self._stubs: + self._stubs['update_enrollment'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateEnrollment', request_serializer=eventarc.UpdateEnrollmentRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["update_enrollment"] + return self._stubs['update_enrollment'] @property - def delete_enrollment( - self, - ) -> Callable[[eventarc.DeleteEnrollmentRequest], operations_pb2.Operation]: + def delete_enrollment(self) -> Callable[ + [eventarc.DeleteEnrollmentRequest], + operations_pb2.Operation]: r"""Return a callable for the delete enrollment method over gRPC. Delete a single Enrollment. @@ -1190,18 +1144,18 @@ def delete_enrollment( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_enrollment" not in self._stubs: - self._stubs["delete_enrollment"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/DeleteEnrollment", + if 'delete_enrollment' not in self._stubs: + self._stubs['delete_enrollment'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteEnrollment', request_serializer=eventarc.DeleteEnrollmentRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["delete_enrollment"] + return self._stubs['delete_enrollment'] @property - def get_pipeline( - self, - ) -> Callable[[eventarc.GetPipelineRequest], pipeline.Pipeline]: + def get_pipeline(self) -> Callable[ + [eventarc.GetPipelineRequest], + pipeline.Pipeline]: r"""Return a callable for the get pipeline method over gRPC. Get a single Pipeline. @@ -1216,18 +1170,18 @@ def get_pipeline( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_pipeline" not in self._stubs: - self._stubs["get_pipeline"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/GetPipeline", + if 'get_pipeline' not in self._stubs: + self._stubs['get_pipeline'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetPipeline', request_serializer=eventarc.GetPipelineRequest.serialize, response_deserializer=pipeline.Pipeline.deserialize, ) - return self._stubs["get_pipeline"] + return self._stubs['get_pipeline'] @property - def list_pipelines( - self, - ) -> Callable[[eventarc.ListPipelinesRequest], eventarc.ListPipelinesResponse]: + def list_pipelines(self) -> Callable[ + [eventarc.ListPipelinesRequest], + eventarc.ListPipelinesResponse]: r"""Return a callable for the list pipelines method over gRPC. List pipelines. @@ -1242,18 +1196,18 @@ def list_pipelines( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_pipelines" not in self._stubs: - self._stubs["list_pipelines"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/ListPipelines", + if 'list_pipelines' not in self._stubs: + self._stubs['list_pipelines'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListPipelines', request_serializer=eventarc.ListPipelinesRequest.serialize, response_deserializer=eventarc.ListPipelinesResponse.deserialize, ) - return self._stubs["list_pipelines"] + return self._stubs['list_pipelines'] @property - def create_pipeline( - self, - ) -> Callable[[eventarc.CreatePipelineRequest], operations_pb2.Operation]: + def create_pipeline(self) -> Callable[ + [eventarc.CreatePipelineRequest], + operations_pb2.Operation]: r"""Return a callable for the create pipeline method over gRPC. Create a new Pipeline in a particular project and @@ -1269,18 +1223,18 @@ def create_pipeline( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_pipeline" not in self._stubs: - self._stubs["create_pipeline"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/CreatePipeline", + if 'create_pipeline' not in self._stubs: + self._stubs['create_pipeline'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreatePipeline', request_serializer=eventarc.CreatePipelineRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_pipeline"] + return self._stubs['create_pipeline'] @property - def update_pipeline( - self, - ) -> Callable[[eventarc.UpdatePipelineRequest], operations_pb2.Operation]: + def update_pipeline(self) -> Callable[ + [eventarc.UpdatePipelineRequest], + operations_pb2.Operation]: r"""Return a callable for the update pipeline method over gRPC. Update a single pipeline. @@ -1295,18 +1249,18 @@ def update_pipeline( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_pipeline" not in self._stubs: - self._stubs["update_pipeline"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/UpdatePipeline", + if 'update_pipeline' not in self._stubs: + self._stubs['update_pipeline'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdatePipeline', request_serializer=eventarc.UpdatePipelineRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["update_pipeline"] + return self._stubs['update_pipeline'] @property - def delete_pipeline( - self, - ) -> Callable[[eventarc.DeletePipelineRequest], operations_pb2.Operation]: + def delete_pipeline(self) -> Callable[ + [eventarc.DeletePipelineRequest], + operations_pb2.Operation]: r"""Return a callable for the delete pipeline method over gRPC. Delete a single pipeline. @@ -1321,20 +1275,18 @@ def delete_pipeline( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_pipeline" not in self._stubs: - self._stubs["delete_pipeline"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/DeletePipeline", + if 'delete_pipeline' not in self._stubs: + self._stubs['delete_pipeline'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeletePipeline', request_serializer=eventarc.DeletePipelineRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["delete_pipeline"] + return self._stubs['delete_pipeline'] @property - def get_google_api_source( - self, - ) -> Callable[ - [eventarc.GetGoogleApiSourceRequest], google_api_source.GoogleApiSource - ]: + def get_google_api_source(self) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], + google_api_source.GoogleApiSource]: r"""Return a callable for the get google api source method over gRPC. Get a single GoogleApiSource. @@ -1349,20 +1301,18 @@ def get_google_api_source( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_google_api_source" not in self._stubs: - self._stubs["get_google_api_source"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/GetGoogleApiSource", + if 'get_google_api_source' not in self._stubs: + self._stubs['get_google_api_source'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/GetGoogleApiSource', request_serializer=eventarc.GetGoogleApiSourceRequest.serialize, response_deserializer=google_api_source.GoogleApiSource.deserialize, ) - return self._stubs["get_google_api_source"] + return self._stubs['get_google_api_source'] @property - def list_google_api_sources( - self, - ) -> Callable[ - [eventarc.ListGoogleApiSourcesRequest], eventarc.ListGoogleApiSourcesResponse - ]: + def list_google_api_sources(self) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], + eventarc.ListGoogleApiSourcesResponse]: r"""Return a callable for the list google api sources method over gRPC. List GoogleApiSources. @@ -1377,18 +1327,18 @@ def list_google_api_sources( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_google_api_sources" not in self._stubs: - self._stubs["list_google_api_sources"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/ListGoogleApiSources", + if 'list_google_api_sources' not in self._stubs: + self._stubs['list_google_api_sources'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/ListGoogleApiSources', request_serializer=eventarc.ListGoogleApiSourcesRequest.serialize, response_deserializer=eventarc.ListGoogleApiSourcesResponse.deserialize, ) - return self._stubs["list_google_api_sources"] + return self._stubs['list_google_api_sources'] @property - def create_google_api_source( - self, - ) -> Callable[[eventarc.CreateGoogleApiSourceRequest], operations_pb2.Operation]: + def create_google_api_source(self) -> Callable[ + [eventarc.CreateGoogleApiSourceRequest], + operations_pb2.Operation]: r"""Return a callable for the create google api source method over gRPC. Create a new GoogleApiSource in a particular project @@ -1404,18 +1354,18 @@ def create_google_api_source( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_google_api_source" not in self._stubs: - self._stubs["create_google_api_source"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/CreateGoogleApiSource", + if 'create_google_api_source' not in self._stubs: + self._stubs['create_google_api_source'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/CreateGoogleApiSource', request_serializer=eventarc.CreateGoogleApiSourceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_google_api_source"] + return self._stubs['create_google_api_source'] @property - def update_google_api_source( - self, - ) -> Callable[[eventarc.UpdateGoogleApiSourceRequest], operations_pb2.Operation]: + def update_google_api_source(self) -> Callable[ + [eventarc.UpdateGoogleApiSourceRequest], + operations_pb2.Operation]: r"""Return a callable for the update google api source method over gRPC. Update a single GoogleApiSource. @@ -1430,18 +1380,18 @@ def update_google_api_source( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_google_api_source" not in self._stubs: - self._stubs["update_google_api_source"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/UpdateGoogleApiSource", + if 'update_google_api_source' not in self._stubs: + self._stubs['update_google_api_source'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/UpdateGoogleApiSource', request_serializer=eventarc.UpdateGoogleApiSourceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["update_google_api_source"] + return self._stubs['update_google_api_source'] @property - def delete_google_api_source( - self, - ) -> Callable[[eventarc.DeleteGoogleApiSourceRequest], operations_pb2.Operation]: + def delete_google_api_source(self) -> Callable[ + [eventarc.DeleteGoogleApiSourceRequest], + operations_pb2.Operation]: r"""Return a callable for the delete google api source method over gRPC. Delete a single GoogleApiSource. @@ -1456,13 +1406,13 @@ def delete_google_api_source( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_google_api_source" not in self._stubs: - self._stubs["delete_google_api_source"] = self._logged_channel.unary_unary( - "/google.cloud.eventarc.v1.Eventarc/DeleteGoogleApiSource", + if 'delete_google_api_source' not in self._stubs: + self._stubs['delete_google_api_source'] = self._logged_channel.unary_unary( + '/google.cloud.eventarc.v1.Eventarc/DeleteGoogleApiSource', request_serializer=eventarc.DeleteGoogleApiSourceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["delete_google_api_source"] + return self._stubs['delete_google_api_source'] def close(self): self._logged_channel.close() @@ -1471,7 +1421,8 @@ def close(self): def delete_operation( self, ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC.""" + r"""Return a callable for the delete_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1488,7 +1439,8 @@ def delete_operation( def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC.""" + r"""Return a callable for the cancel_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1505,7 +1457,8 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1521,10 +1474,9 @@ def get_operation( @property def list_operations( self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse - ]: - r"""Return a callable for the list_operations method over gRPC.""" + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1540,10 +1492,9 @@ def list_operations( @property def list_locations( self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse - ]: - r"""Return a callable for the list locations method over gRPC.""" + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1560,7 +1511,8 @@ def list_locations( def get_location( self, ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC.""" + r"""Return a callable for the list locations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1628,8 +1580,7 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse, + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse ]: r"""Return a callable for the test iam permissions method over gRPC. Tests the specified permissions against the IAM access control @@ -1658,4 +1609,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("EventarcGrpcTransport",) +__all__ = ( + 'EventarcGrpcTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py index 65eb13b69934..53a782c89be6 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py @@ -13,46 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import inspect import json import logging as std_logging import os import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings -from collections import OrderedDict -from http import HTTPStatus -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import google.protobuf +from google.cloud.logging_v2 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.logging_v2 import gapic_version as package_version -from google.cloud.logging_v2._compat import ( - get_api_endpoint, - get_default_mtls_endpoint, - get_universe_domain, - read_environment_variables, - should_use_client_cert, -) -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -61,7 +44,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -75,16 +57,15 @@ _LOGGER = std_logging.getLogger(__name__) +from google.cloud.logging_v2.services.config_service_v2 import pagers +from google.cloud.logging_v2.types import logging_config +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from google.cloud.logging_v2.services.config_service_v2 import pagers -from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore - -from .transports.base import DEFAULT_CLIENT_INFO, ConfigServiceV2Transport +from .transports.base import ConfigServiceV2Transport, DEFAULT_CLIENT_INFO from .transports.grpc import ConfigServiceV2GrpcTransport from .transports.grpc_asyncio import ConfigServiceV2GrpcAsyncIOTransport @@ -96,15 +77,13 @@ class ConfigServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[ConfigServiceV2Transport]] _transport_registry["grpc"] = ConfigServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = ConfigServiceV2GrpcAsyncIOTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[ConfigServiceV2Transport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ConfigServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -164,7 +143,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConfigServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -181,220 +161,139 @@ def transport(self) -> ConfigServiceV2Transport: return self._transport @staticmethod - def cmek_settings_path( - project: str, - ) -> str: + def cmek_settings_path(project: str,) -> str: """Returns a fully-qualified cmek_settings string.""" - return "projects/{project}/cmekSettings".format( - project=project, - ) + return "projects/{project}/cmekSettings".format(project=project, ) @staticmethod - def parse_cmek_settings_path(path: str) -> Dict[str, str]: + def parse_cmek_settings_path(path: str) -> Dict[str,str]: """Parses a cmek_settings path into its component segments.""" m = re.match(r"^projects/(?P.+?)/cmekSettings$", path) return m.groupdict() if m else {} @staticmethod - def link_path( - project: str, - location: str, - bucket: str, - link: str, - ) -> str: + def link_path(project: str,location: str,bucket: str,link: str,) -> str: """Returns a fully-qualified link string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format( - project=project, - location=location, - bucket=bucket, - link=link, - ) + return "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format(project=project, location=location, bucket=bucket, link=link, ) @staticmethod - def parse_link_path(path: str) -> Dict[str, str]: + def parse_link_path(path: str) -> Dict[str,str]: """Parses a link path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/links/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/links/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_bucket_path( - project: str, - location: str, - bucket: str, - ) -> str: + def log_bucket_path(project: str,location: str,bucket: str,) -> str: """Returns a fully-qualified log_bucket string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}".format( - project=project, - location=location, - bucket=bucket, - ) + return "projects/{project}/locations/{location}/buckets/{bucket}".format(project=project, location=location, bucket=bucket, ) @staticmethod - def parse_log_bucket_path(path: str) -> Dict[str, str]: + def parse_log_bucket_path(path: str) -> Dict[str,str]: """Parses a log_bucket path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_exclusion_path( - project: str, - exclusion: str, - ) -> str: + def log_exclusion_path(project: str,exclusion: str,) -> str: """Returns a fully-qualified log_exclusion string.""" - return "projects/{project}/exclusions/{exclusion}".format( - project=project, - exclusion=exclusion, - ) + return "projects/{project}/exclusions/{exclusion}".format(project=project, exclusion=exclusion, ) @staticmethod - def parse_log_exclusion_path(path: str) -> Dict[str, str]: + def parse_log_exclusion_path(path: str) -> Dict[str,str]: """Parses a log_exclusion path into its component segments.""" m = re.match(r"^projects/(?P.+?)/exclusions/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_sink_path( - project: str, - sink: str, - ) -> str: + def log_sink_path(project: str,sink: str,) -> str: """Returns a fully-qualified log_sink string.""" - return "projects/{project}/sinks/{sink}".format( - project=project, - sink=sink, - ) + return "projects/{project}/sinks/{sink}".format(project=project, sink=sink, ) @staticmethod - def parse_log_sink_path(path: str) -> Dict[str, str]: + def parse_log_sink_path(path: str) -> Dict[str,str]: """Parses a log_sink path into its component segments.""" m = re.match(r"^projects/(?P.+?)/sinks/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_view_path( - project: str, - location: str, - bucket: str, - view: str, - ) -> str: + def log_view_path(project: str,location: str,bucket: str,view: str,) -> str: """Returns a fully-qualified log_view string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format( - project=project, - location=location, - bucket=bucket, - view=view, - ) + return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format(project=project, location=location, bucket=bucket, view=view, ) @staticmethod - def parse_log_view_path(path: str) -> Dict[str, str]: + def parse_log_view_path(path: str) -> Dict[str,str]: """Parses a log_view path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def settings_path( - project: str, - ) -> str: + def settings_path(project: str,) -> str: """Returns a fully-qualified settings string.""" - return "projects/{project}/settings".format( - project=project, - ) + return "projects/{project}/settings".format(project=project, ) @staticmethod - def parse_settings_path(path: str) -> Dict[str, str]: + def parse_settings_path(path: str) -> Dict[str,str]: """Parses a settings path into its component segments.""" m = re.match(r"^projects/(?P.+?)/settings$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -426,18 +325,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -450,10 +345,8 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -492,18 +385,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -536,18 +426,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[ - str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the config service v2 client. Args: @@ -602,23 +486,13 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - read_environment_variables() - ) - self._client_cert_source = ConfigServiceV2Client._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = get_universe_domain( - universe_domain_opt, - self._universe_domain_env, - default_universe=ConfigServiceV2Client._DEFAULT_UNIVERSE, - ) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() + self._client_cert_source = ConfigServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=ConfigServiceV2Client._DEFAULT_UNIVERSE) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -630,9 +504,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -641,40 +513,35 @@ def __init__( if transport_provided: # transport is a ConfigServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = cast(ConfigServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = self._api_endpoint or get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=ConfigServiceV2Client._DEFAULT_UNIVERSE, - default_mtls_endpoint=ConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=ConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" - or (self._use_mtls_endpoint == "auto" and self._client_cert_source), - ) + self._api_endpoint = (self._api_endpoint or + get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=ConfigServiceV2Client._DEFAULT_UNIVERSE, + default_mtls_endpoint=ConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=ConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" or ( + self._use_mtls_endpoint == "auto" and self._client_cert_source + ), + )) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[ConfigServiceV2Transport], Callable[..., ConfigServiceV2Transport] - ] = ( + transport_init: Union[Type[ConfigServiceV2Transport], Callable[..., ConfigServiceV2Transport]] = ( ConfigServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ConfigServiceV2Transport], transport) @@ -703,46 +570,33 @@ def __init__( "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **( - {"client_options": client_options} - if client_options is not None - else {} - ), + **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.ConfigServiceV2Client`.", - extra={ + extra = { "serviceName": "google.logging.v2.ConfigServiceV2", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.logging.v2.ConfigServiceV2", "credentialsType": None, - }, + } ) - def list_buckets( - self, - request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBucketsPager: + def list_buckets(self, + request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketsPager: r"""Lists log buckets. .. code-block:: python @@ -814,14 +668,10 @@ def sample_list_buckets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -839,7 +689,9 @@ def sample_list_buckets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -867,14 +719,13 @@ def sample_list_buckets(): # Done; return the response. return response - def get_bucket( - self, - request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def get_bucket(self, + request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Gets a log bucket. .. code-block:: python @@ -933,7 +784,9 @@ def sample_get_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -950,14 +803,13 @@ def sample_get_bucket(): # Done; return the response. return response - def create_bucket_async( - self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_bucket_async(self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a log bucket asynchronously that can be used to store log entries. After a bucket has been created, the bucket's location @@ -1027,7 +879,9 @@ def sample_create_bucket_async(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1052,14 +906,13 @@ def sample_create_bucket_async(): # Done; return the response. return response - def update_bucket_async( - self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_bucket_async(self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates a log bucket asynchronously. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -1131,7 +984,9 @@ def sample_update_bucket_async(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1156,14 +1011,13 @@ def sample_update_bucket_async(): # Done; return the response. return response - def create_bucket( - self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def create_bucket(self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Creates a log bucket that can be used to store log entries. After a bucket has been created, the bucket's location cannot be changed. @@ -1225,7 +1079,9 @@ def sample_create_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1242,14 +1098,13 @@ def sample_create_bucket(): # Done; return the response. return response - def update_bucket( - self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def update_bucket(self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Updates a log bucket. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -1314,7 +1169,9 @@ def sample_update_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1331,14 +1188,13 @@ def sample_update_bucket(): # Done; return the response. return response - def delete_bucket( - self, - request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_bucket(self, + request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a log bucket. Changes the bucket's ``lifecycle_state`` to the @@ -1393,7 +1249,9 @@ def sample_delete_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1407,14 +1265,13 @@ def sample_delete_bucket(): metadata=metadata, ) - def undelete_bucket( - self, - request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def undelete_bucket(self, + request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Undeletes a log bucket. A bucket that has been deleted can be undeleted within the grace period of 7 days. @@ -1466,7 +1323,9 @@ def sample_undelete_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1480,15 +1339,14 @@ def sample_undelete_bucket(): metadata=metadata, ) - def list_views( - self, - request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListViewsPager: + def list_views(self, + request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListViewsPager: r"""Lists views on a log bucket. .. code-block:: python @@ -1552,14 +1410,10 @@ def sample_list_views(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1577,7 +1431,9 @@ def sample_list_views(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1605,14 +1461,13 @@ def sample_list_views(): # Done; return the response. return response - def get_view( - self, - request: Optional[Union[logging_config.GetViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def get_view(self, + request: Optional[Union[logging_config.GetViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Gets a view on a log bucket.. .. code-block:: python @@ -1671,7 +1526,9 @@ def sample_get_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1688,14 +1545,13 @@ def sample_get_view(): # Done; return the response. return response - def create_view( - self, - request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def create_view(self, + request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Creates a view over log entries in a log bucket. A bucket may contain a maximum of 30 views. @@ -1756,7 +1612,9 @@ def sample_create_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1773,14 +1631,13 @@ def sample_create_view(): # Done; return the response. return response - def update_view( - self, - request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def update_view(self, + request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Updates a view on a log bucket. This method replaces the following fields in the existing view with values from the new view: ``filter``. If an ``UNAVAILABLE`` error is returned, this @@ -1843,7 +1700,9 @@ def sample_update_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1860,14 +1719,13 @@ def sample_update_view(): # Done; return the response. return response - def delete_view( - self, - request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_view(self, + request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is returned, this indicates that system is not in a state where it can delete the view. If this occurs, please try again in a few @@ -1920,7 +1778,9 @@ def sample_delete_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1934,15 +1794,14 @@ def sample_delete_view(): metadata=metadata, ) - def list_sinks( - self, - request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListSinksPager: + def list_sinks(self, + request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSinksPager: r"""Lists sinks. .. code-block:: python @@ -2009,14 +1868,10 @@ def sample_list_sinks(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2034,7 +1889,9 @@ def sample_list_sinks(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2062,15 +1919,14 @@ def sample_list_sinks(): # Done; return the response. return response - def get_sink( - self, - request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def get_sink(self, + request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Gets a sink. .. code-block:: python @@ -2144,14 +2000,10 @@ def sample_get_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2169,9 +2021,9 @@ def sample_get_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("sink_name", request.sink_name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("sink_name", request.sink_name), + )), ) # Validate the universe domain. @@ -2188,16 +2040,15 @@ def sample_get_sink(): # Done; return the response. return response - def create_sink( - self, - request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def create_sink(self, + request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not @@ -2287,14 +2138,10 @@ def sample_create_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, sink] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2314,7 +2161,9 @@ def sample_create_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2331,17 +2180,16 @@ def sample_create_sink(): # Done; return the response. return response - def update_sink( - self, - request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def update_sink(self, + request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: ``destination``, and ``filter``. @@ -2455,14 +2303,10 @@ def sample_update_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name, sink, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2484,9 +2328,9 @@ def sample_update_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("sink_name", request.sink_name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("sink_name", request.sink_name), + )), ) # Validate the universe domain. @@ -2503,15 +2347,14 @@ def sample_update_sink(): # Done; return the response. return response - def delete_sink( - self, - request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_sink(self, + request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a sink. If the sink has a unique ``writer_identity``, then that service account is also deleted. @@ -2571,14 +2414,10 @@ def sample_delete_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2596,9 +2435,9 @@ def sample_delete_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("sink_name", request.sink_name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("sink_name", request.sink_name), + )), ) # Validate the universe domain. @@ -2612,17 +2451,16 @@ def sample_delete_sink(): metadata=metadata, ) - def create_link( - self, - request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - link: Optional[logging_config.Link] = None, - link_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_link(self, + request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + link: Optional[logging_config.Link] = None, + link_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Asynchronously creates a linked dataset in BigQuery which makes it possible to use BigQuery to read the logs stored in the log bucket. A log bucket may currently @@ -2710,14 +2548,10 @@ def sample_create_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, link, link_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2739,7 +2573,9 @@ def sample_create_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2764,15 +2600,14 @@ def sample_create_link(): # Done; return the response. return response - def delete_link( - self, - request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_link(self, + request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes a link. This will also delete the corresponding BigQuery linked dataset. @@ -2848,14 +2683,10 @@ def sample_delete_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2873,7 +2704,9 @@ def sample_delete_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2898,15 +2731,14 @@ def sample_delete_link(): # Done; return the response. return response - def list_links( - self, - request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLinksPager: + def list_links(self, + request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLinksPager: r"""Lists links. .. code-block:: python @@ -2972,14 +2804,10 @@ def sample_list_links(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2997,7 +2825,9 @@ def sample_list_links(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3025,15 +2855,14 @@ def sample_list_links(): # Done; return the response. return response - def get_link( - self, - request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Link: + def get_link(self, + request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Link: r"""Gets a link. .. code-block:: python @@ -3094,14 +2923,10 @@ def sample_get_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3119,7 +2944,9 @@ def sample_get_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3136,15 +2963,14 @@ def sample_get_link(): # Done; return the response. return response - def list_exclusions( - self, - request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListExclusionsPager: + def list_exclusions(self, + request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExclusionsPager: r"""Lists all the exclusions on the \_Default sink in a parent resource. @@ -3212,14 +3038,10 @@ def sample_list_exclusions(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3237,7 +3059,9 @@ def sample_list_exclusions(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3265,15 +3089,14 @@ def sample_list_exclusions(): # Done; return the response. return response - def get_exclusion( - self, - request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def get_exclusion(self, + request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Gets the description of an exclusion in the \_Default sink. .. code-block:: python @@ -3345,14 +3168,10 @@ def sample_get_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3370,7 +3189,9 @@ def sample_get_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3387,16 +3208,15 @@ def sample_get_exclusion(): # Done; return the response. return response - def create_exclusion( - self, - request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, - *, - parent: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def create_exclusion(self, + request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, + *, + parent: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Creates a new exclusion in the \_Default sink in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. @@ -3485,14 +3305,10 @@ def sample_create_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, exclusion] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3512,7 +3328,9 @@ def sample_create_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3529,17 +3347,16 @@ def sample_create_exclusion(): # Done; return the response. return response - def update_exclusion( - self, - request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def update_exclusion(self, + request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Changes one or more properties of an existing exclusion in the \_Default sink. @@ -3639,14 +3456,10 @@ def sample_update_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, exclusion, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3668,7 +3481,9 @@ def sample_update_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3685,15 +3500,14 @@ def sample_update_exclusion(): # Done; return the response. return response - def delete_exclusion( - self, - request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_exclusion(self, + request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes an exclusion in the \_Default sink. .. code-block:: python @@ -3752,14 +3566,10 @@ def sample_delete_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3777,7 +3587,9 @@ def sample_delete_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3791,14 +3603,13 @@ def sample_delete_exclusion(): metadata=metadata, ) - def get_cmek_settings( - self, - request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + def get_cmek_settings(self, + request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Gets the Logging CMEK settings for the given resource. Note: CMEK for the Log Router can be configured for Google Cloud @@ -3881,7 +3692,9 @@ def sample_get_cmek_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3898,14 +3711,13 @@ def sample_get_cmek_settings(): # Done; return the response. return response - def update_cmek_settings( - self, - request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + def update_cmek_settings(self, + request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Updates the Log Router CMEK settings for the given resource. Note: CMEK for the Log Router can currently only be configured @@ -3993,7 +3805,9 @@ def sample_update_cmek_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -4010,15 +3824,14 @@ def sample_update_cmek_settings(): # Done; return the response. return response - def get_settings( - self, - request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + def get_settings(self, + request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Gets the Log Router settings for the given resource. Note: Settings for the Log Router can be get for Google Cloud @@ -4108,14 +3921,10 @@ def sample_get_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4133,7 +3942,9 @@ def sample_get_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -4150,16 +3961,15 @@ def sample_get_settings(): # Done; return the response. return response - def update_settings( - self, - request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, - *, - settings: Optional[logging_config.Settings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + def update_settings(self, + request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, + *, + settings: Optional[logging_config.Settings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Updates the Log Router settings for the given resource. Note: Settings for the Log Router can currently only be @@ -4256,14 +4066,10 @@ def sample_update_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [settings, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4283,7 +4089,9 @@ def sample_update_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -4300,14 +4108,13 @@ def sample_update_settings(): # Done; return the response. return response - def copy_log_entries( - self, - request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def copy_log_entries(self, + request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Copies a set of log entries from a log bucket to a Cloud Storage bucket. @@ -4450,7 +4257,8 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -4459,11 +4267,7 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -4513,7 +4317,8 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -4522,11 +4327,7 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -4579,24 +4380,25 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ConfigServiceV2Client",) +__all__ = ( + "ConfigServiceV2Client", +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py index 97dbac19187d..89638bbf0c72 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -17,23 +17,24 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import google.api_core +from google.cloud.logging_v2 import gapic_version as package_version + import google.auth # type: ignore -import google.protobuf -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.api_core from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.cloud.logging_v2 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore +import google.protobuf + from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ # Check once at module load time whether google-api-core's wrap_method supports @@ -48,28 +49,27 @@ class ConfigServiceV2Transport(abc.ABC): """Abstract transport class for ConfigServiceV2.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-platform.read-only", - "https://www.googleapis.com/auth/logging.admin", - "https://www.googleapis.com/auth/logging.read", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + 'https://www.googleapis.com/auth/logging.admin', + 'https://www.googleapis.com/auth/logging.read', ) - DEFAULT_HOST: str = "logging.googleapis.com" + DEFAULT_HOST: str = 'logging.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -111,43 +111,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host self._client_options = client_options @@ -174,12 +162,7 @@ def _wrap_method(self, func, *args, **kwargs): # of google-api-core is installed (which does not accept client_options, etc.). # Excluded from coverage because our CI and testing environments always install # a modern version of google-api-core that supports tracing. - for k in [ - "client_options", - "method_name", - "is_streaming", - "kind", - ]: # pragma: NO COVER + for k in ["client_options", "method_name", "is_streaming", "kind"]: # pragma: NO COVER kwargs.pop(k, None) # pragma: NO COVER return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER @@ -470,14 +453,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -487,306 +470,291 @@ def operations_client(self): raise NotImplementedError() @property - def list_buckets( - self, - ) -> Callable[ - [logging_config.ListBucketsRequest], - Union[ - logging_config.ListBucketsResponse, - Awaitable[logging_config.ListBucketsResponse], - ], - ]: + def list_buckets(self) -> Callable[ + [logging_config.ListBucketsRequest], + Union[ + logging_config.ListBucketsResponse, + Awaitable[logging_config.ListBucketsResponse] + ]]: raise NotImplementedError() @property - def get_bucket( - self, - ) -> Callable[ - [logging_config.GetBucketRequest], - Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], - ]: + def get_bucket(self) -> Callable[ + [logging_config.GetBucketRequest], + Union[ + logging_config.LogBucket, + Awaitable[logging_config.LogBucket] + ]]: raise NotImplementedError() @property - def create_bucket_async( - self, - ) -> Callable[ - [logging_config.CreateBucketRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_bucket_async(self) -> Callable[ + [logging_config.CreateBucketRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def update_bucket_async( - self, - ) -> Callable[ - [logging_config.UpdateBucketRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def update_bucket_async(self) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def create_bucket( - self, - ) -> Callable[ - [logging_config.CreateBucketRequest], - Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], - ]: + def create_bucket(self) -> Callable[ + [logging_config.CreateBucketRequest], + Union[ + logging_config.LogBucket, + Awaitable[logging_config.LogBucket] + ]]: raise NotImplementedError() @property - def update_bucket( - self, - ) -> Callable[ - [logging_config.UpdateBucketRequest], - Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], - ]: + def update_bucket(self) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[ + logging_config.LogBucket, + Awaitable[logging_config.LogBucket] + ]]: raise NotImplementedError() @property - def delete_bucket( - self, - ) -> Callable[ - [logging_config.DeleteBucketRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_bucket(self) -> Callable[ + [logging_config.DeleteBucketRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def undelete_bucket( - self, - ) -> Callable[ - [logging_config.UndeleteBucketRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def undelete_bucket(self) -> Callable[ + [logging_config.UndeleteBucketRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def list_views( - self, - ) -> Callable[ - [logging_config.ListViewsRequest], - Union[ - logging_config.ListViewsResponse, - Awaitable[logging_config.ListViewsResponse], - ], - ]: + def list_views(self) -> Callable[ + [logging_config.ListViewsRequest], + Union[ + logging_config.ListViewsResponse, + Awaitable[logging_config.ListViewsResponse] + ]]: raise NotImplementedError() @property - def get_view( - self, - ) -> Callable[ - [logging_config.GetViewRequest], - Union[logging_config.LogView, Awaitable[logging_config.LogView]], - ]: + def get_view(self) -> Callable[ + [logging_config.GetViewRequest], + Union[ + logging_config.LogView, + Awaitable[logging_config.LogView] + ]]: raise NotImplementedError() @property - def create_view( - self, - ) -> Callable[ - [logging_config.CreateViewRequest], - Union[logging_config.LogView, Awaitable[logging_config.LogView]], - ]: + def create_view(self) -> Callable[ + [logging_config.CreateViewRequest], + Union[ + logging_config.LogView, + Awaitable[logging_config.LogView] + ]]: raise NotImplementedError() @property - def update_view( - self, - ) -> Callable[ - [logging_config.UpdateViewRequest], - Union[logging_config.LogView, Awaitable[logging_config.LogView]], - ]: + def update_view(self) -> Callable[ + [logging_config.UpdateViewRequest], + Union[ + logging_config.LogView, + Awaitable[logging_config.LogView] + ]]: raise NotImplementedError() @property - def delete_view( - self, - ) -> Callable[ - [logging_config.DeleteViewRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_view(self) -> Callable[ + [logging_config.DeleteViewRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def list_sinks( - self, - ) -> Callable[ - [logging_config.ListSinksRequest], - Union[ - logging_config.ListSinksResponse, - Awaitable[logging_config.ListSinksResponse], - ], - ]: + def list_sinks(self) -> Callable[ + [logging_config.ListSinksRequest], + Union[ + logging_config.ListSinksResponse, + Awaitable[logging_config.ListSinksResponse] + ]]: raise NotImplementedError() @property - def get_sink( - self, - ) -> Callable[ - [logging_config.GetSinkRequest], - Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], - ]: + def get_sink(self) -> Callable[ + [logging_config.GetSinkRequest], + Union[ + logging_config.LogSink, + Awaitable[logging_config.LogSink] + ]]: raise NotImplementedError() @property - def create_sink( - self, - ) -> Callable[ - [logging_config.CreateSinkRequest], - Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], - ]: + def create_sink(self) -> Callable[ + [logging_config.CreateSinkRequest], + Union[ + logging_config.LogSink, + Awaitable[logging_config.LogSink] + ]]: raise NotImplementedError() @property - def update_sink( - self, - ) -> Callable[ - [logging_config.UpdateSinkRequest], - Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], - ]: + def update_sink(self) -> Callable[ + [logging_config.UpdateSinkRequest], + Union[ + logging_config.LogSink, + Awaitable[logging_config.LogSink] + ]]: raise NotImplementedError() @property - def delete_sink( - self, - ) -> Callable[ - [logging_config.DeleteSinkRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_sink(self) -> Callable[ + [logging_config.DeleteSinkRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def create_link( - self, - ) -> Callable[ - [logging_config.CreateLinkRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_link(self) -> Callable[ + [logging_config.CreateLinkRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def delete_link( - self, - ) -> Callable[ - [logging_config.DeleteLinkRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def delete_link(self) -> Callable[ + [logging_config.DeleteLinkRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def list_links( - self, - ) -> Callable[ - [logging_config.ListLinksRequest], - Union[ - logging_config.ListLinksResponse, - Awaitable[logging_config.ListLinksResponse], - ], - ]: + def list_links(self) -> Callable[ + [logging_config.ListLinksRequest], + Union[ + logging_config.ListLinksResponse, + Awaitable[logging_config.ListLinksResponse] + ]]: raise NotImplementedError() @property - def get_link( - self, - ) -> Callable[ - [logging_config.GetLinkRequest], - Union[logging_config.Link, Awaitable[logging_config.Link]], - ]: + def get_link(self) -> Callable[ + [logging_config.GetLinkRequest], + Union[ + logging_config.Link, + Awaitable[logging_config.Link] + ]]: raise NotImplementedError() @property - def list_exclusions( - self, - ) -> Callable[ - [logging_config.ListExclusionsRequest], - Union[ - logging_config.ListExclusionsResponse, - Awaitable[logging_config.ListExclusionsResponse], - ], - ]: + def list_exclusions(self) -> Callable[ + [logging_config.ListExclusionsRequest], + Union[ + logging_config.ListExclusionsResponse, + Awaitable[logging_config.ListExclusionsResponse] + ]]: raise NotImplementedError() @property - def get_exclusion( - self, - ) -> Callable[ - [logging_config.GetExclusionRequest], - Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], - ]: + def get_exclusion(self) -> Callable[ + [logging_config.GetExclusionRequest], + Union[ + logging_config.LogExclusion, + Awaitable[logging_config.LogExclusion] + ]]: raise NotImplementedError() @property - def create_exclusion( - self, - ) -> Callable[ - [logging_config.CreateExclusionRequest], - Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], - ]: + def create_exclusion(self) -> Callable[ + [logging_config.CreateExclusionRequest], + Union[ + logging_config.LogExclusion, + Awaitable[logging_config.LogExclusion] + ]]: raise NotImplementedError() @property - def update_exclusion( - self, - ) -> Callable[ - [logging_config.UpdateExclusionRequest], - Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], - ]: + def update_exclusion(self) -> Callable[ + [logging_config.UpdateExclusionRequest], + Union[ + logging_config.LogExclusion, + Awaitable[logging_config.LogExclusion] + ]]: raise NotImplementedError() @property - def delete_exclusion( - self, - ) -> Callable[ - [logging_config.DeleteExclusionRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_exclusion(self) -> Callable[ + [logging_config.DeleteExclusionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def get_cmek_settings( - self, - ) -> Callable[ - [logging_config.GetCmekSettingsRequest], - Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], - ]: + def get_cmek_settings(self) -> Callable[ + [logging_config.GetCmekSettingsRequest], + Union[ + logging_config.CmekSettings, + Awaitable[logging_config.CmekSettings] + ]]: raise NotImplementedError() @property - def update_cmek_settings( - self, - ) -> Callable[ - [logging_config.UpdateCmekSettingsRequest], - Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], - ]: + def update_cmek_settings(self) -> Callable[ + [logging_config.UpdateCmekSettingsRequest], + Union[ + logging_config.CmekSettings, + Awaitable[logging_config.CmekSettings] + ]]: raise NotImplementedError() @property - def get_settings( - self, - ) -> Callable[ - [logging_config.GetSettingsRequest], - Union[logging_config.Settings, Awaitable[logging_config.Settings]], - ]: + def get_settings(self) -> Callable[ + [logging_config.GetSettingsRequest], + Union[ + logging_config.Settings, + Awaitable[logging_config.Settings] + ]]: raise NotImplementedError() @property - def update_settings( - self, - ) -> Callable[ - [logging_config.UpdateSettingsRequest], - Union[logging_config.Settings, Awaitable[logging_config.Settings]], - ]: + def update_settings(self) -> Callable[ + [logging_config.UpdateSettingsRequest], + Union[ + logging_config.Settings, + Awaitable[logging_config.Settings] + ]]: raise NotImplementedError() @property - def copy_log_entries( - self, - ) -> Callable[ - [logging_config.CopyLogEntriesRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def copy_log_entries(self) -> Callable[ + [logging_config.CopyLogEntriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property @@ -794,10 +762,7 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[ - operations_pb2.ListOperationsResponse, - Awaitable[operations_pb2.ListOperationsResponse], - ], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], ]: raise NotImplementedError() @@ -824,4 +789,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("ConfigServiceV2Transport",) +__all__ = ( + 'ConfigServiceV2Transport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index 0fd4a31ba7f8..164e83c216d9 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -17,19 +17,17 @@ import logging as std_logging import pickle import warnings -from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ( - ClientInterceptor, # type: ignore[attr-defined] - ) + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1, operations_v1 - +from google.api_core import gapic_v1 # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -37,21 +35,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -import google.protobuf.message -import proto # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import proto # type: ignore -from .base import DEFAULT_CLIENT_INFO, ConfigServiceV2Transport +from google.cloud.logging_v2.types import logging_config +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from .base import ConfigServiceV2Transport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -61,9 +59,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -84,7 +80,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.logging.v2.ConfigServiceV2", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -95,11 +91,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -114,7 +106,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.logging.v2.ConfigServiceV2", "rpcName": client_call_details.method, "response": grpc_response, @@ -136,35 +128,32 @@ class ConfigServiceV2GrpcTransport(ConfigServiceV2Transport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "logging.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], + def __init__(self, *, + host: str = 'logging.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], + ] ] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -301,17 +290,9 @@ def __init__( channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) - ) - is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None and otel_interceptor not in channel_interceptors - and not any( - getattr(i, "_is_otel_interceptor", None) is True - for i in channel_interceptors - ) + and not any(getattr(i, "_is_otel_interceptor", None) is True for i in channel_interceptors) ): channel_interceptors.append(otel_interceptor) @@ -320,28 +301,22 @@ def __init__( "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors( - self._grpc_channel, channel_interceptors - ) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "logging.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'logging.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -377,12 +352,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -402,11 +378,9 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def list_buckets( - self, - ) -> Callable[ - [logging_config.ListBucketsRequest], logging_config.ListBucketsResponse - ]: + def list_buckets(self) -> Callable[ + [logging_config.ListBucketsRequest], + logging_config.ListBucketsResponse]: r"""Return a callable for the list buckets method over gRPC. Lists log buckets. @@ -421,18 +395,18 @@ def list_buckets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_buckets" not in self._stubs: - self._stubs["list_buckets"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/ListBuckets", + if 'list_buckets' not in self._stubs: + self._stubs['list_buckets'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/ListBuckets', request_serializer=logging_config.ListBucketsRequest.serialize, response_deserializer=logging_config.ListBucketsResponse.deserialize, ) - return self._stubs["list_buckets"] + return self._stubs['list_buckets'] @property - def get_bucket( - self, - ) -> Callable[[logging_config.GetBucketRequest], logging_config.LogBucket]: + def get_bucket(self) -> Callable[ + [logging_config.GetBucketRequest], + logging_config.LogBucket]: r"""Return a callable for the get bucket method over gRPC. Gets a log bucket. @@ -447,18 +421,18 @@ def get_bucket( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_bucket" not in self._stubs: - self._stubs["get_bucket"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetBucket", + if 'get_bucket' not in self._stubs: + self._stubs['get_bucket'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetBucket', request_serializer=logging_config.GetBucketRequest.serialize, response_deserializer=logging_config.LogBucket.deserialize, ) - return self._stubs["get_bucket"] + return self._stubs['get_bucket'] @property - def create_bucket_async( - self, - ) -> Callable[[logging_config.CreateBucketRequest], operations_pb2.Operation]: + def create_bucket_async(self) -> Callable[ + [logging_config.CreateBucketRequest], + operations_pb2.Operation]: r"""Return a callable for the create bucket async method over gRPC. Creates a log bucket asynchronously that can be used @@ -476,18 +450,18 @@ def create_bucket_async( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_bucket_async" not in self._stubs: - self._stubs["create_bucket_async"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CreateBucketAsync", + if 'create_bucket_async' not in self._stubs: + self._stubs['create_bucket_async'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CreateBucketAsync', request_serializer=logging_config.CreateBucketRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_bucket_async"] + return self._stubs['create_bucket_async'] @property - def update_bucket_async( - self, - ) -> Callable[[logging_config.UpdateBucketRequest], operations_pb2.Operation]: + def update_bucket_async(self) -> Callable[ + [logging_config.UpdateBucketRequest], + operations_pb2.Operation]: r"""Return a callable for the update bucket async method over gRPC. Updates a log bucket asynchronously. @@ -508,18 +482,18 @@ def update_bucket_async( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_bucket_async" not in self._stubs: - self._stubs["update_bucket_async"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateBucketAsync", + if 'update_bucket_async' not in self._stubs: + self._stubs['update_bucket_async'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateBucketAsync', request_serializer=logging_config.UpdateBucketRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["update_bucket_async"] + return self._stubs['update_bucket_async'] @property - def create_bucket( - self, - ) -> Callable[[logging_config.CreateBucketRequest], logging_config.LogBucket]: + def create_bucket(self) -> Callable[ + [logging_config.CreateBucketRequest], + logging_config.LogBucket]: r"""Return a callable for the create bucket method over gRPC. Creates a log bucket that can be used to store log @@ -536,18 +510,18 @@ def create_bucket( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_bucket" not in self._stubs: - self._stubs["create_bucket"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CreateBucket", + if 'create_bucket' not in self._stubs: + self._stubs['create_bucket'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CreateBucket', request_serializer=logging_config.CreateBucketRequest.serialize, response_deserializer=logging_config.LogBucket.deserialize, ) - return self._stubs["create_bucket"] + return self._stubs['create_bucket'] @property - def update_bucket( - self, - ) -> Callable[[logging_config.UpdateBucketRequest], logging_config.LogBucket]: + def update_bucket(self) -> Callable[ + [logging_config.UpdateBucketRequest], + logging_config.LogBucket]: r"""Return a callable for the update bucket method over gRPC. Updates a log bucket. @@ -568,18 +542,18 @@ def update_bucket( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_bucket" not in self._stubs: - self._stubs["update_bucket"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateBucket", + if 'update_bucket' not in self._stubs: + self._stubs['update_bucket'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateBucket', request_serializer=logging_config.UpdateBucketRequest.serialize, response_deserializer=logging_config.LogBucket.deserialize, ) - return self._stubs["update_bucket"] + return self._stubs['update_bucket'] @property - def delete_bucket( - self, - ) -> Callable[[logging_config.DeleteBucketRequest], empty_pb2.Empty]: + def delete_bucket(self) -> Callable[ + [logging_config.DeleteBucketRequest], + empty_pb2.Empty]: r"""Return a callable for the delete bucket method over gRPC. Deletes a log bucket. @@ -599,18 +573,18 @@ def delete_bucket( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_bucket" not in self._stubs: - self._stubs["delete_bucket"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/DeleteBucket", + if 'delete_bucket' not in self._stubs: + self._stubs['delete_bucket'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/DeleteBucket', request_serializer=logging_config.DeleteBucketRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_bucket"] + return self._stubs['delete_bucket'] @property - def undelete_bucket( - self, - ) -> Callable[[logging_config.UndeleteBucketRequest], empty_pb2.Empty]: + def undelete_bucket(self) -> Callable[ + [logging_config.UndeleteBucketRequest], + empty_pb2.Empty]: r"""Return a callable for the undelete bucket method over gRPC. Undeletes a log bucket. A bucket that has been @@ -627,18 +601,18 @@ def undelete_bucket( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "undelete_bucket" not in self._stubs: - self._stubs["undelete_bucket"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UndeleteBucket", + if 'undelete_bucket' not in self._stubs: + self._stubs['undelete_bucket'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UndeleteBucket', request_serializer=logging_config.UndeleteBucketRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["undelete_bucket"] + return self._stubs['undelete_bucket'] @property - def list_views( - self, - ) -> Callable[[logging_config.ListViewsRequest], logging_config.ListViewsResponse]: + def list_views(self) -> Callable[ + [logging_config.ListViewsRequest], + logging_config.ListViewsResponse]: r"""Return a callable for the list views method over gRPC. Lists views on a log bucket. @@ -653,18 +627,18 @@ def list_views( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_views" not in self._stubs: - self._stubs["list_views"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/ListViews", + if 'list_views' not in self._stubs: + self._stubs['list_views'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/ListViews', request_serializer=logging_config.ListViewsRequest.serialize, response_deserializer=logging_config.ListViewsResponse.deserialize, ) - return self._stubs["list_views"] + return self._stubs['list_views'] @property - def get_view( - self, - ) -> Callable[[logging_config.GetViewRequest], logging_config.LogView]: + def get_view(self) -> Callable[ + [logging_config.GetViewRequest], + logging_config.LogView]: r"""Return a callable for the get view method over gRPC. Gets a view on a log bucket.. @@ -679,18 +653,18 @@ def get_view( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_view" not in self._stubs: - self._stubs["get_view"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetView", + if 'get_view' not in self._stubs: + self._stubs['get_view'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetView', request_serializer=logging_config.GetViewRequest.serialize, response_deserializer=logging_config.LogView.deserialize, ) - return self._stubs["get_view"] + return self._stubs['get_view'] @property - def create_view( - self, - ) -> Callable[[logging_config.CreateViewRequest], logging_config.LogView]: + def create_view(self) -> Callable[ + [logging_config.CreateViewRequest], + logging_config.LogView]: r"""Return a callable for the create view method over gRPC. Creates a view over log entries in a log bucket. A @@ -706,18 +680,18 @@ def create_view( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_view" not in self._stubs: - self._stubs["create_view"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CreateView", + if 'create_view' not in self._stubs: + self._stubs['create_view'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CreateView', request_serializer=logging_config.CreateViewRequest.serialize, response_deserializer=logging_config.LogView.deserialize, ) - return self._stubs["create_view"] + return self._stubs['create_view'] @property - def update_view( - self, - ) -> Callable[[logging_config.UpdateViewRequest], logging_config.LogView]: + def update_view(self) -> Callable[ + [logging_config.UpdateViewRequest], + logging_config.LogView]: r"""Return a callable for the update view method over gRPC. Updates a view on a log bucket. This method replaces the @@ -736,18 +710,18 @@ def update_view( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_view" not in self._stubs: - self._stubs["update_view"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateView", + if 'update_view' not in self._stubs: + self._stubs['update_view'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateView', request_serializer=logging_config.UpdateViewRequest.serialize, response_deserializer=logging_config.LogView.deserialize, ) - return self._stubs["update_view"] + return self._stubs['update_view'] @property - def delete_view( - self, - ) -> Callable[[logging_config.DeleteViewRequest], empty_pb2.Empty]: + def delete_view(self) -> Callable[ + [logging_config.DeleteViewRequest], + empty_pb2.Empty]: r"""Return a callable for the delete view method over gRPC. Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is @@ -765,18 +739,18 @@ def delete_view( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_view" not in self._stubs: - self._stubs["delete_view"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/DeleteView", + if 'delete_view' not in self._stubs: + self._stubs['delete_view'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/DeleteView', request_serializer=logging_config.DeleteViewRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_view"] + return self._stubs['delete_view'] @property - def list_sinks( - self, - ) -> Callable[[logging_config.ListSinksRequest], logging_config.ListSinksResponse]: + def list_sinks(self) -> Callable[ + [logging_config.ListSinksRequest], + logging_config.ListSinksResponse]: r"""Return a callable for the list sinks method over gRPC. Lists sinks. @@ -791,18 +765,18 @@ def list_sinks( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_sinks" not in self._stubs: - self._stubs["list_sinks"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/ListSinks", + if 'list_sinks' not in self._stubs: + self._stubs['list_sinks'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/ListSinks', request_serializer=logging_config.ListSinksRequest.serialize, response_deserializer=logging_config.ListSinksResponse.deserialize, ) - return self._stubs["list_sinks"] + return self._stubs['list_sinks'] @property - def get_sink( - self, - ) -> Callable[[logging_config.GetSinkRequest], logging_config.LogSink]: + def get_sink(self) -> Callable[ + [logging_config.GetSinkRequest], + logging_config.LogSink]: r"""Return a callable for the get sink method over gRPC. Gets a sink. @@ -817,18 +791,18 @@ def get_sink( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_sink" not in self._stubs: - self._stubs["get_sink"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetSink", + if 'get_sink' not in self._stubs: + self._stubs['get_sink'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetSink', request_serializer=logging_config.GetSinkRequest.serialize, response_deserializer=logging_config.LogSink.deserialize, ) - return self._stubs["get_sink"] + return self._stubs['get_sink'] @property - def create_sink( - self, - ) -> Callable[[logging_config.CreateSinkRequest], logging_config.LogSink]: + def create_sink(self) -> Callable[ + [logging_config.CreateSinkRequest], + logging_config.LogSink]: r"""Return a callable for the create sink method over gRPC. Creates a sink that exports specified log entries to a @@ -847,18 +821,18 @@ def create_sink( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_sink" not in self._stubs: - self._stubs["create_sink"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CreateSink", + if 'create_sink' not in self._stubs: + self._stubs['create_sink'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CreateSink', request_serializer=logging_config.CreateSinkRequest.serialize, response_deserializer=logging_config.LogSink.deserialize, ) - return self._stubs["create_sink"] + return self._stubs['create_sink'] @property - def update_sink( - self, - ) -> Callable[[logging_config.UpdateSinkRequest], logging_config.LogSink]: + def update_sink(self) -> Callable[ + [logging_config.UpdateSinkRequest], + logging_config.LogSink]: r"""Return a callable for the update sink method over gRPC. Updates a sink. This method replaces the following fields in the @@ -878,18 +852,18 @@ def update_sink( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_sink" not in self._stubs: - self._stubs["update_sink"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateSink", + if 'update_sink' not in self._stubs: + self._stubs['update_sink'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateSink', request_serializer=logging_config.UpdateSinkRequest.serialize, response_deserializer=logging_config.LogSink.deserialize, ) - return self._stubs["update_sink"] + return self._stubs['update_sink'] @property - def delete_sink( - self, - ) -> Callable[[logging_config.DeleteSinkRequest], empty_pb2.Empty]: + def delete_sink(self) -> Callable[ + [logging_config.DeleteSinkRequest], + empty_pb2.Empty]: r"""Return a callable for the delete sink method over gRPC. Deletes a sink. If the sink has a unique ``writer_identity``, @@ -905,18 +879,18 @@ def delete_sink( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_sink" not in self._stubs: - self._stubs["delete_sink"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/DeleteSink", + if 'delete_sink' not in self._stubs: + self._stubs['delete_sink'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/DeleteSink', request_serializer=logging_config.DeleteSinkRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_sink"] + return self._stubs['delete_sink'] @property - def create_link( - self, - ) -> Callable[[logging_config.CreateLinkRequest], operations_pb2.Operation]: + def create_link(self) -> Callable[ + [logging_config.CreateLinkRequest], + operations_pb2.Operation]: r"""Return a callable for the create link method over gRPC. Asynchronously creates a linked dataset in BigQuery @@ -934,18 +908,18 @@ def create_link( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_link" not in self._stubs: - self._stubs["create_link"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CreateLink", + if 'create_link' not in self._stubs: + self._stubs['create_link'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CreateLink', request_serializer=logging_config.CreateLinkRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_link"] + return self._stubs['create_link'] @property - def delete_link( - self, - ) -> Callable[[logging_config.DeleteLinkRequest], operations_pb2.Operation]: + def delete_link(self) -> Callable[ + [logging_config.DeleteLinkRequest], + operations_pb2.Operation]: r"""Return a callable for the delete link method over gRPC. Deletes a link. This will also delete the @@ -961,18 +935,18 @@ def delete_link( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_link" not in self._stubs: - self._stubs["delete_link"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/DeleteLink", + if 'delete_link' not in self._stubs: + self._stubs['delete_link'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/DeleteLink', request_serializer=logging_config.DeleteLinkRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["delete_link"] + return self._stubs['delete_link'] @property - def list_links( - self, - ) -> Callable[[logging_config.ListLinksRequest], logging_config.ListLinksResponse]: + def list_links(self) -> Callable[ + [logging_config.ListLinksRequest], + logging_config.ListLinksResponse]: r"""Return a callable for the list links method over gRPC. Lists links. @@ -987,18 +961,18 @@ def list_links( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_links" not in self._stubs: - self._stubs["list_links"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/ListLinks", + if 'list_links' not in self._stubs: + self._stubs['list_links'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/ListLinks', request_serializer=logging_config.ListLinksRequest.serialize, response_deserializer=logging_config.ListLinksResponse.deserialize, ) - return self._stubs["list_links"] + return self._stubs['list_links'] @property - def get_link( - self, - ) -> Callable[[logging_config.GetLinkRequest], logging_config.Link]: + def get_link(self) -> Callable[ + [logging_config.GetLinkRequest], + logging_config.Link]: r"""Return a callable for the get link method over gRPC. Gets a link. @@ -1013,20 +987,18 @@ def get_link( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_link" not in self._stubs: - self._stubs["get_link"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetLink", + if 'get_link' not in self._stubs: + self._stubs['get_link'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetLink', request_serializer=logging_config.GetLinkRequest.serialize, response_deserializer=logging_config.Link.deserialize, ) - return self._stubs["get_link"] + return self._stubs['get_link'] @property - def list_exclusions( - self, - ) -> Callable[ - [logging_config.ListExclusionsRequest], logging_config.ListExclusionsResponse - ]: + def list_exclusions(self) -> Callable[ + [logging_config.ListExclusionsRequest], + logging_config.ListExclusionsResponse]: r"""Return a callable for the list exclusions method over gRPC. Lists all the exclusions on the \_Default sink in a parent @@ -1042,18 +1014,18 @@ def list_exclusions( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_exclusions" not in self._stubs: - self._stubs["list_exclusions"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/ListExclusions", + if 'list_exclusions' not in self._stubs: + self._stubs['list_exclusions'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/ListExclusions', request_serializer=logging_config.ListExclusionsRequest.serialize, response_deserializer=logging_config.ListExclusionsResponse.deserialize, ) - return self._stubs["list_exclusions"] + return self._stubs['list_exclusions'] @property - def get_exclusion( - self, - ) -> Callable[[logging_config.GetExclusionRequest], logging_config.LogExclusion]: + def get_exclusion(self) -> Callable[ + [logging_config.GetExclusionRequest], + logging_config.LogExclusion]: r"""Return a callable for the get exclusion method over gRPC. Gets the description of an exclusion in the \_Default sink. @@ -1068,18 +1040,18 @@ def get_exclusion( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_exclusion" not in self._stubs: - self._stubs["get_exclusion"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetExclusion", + if 'get_exclusion' not in self._stubs: + self._stubs['get_exclusion'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetExclusion', request_serializer=logging_config.GetExclusionRequest.serialize, response_deserializer=logging_config.LogExclusion.deserialize, ) - return self._stubs["get_exclusion"] + return self._stubs['get_exclusion'] @property - def create_exclusion( - self, - ) -> Callable[[logging_config.CreateExclusionRequest], logging_config.LogExclusion]: + def create_exclusion(self) -> Callable[ + [logging_config.CreateExclusionRequest], + logging_config.LogExclusion]: r"""Return a callable for the create exclusion method over gRPC. Creates a new exclusion in the \_Default sink in a specified @@ -1096,18 +1068,18 @@ def create_exclusion( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_exclusion" not in self._stubs: - self._stubs["create_exclusion"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CreateExclusion", + if 'create_exclusion' not in self._stubs: + self._stubs['create_exclusion'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CreateExclusion', request_serializer=logging_config.CreateExclusionRequest.serialize, response_deserializer=logging_config.LogExclusion.deserialize, ) - return self._stubs["create_exclusion"] + return self._stubs['create_exclusion'] @property - def update_exclusion( - self, - ) -> Callable[[logging_config.UpdateExclusionRequest], logging_config.LogExclusion]: + def update_exclusion(self) -> Callable[ + [logging_config.UpdateExclusionRequest], + logging_config.LogExclusion]: r"""Return a callable for the update exclusion method over gRPC. Changes one or more properties of an existing exclusion in the @@ -1123,18 +1095,18 @@ def update_exclusion( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_exclusion" not in self._stubs: - self._stubs["update_exclusion"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateExclusion", + if 'update_exclusion' not in self._stubs: + self._stubs['update_exclusion'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateExclusion', request_serializer=logging_config.UpdateExclusionRequest.serialize, response_deserializer=logging_config.LogExclusion.deserialize, ) - return self._stubs["update_exclusion"] + return self._stubs['update_exclusion'] @property - def delete_exclusion( - self, - ) -> Callable[[logging_config.DeleteExclusionRequest], empty_pb2.Empty]: + def delete_exclusion(self) -> Callable[ + [logging_config.DeleteExclusionRequest], + empty_pb2.Empty]: r"""Return a callable for the delete exclusion method over gRPC. Deletes an exclusion in the \_Default sink. @@ -1149,18 +1121,18 @@ def delete_exclusion( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_exclusion" not in self._stubs: - self._stubs["delete_exclusion"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/DeleteExclusion", + if 'delete_exclusion' not in self._stubs: + self._stubs['delete_exclusion'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/DeleteExclusion', request_serializer=logging_config.DeleteExclusionRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_exclusion"] + return self._stubs['delete_exclusion'] @property - def get_cmek_settings( - self, - ) -> Callable[[logging_config.GetCmekSettingsRequest], logging_config.CmekSettings]: + def get_cmek_settings(self) -> Callable[ + [logging_config.GetCmekSettingsRequest], + logging_config.CmekSettings]: r"""Return a callable for the get cmek settings method over gRPC. Gets the Logging CMEK settings for the given resource. @@ -1184,20 +1156,18 @@ def get_cmek_settings( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_cmek_settings" not in self._stubs: - self._stubs["get_cmek_settings"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetCmekSettings", + if 'get_cmek_settings' not in self._stubs: + self._stubs['get_cmek_settings'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetCmekSettings', request_serializer=logging_config.GetCmekSettingsRequest.serialize, response_deserializer=logging_config.CmekSettings.deserialize, ) - return self._stubs["get_cmek_settings"] + return self._stubs['get_cmek_settings'] @property - def update_cmek_settings( - self, - ) -> Callable[ - [logging_config.UpdateCmekSettingsRequest], logging_config.CmekSettings - ]: + def update_cmek_settings(self) -> Callable[ + [logging_config.UpdateCmekSettingsRequest], + logging_config.CmekSettings]: r"""Return a callable for the update cmek settings method over gRPC. Updates the Log Router CMEK settings for the given resource. @@ -1226,18 +1196,18 @@ def update_cmek_settings( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_cmek_settings" not in self._stubs: - self._stubs["update_cmek_settings"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateCmekSettings", + if 'update_cmek_settings' not in self._stubs: + self._stubs['update_cmek_settings'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateCmekSettings', request_serializer=logging_config.UpdateCmekSettingsRequest.serialize, response_deserializer=logging_config.CmekSettings.deserialize, ) - return self._stubs["update_cmek_settings"] + return self._stubs['update_cmek_settings'] @property - def get_settings( - self, - ) -> Callable[[logging_config.GetSettingsRequest], logging_config.Settings]: + def get_settings(self) -> Callable[ + [logging_config.GetSettingsRequest], + logging_config.Settings]: r"""Return a callable for the get settings method over gRPC. Gets the Log Router settings for the given resource. @@ -1262,18 +1232,18 @@ def get_settings( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_settings" not in self._stubs: - self._stubs["get_settings"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetSettings", + if 'get_settings' not in self._stubs: + self._stubs['get_settings'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetSettings', request_serializer=logging_config.GetSettingsRequest.serialize, response_deserializer=logging_config.Settings.deserialize, ) - return self._stubs["get_settings"] + return self._stubs['get_settings'] @property - def update_settings( - self, - ) -> Callable[[logging_config.UpdateSettingsRequest], logging_config.Settings]: + def update_settings(self) -> Callable[ + [logging_config.UpdateSettingsRequest], + logging_config.Settings]: r"""Return a callable for the update settings method over gRPC. Updates the Log Router settings for the given resource. @@ -1305,18 +1275,18 @@ def update_settings( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_settings" not in self._stubs: - self._stubs["update_settings"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateSettings", + if 'update_settings' not in self._stubs: + self._stubs['update_settings'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateSettings', request_serializer=logging_config.UpdateSettingsRequest.serialize, response_deserializer=logging_config.Settings.deserialize, ) - return self._stubs["update_settings"] + return self._stubs['update_settings'] @property - def copy_log_entries( - self, - ) -> Callable[[logging_config.CopyLogEntriesRequest], operations_pb2.Operation]: + def copy_log_entries(self) -> Callable[ + [logging_config.CopyLogEntriesRequest], + operations_pb2.Operation]: r"""Return a callable for the copy log entries method over gRPC. Copies a set of log entries from a log bucket to a @@ -1332,13 +1302,13 @@ def copy_log_entries( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "copy_log_entries" not in self._stubs: - self._stubs["copy_log_entries"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CopyLogEntries", + if 'copy_log_entries' not in self._stubs: + self._stubs['copy_log_entries'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CopyLogEntries', request_serializer=logging_config.CopyLogEntriesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["copy_log_entries"] + return self._stubs['copy_log_entries'] def close(self): self._logged_channel.close() @@ -1347,7 +1317,8 @@ def close(self): def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC.""" + r"""Return a callable for the cancel_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1364,7 +1335,8 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1380,10 +1352,9 @@ def get_operation( @property def list_operations( self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse - ]: - r"""Return a callable for the list_operations method over gRPC.""" + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1401,4 +1372,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("ConfigServiceV2GrpcTransport",) +__all__ = ( + 'ConfigServiceV2GrpcTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py index 40c01d7305c8..1a479a753bae 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -13,48 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import inspect import json import logging as std_logging import os import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast import warnings -from collections import OrderedDict -from http import HTTPStatus -from typing import ( - Callable, - Dict, - Iterable, - Iterator, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import google.protobuf +from google.cloud.logging_v2 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.logging_v2 import gapic_version as package_version -from google.cloud.logging_v2._compat import ( - get_api_endpoint, - get_default_mtls_endpoint, - get_universe_domain, - read_environment_variables, - should_use_client_cert, -) -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -63,7 +44,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -77,12 +57,12 @@ _LOGGER = std_logging.getLogger(__name__) -import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore from google.cloud.logging_v2.services.logging_service_v2 import pagers -from google.cloud.logging_v2.types import log_entry, logging -from google.longrunning import operations_pb2 # type: ignore - -from .transports.base import DEFAULT_CLIENT_INFO, LoggingServiceV2Transport +from google.cloud.logging_v2.types import log_entry +from google.cloud.logging_v2.types import logging +from google.longrunning import operations_pb2 # type: ignore +import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore +from .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO from .transports.grpc import LoggingServiceV2GrpcTransport from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport @@ -94,15 +74,13 @@ class LoggingServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[LoggingServiceV2Transport]] _transport_registry["grpc"] = LoggingServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = LoggingServiceV2GrpcAsyncIOTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[LoggingServiceV2Transport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[LoggingServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -162,7 +140,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LoggingServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -179,103 +158,73 @@ def transport(self) -> LoggingServiceV2Transport: return self._transport @staticmethod - def log_path( - project: str, - log: str, - ) -> str: + def log_path(project: str,log: str,) -> str: """Returns a fully-qualified log string.""" - return "projects/{project}/logs/{log}".format( - project=project, - log=log, - ) + return "projects/{project}/logs/{log}".format(project=project, log=log, ) @staticmethod - def parse_log_path(path: str) -> Dict[str, str]: + def parse_log_path(path: str) -> Dict[str,str]: """Parses a log path into its component segments.""" m = re.match(r"^projects/(?P.+?)/logs/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -307,18 +256,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -331,10 +276,8 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -373,18 +316,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -417,18 +357,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[ - str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the logging service v2 client. Args: @@ -483,23 +417,13 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - read_environment_variables() - ) - self._client_cert_source = LoggingServiceV2Client._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = get_universe_domain( - universe_domain_opt, - self._universe_domain_env, - default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE, - ) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() + self._client_cert_source = LoggingServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -511,9 +435,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -522,41 +444,35 @@ def __init__( if transport_provided: # transport is a LoggingServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = cast(LoggingServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = self._api_endpoint or get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE, - default_mtls_endpoint=LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" - or (self._use_mtls_endpoint == "auto" and self._client_cert_source), - ) + self._api_endpoint = (self._api_endpoint or + get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE, + default_mtls_endpoint=LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" or ( + self._use_mtls_endpoint == "auto" and self._client_cert_source + ), + )) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[LoggingServiceV2Transport], - Callable[..., LoggingServiceV2Transport], - ] = ( + transport_init: Union[Type[LoggingServiceV2Transport], Callable[..., LoggingServiceV2Transport]] = ( LoggingServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., LoggingServiceV2Transport], transport) @@ -585,46 +501,33 @@ def __init__( "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **( - {"client_options": client_options} - if client_options is not None - else {} - ), + **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.LoggingServiceV2Client`.", - extra={ + extra = { "serviceName": "google.logging.v2.LoggingServiceV2", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.logging.v2.LoggingServiceV2", "credentialsType": None, - }, + } ) - def delete_log( - self, - request: Optional[Union[logging.DeleteLogRequest, dict]] = None, - *, - log_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_log(self, + request: Optional[Union[logging.DeleteLogRequest, dict]] = None, + *, + log_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes all the log entries in a log for the \_Default Log Bucket. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be @@ -687,14 +590,10 @@ def sample_delete_log(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -712,7 +611,9 @@ def sample_delete_log(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("log_name", request.log_name), + )), ) # Validate the universe domain. @@ -726,18 +627,17 @@ def sample_delete_log(): metadata=metadata, ) - def write_log_entries( - self, - request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, - *, - log_name: Optional[str] = None, - resource: Optional[monitored_resource_pb2.MonitoredResource] = None, - labels: Optional[MutableMapping[str, str]] = None, - entries: Optional[MutableSequence[log_entry.LogEntry]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging.WriteLogEntriesResponse: + def write_log_entries(self, + request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, + *, + log_name: Optional[str] = None, + resource: Optional[monitored_resource_pb2.MonitoredResource] = None, + labels: Optional[MutableMapping[str, str]] = None, + entries: Optional[MutableSequence[log_entry.LogEntry]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging.WriteLogEntriesResponse: r"""Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent @@ -880,14 +780,10 @@ def sample_write_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name, resource, labels, entries] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -922,17 +818,16 @@ def sample_write_log_entries(): # Done; return the response. return response - def list_log_entries( - self, - request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, - *, - resource_names: Optional[MutableSequence[str]] = None, - filter: Optional[str] = None, - order_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogEntriesPager: + def list_log_entries(self, + request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, + *, + resource_names: Optional[MutableSequence[str]] = None, + filter: Optional[str] = None, + order_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogEntriesPager: r"""Lists log entries. Use this method to retrieve log entries that originated from a project/folder/organization/billing account. For ways to export log entries, see `Exporting @@ -1035,14 +930,10 @@ def sample_list_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [resource_names, filter, order_by] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1086,16 +977,13 @@ def sample_list_log_entries(): # Done; return the response. return response - def list_monitored_resource_descriptors( - self, - request: Optional[ - Union[logging.ListMonitoredResourceDescriptorsRequest, dict] - ] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMonitoredResourceDescriptorsPager: + def list_monitored_resource_descriptors(self, + request: Optional[Union[logging.ListMonitoredResourceDescriptorsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMonitoredResourceDescriptorsPager: r"""Lists the descriptors for monitored resource types used by Logging. @@ -1154,9 +1042,7 @@ def sample_list_monitored_resource_descriptors(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.list_monitored_resource_descriptors - ] + rpc = self._transport._wrapped_methods[self._transport.list_monitored_resource_descriptors] # Validate the universe domain. self._validate_universe_domain() @@ -1183,15 +1069,14 @@ def sample_list_monitored_resource_descriptors(): # Done; return the response. return response - def list_logs( - self, - request: Optional[Union[logging.ListLogsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogsPager: + def list_logs(self, + request: Optional[Union[logging.ListLogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogsPager: r"""Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have entries are listed. @@ -1258,14 +1143,10 @@ def sample_list_logs(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1283,7 +1164,9 @@ def sample_list_logs(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1311,14 +1194,13 @@ def sample_list_logs(): # Done; return the response. return response - def tail_log_entries( - self, - requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Iterable[logging.TailLogEntriesResponse]: + def tail_log_entries(self, + requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[logging.TailLogEntriesResponse]: r"""Streaming read of log entries as they are ingested. Until the stream is terminated, it will continue reading logs. @@ -1449,7 +1331,8 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1458,11 +1341,7 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1512,7 +1391,8 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1521,11 +1401,7 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1578,24 +1454,25 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("LoggingServiceV2Client",) +__all__ = ( + "LoggingServiceV2Client", +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index 82763d3d459b..5be4cc6ca83e 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -17,23 +17,23 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import google.api_core +from google.cloud.logging_v2 import gapic_version as package_version + import google.auth # type: ignore -import google.protobuf -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.api_core from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.cloud.logging_v2 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore +import google.protobuf + from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ # Check once at module load time whether google-api-core's wrap_method supports @@ -48,29 +48,28 @@ class LoggingServiceV2Transport(abc.ABC): """Abstract transport class for LoggingServiceV2.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-platform.read-only", - "https://www.googleapis.com/auth/logging.admin", - "https://www.googleapis.com/auth/logging.read", - "https://www.googleapis.com/auth/logging.write", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + 'https://www.googleapis.com/auth/logging.admin', + 'https://www.googleapis.com/auth/logging.read', + 'https://www.googleapis.com/auth/logging.write', ) - DEFAULT_HOST: str = "logging.googleapis.com" + DEFAULT_HOST: str = 'logging.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -112,43 +111,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host self._client_options = client_options @@ -175,12 +162,7 @@ def _wrap_method(self, func, *args, **kwargs): # of google-api-core is installed (which does not accept client_options, etc.). # Excluded from coverage because our CI and testing environments always install # a modern version of google-api-core that supports tracing. - for k in [ - "client_options", - "method_name", - "is_streaming", - "kind", - ]: # pragma: NO COVER + for k in ["client_options", "method_name", "is_streaming", "kind"]: # pragma: NO COVER kwargs.pop(k, None) # pragma: NO COVER return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER @@ -305,77 +287,69 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def delete_log( - self, - ) -> Callable[ - [logging.DeleteLogRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] - ]: + def delete_log(self) -> Callable[ + [logging.DeleteLogRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def write_log_entries( - self, - ) -> Callable[ - [logging.WriteLogEntriesRequest], - Union[ - logging.WriteLogEntriesResponse, Awaitable[logging.WriteLogEntriesResponse] - ], - ]: + def write_log_entries(self) -> Callable[ + [logging.WriteLogEntriesRequest], + Union[ + logging.WriteLogEntriesResponse, + Awaitable[logging.WriteLogEntriesResponse] + ]]: raise NotImplementedError() @property - def list_log_entries( - self, - ) -> Callable[ - [logging.ListLogEntriesRequest], - Union[ - logging.ListLogEntriesResponse, Awaitable[logging.ListLogEntriesResponse] - ], - ]: + def list_log_entries(self) -> Callable[ + [logging.ListLogEntriesRequest], + Union[ + logging.ListLogEntriesResponse, + Awaitable[logging.ListLogEntriesResponse] + ]]: raise NotImplementedError() @property - def list_monitored_resource_descriptors( - self, - ) -> Callable[ - [logging.ListMonitoredResourceDescriptorsRequest], - Union[ - logging.ListMonitoredResourceDescriptorsResponse, - Awaitable[logging.ListMonitoredResourceDescriptorsResponse], - ], - ]: + def list_monitored_resource_descriptors(self) -> Callable[ + [logging.ListMonitoredResourceDescriptorsRequest], + Union[ + logging.ListMonitoredResourceDescriptorsResponse, + Awaitable[logging.ListMonitoredResourceDescriptorsResponse] + ]]: raise NotImplementedError() @property - def list_logs( - self, - ) -> Callable[ - [logging.ListLogsRequest], - Union[logging.ListLogsResponse, Awaitable[logging.ListLogsResponse]], - ]: + def list_logs(self) -> Callable[ + [logging.ListLogsRequest], + Union[ + logging.ListLogsResponse, + Awaitable[logging.ListLogsResponse] + ]]: raise NotImplementedError() @property - def tail_log_entries( - self, - ) -> Callable[ - [logging.TailLogEntriesRequest], - Union[ - logging.TailLogEntriesResponse, Awaitable[logging.TailLogEntriesResponse] - ], - ]: + def tail_log_entries(self) -> Callable[ + [logging.TailLogEntriesRequest], + Union[ + logging.TailLogEntriesResponse, + Awaitable[logging.TailLogEntriesResponse] + ]]: raise NotImplementedError() @property @@ -383,10 +357,7 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[ - operations_pb2.ListOperationsResponse, - Awaitable[operations_pb2.ListOperationsResponse], - ], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], ]: raise NotImplementedError() @@ -413,4 +384,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("LoggingServiceV2Transport",) +__all__ = ( + 'LoggingServiceV2Transport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index bd4c44c84030..5e994ee69806 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -17,19 +17,16 @@ import logging as std_logging import pickle import warnings -from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ( - ClientInterceptor, # type: ignore[attr-defined] - ) + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 - # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -37,21 +34,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -import google.protobuf.message -import proto # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import proto # type: ignore -from .base import DEFAULT_CLIENT_INFO, LoggingServiceV2Transport +from google.cloud.logging_v2.types import logging +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from .base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -61,9 +58,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -84,7 +79,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.logging.v2.LoggingServiceV2", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -95,11 +90,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -114,7 +105,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.logging.v2.LoggingServiceV2", "rpcName": client_call_details.method, "response": grpc_response, @@ -136,35 +127,32 @@ class LoggingServiceV2GrpcTransport(LoggingServiceV2Transport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "logging.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], + def __init__(self, *, + host: str = 'logging.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], + ] ] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -300,17 +288,9 @@ def __init__( channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) - ) - is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None and otel_interceptor not in channel_interceptors - and not any( - getattr(i, "_is_otel_interceptor", None) is True - for i in channel_interceptors - ) + and not any(getattr(i, "_is_otel_interceptor", None) is True for i in channel_interceptors) ): channel_interceptors.append(otel_interceptor) @@ -319,28 +299,22 @@ def __init__( "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors( - self._grpc_channel, channel_interceptors - ) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "logging.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'logging.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -376,16 +350,19 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property - def delete_log(self) -> Callable[[logging.DeleteLogRequest], empty_pb2.Empty]: + def delete_log(self) -> Callable[ + [logging.DeleteLogRequest], + empty_pb2.Empty]: r"""Return a callable for the delete log method over gRPC. Deletes all the log entries in a log for the \_Default Log @@ -404,18 +381,18 @@ def delete_log(self) -> Callable[[logging.DeleteLogRequest], empty_pb2.Empty]: # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_log" not in self._stubs: - self._stubs["delete_log"] = self._logged_channel.unary_unary( - "/google.logging.v2.LoggingServiceV2/DeleteLog", + if 'delete_log' not in self._stubs: + self._stubs['delete_log'] = self._logged_channel.unary_unary( + '/google.logging.v2.LoggingServiceV2/DeleteLog', request_serializer=logging.DeleteLogRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_log"] + return self._stubs['delete_log'] @property - def write_log_entries( - self, - ) -> Callable[[logging.WriteLogEntriesRequest], logging.WriteLogEntriesResponse]: + def write_log_entries(self) -> Callable[ + [logging.WriteLogEntriesRequest], + logging.WriteLogEntriesResponse]: r"""Return a callable for the write log entries method over gRPC. Writes log entries to Logging. This API method is the @@ -436,18 +413,18 @@ def write_log_entries( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "write_log_entries" not in self._stubs: - self._stubs["write_log_entries"] = self._logged_channel.unary_unary( - "/google.logging.v2.LoggingServiceV2/WriteLogEntries", + if 'write_log_entries' not in self._stubs: + self._stubs['write_log_entries'] = self._logged_channel.unary_unary( + '/google.logging.v2.LoggingServiceV2/WriteLogEntries', request_serializer=logging.WriteLogEntriesRequest.serialize, response_deserializer=logging.WriteLogEntriesResponse.deserialize, ) - return self._stubs["write_log_entries"] + return self._stubs['write_log_entries'] @property - def list_log_entries( - self, - ) -> Callable[[logging.ListLogEntriesRequest], logging.ListLogEntriesResponse]: + def list_log_entries(self) -> Callable[ + [logging.ListLogEntriesRequest], + logging.ListLogEntriesResponse]: r"""Return a callable for the list log entries method over gRPC. Lists log entries. Use this method to retrieve log entries that @@ -465,21 +442,18 @@ def list_log_entries( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_log_entries" not in self._stubs: - self._stubs["list_log_entries"] = self._logged_channel.unary_unary( - "/google.logging.v2.LoggingServiceV2/ListLogEntries", + if 'list_log_entries' not in self._stubs: + self._stubs['list_log_entries'] = self._logged_channel.unary_unary( + '/google.logging.v2.LoggingServiceV2/ListLogEntries', request_serializer=logging.ListLogEntriesRequest.serialize, response_deserializer=logging.ListLogEntriesResponse.deserialize, ) - return self._stubs["list_log_entries"] + return self._stubs['list_log_entries'] @property - def list_monitored_resource_descriptors( - self, - ) -> Callable[ - [logging.ListMonitoredResourceDescriptorsRequest], - logging.ListMonitoredResourceDescriptorsResponse, - ]: + def list_monitored_resource_descriptors(self) -> Callable[ + [logging.ListMonitoredResourceDescriptorsRequest], + logging.ListMonitoredResourceDescriptorsResponse]: r"""Return a callable for the list monitored resource descriptors method over gRPC. @@ -496,20 +470,18 @@ def list_monitored_resource_descriptors( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_monitored_resource_descriptors" not in self._stubs: - self._stubs["list_monitored_resource_descriptors"] = ( - self._logged_channel.unary_unary( - "/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors", - request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize, - response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize, - ) + if 'list_monitored_resource_descriptors' not in self._stubs: + self._stubs['list_monitored_resource_descriptors'] = self._logged_channel.unary_unary( + '/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors', + request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize, + response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize, ) - return self._stubs["list_monitored_resource_descriptors"] + return self._stubs['list_monitored_resource_descriptors'] @property - def list_logs( - self, - ) -> Callable[[logging.ListLogsRequest], logging.ListLogsResponse]: + def list_logs(self) -> Callable[ + [logging.ListLogsRequest], + logging.ListLogsResponse]: r"""Return a callable for the list logs method over gRPC. Lists the logs in projects, organizations, folders, @@ -526,18 +498,18 @@ def list_logs( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_logs" not in self._stubs: - self._stubs["list_logs"] = self._logged_channel.unary_unary( - "/google.logging.v2.LoggingServiceV2/ListLogs", + if 'list_logs' not in self._stubs: + self._stubs['list_logs'] = self._logged_channel.unary_unary( + '/google.logging.v2.LoggingServiceV2/ListLogs', request_serializer=logging.ListLogsRequest.serialize, response_deserializer=logging.ListLogsResponse.deserialize, ) - return self._stubs["list_logs"] + return self._stubs['list_logs'] @property - def tail_log_entries( - self, - ) -> Callable[[logging.TailLogEntriesRequest], logging.TailLogEntriesResponse]: + def tail_log_entries(self) -> Callable[ + [logging.TailLogEntriesRequest], + logging.TailLogEntriesResponse]: r"""Return a callable for the tail log entries method over gRPC. Streaming read of log entries as they are ingested. @@ -554,13 +526,13 @@ def tail_log_entries( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "tail_log_entries" not in self._stubs: - self._stubs["tail_log_entries"] = self._logged_channel.stream_stream( - "/google.logging.v2.LoggingServiceV2/TailLogEntries", + if 'tail_log_entries' not in self._stubs: + self._stubs['tail_log_entries'] = self._logged_channel.stream_stream( + '/google.logging.v2.LoggingServiceV2/TailLogEntries', request_serializer=logging.TailLogEntriesRequest.serialize, response_deserializer=logging.TailLogEntriesResponse.deserialize, ) - return self._stubs["tail_log_entries"] + return self._stubs['tail_log_entries'] def close(self): self._logged_channel.close() @@ -569,7 +541,8 @@ def close(self): def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC.""" + r"""Return a callable for the cancel_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -586,7 +559,8 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -602,10 +576,9 @@ def get_operation( @property def list_operations( self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse - ]: - r"""Return a callable for the list_operations method over gRPC.""" + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -623,4 +596,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("LoggingServiceV2GrpcTransport",) +__all__ = ( + 'LoggingServiceV2GrpcTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py index 45708b5c5e34..0deb3709d39c 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -13,46 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import inspect import json import logging as std_logging import os import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings -from collections import OrderedDict -from http import HTTPStatus -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import google.protobuf +from google.cloud.logging_v2 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.logging_v2 import gapic_version as package_version -from google.cloud.logging_v2._compat import ( - get_api_endpoint, - get_default_mtls_endpoint, - get_universe_domain, - read_environment_variables, - should_use_client_cert, -) -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -61,7 +44,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -75,14 +57,13 @@ _LOGGER = std_logging.getLogger(__name__) +from google.cloud.logging_v2.services.metrics_service_v2 import pagers +from google.cloud.logging_v2.types import logging_metrics +from google.longrunning import operations_pb2 # type: ignore import google.api.distribution_pb2 as distribution_pb2 # type: ignore import google.api.metric_pb2 as metric_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from google.cloud.logging_v2.services.metrics_service_v2 import pagers -from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore - -from .transports.base import DEFAULT_CLIENT_INFO, MetricsServiceV2Transport +from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO from .transports.grpc import MetricsServiceV2GrpcTransport from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport @@ -94,15 +75,13 @@ class MetricsServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[MetricsServiceV2Transport]] _transport_registry["grpc"] = MetricsServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[MetricsServiceV2Transport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[MetricsServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -162,7 +141,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: MetricsServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -179,103 +159,73 @@ def transport(self) -> MetricsServiceV2Transport: return self._transport @staticmethod - def log_metric_path( - project: str, - metric: str, - ) -> str: + def log_metric_path(project: str,metric: str,) -> str: """Returns a fully-qualified log_metric string.""" - return "projects/{project}/metrics/{metric}".format( - project=project, - metric=metric, - ) + return "projects/{project}/metrics/{metric}".format(project=project, metric=metric, ) @staticmethod - def parse_log_metric_path(path: str) -> Dict[str, str]: + def parse_log_metric_path(path: str) -> Dict[str,str]: """Parses a log_metric path into its component segments.""" m = re.match(r"^projects/(?P.+?)/metrics/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -307,18 +257,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -331,10 +277,8 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -373,18 +317,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -417,18 +358,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[ - str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the metrics service v2 client. Args: @@ -483,23 +418,13 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - read_environment_variables() - ) - self._client_cert_source = MetricsServiceV2Client._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = get_universe_domain( - universe_domain_opt, - self._universe_domain_env, - default_universe=MetricsServiceV2Client._DEFAULT_UNIVERSE, - ) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() + self._client_cert_source = MetricsServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=MetricsServiceV2Client._DEFAULT_UNIVERSE) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -511,9 +436,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -522,41 +445,35 @@ def __init__( if transport_provided: # transport is a MetricsServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = cast(MetricsServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = self._api_endpoint or get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=MetricsServiceV2Client._DEFAULT_UNIVERSE, - default_mtls_endpoint=MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" - or (self._use_mtls_endpoint == "auto" and self._client_cert_source), - ) + self._api_endpoint = (self._api_endpoint or + get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=MetricsServiceV2Client._DEFAULT_UNIVERSE, + default_mtls_endpoint=MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" or ( + self._use_mtls_endpoint == "auto" and self._client_cert_source + ), + )) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[MetricsServiceV2Transport], - Callable[..., MetricsServiceV2Transport], - ] = ( + transport_init: Union[Type[MetricsServiceV2Transport], Callable[..., MetricsServiceV2Transport]] = ( MetricsServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., MetricsServiceV2Transport], transport) @@ -585,46 +502,33 @@ def __init__( "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **( - {"client_options": client_options} - if client_options is not None - else {} - ), + **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.MetricsServiceV2Client`.", - extra={ + extra = { "serviceName": "google.logging.v2.MetricsServiceV2", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.logging.v2.MetricsServiceV2", "credentialsType": None, - }, + } ) - def list_log_metrics( - self, - request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogMetricsPager: + def list_log_metrics(self, + request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogMetricsPager: r"""Lists logs-based metrics. .. code-block:: python @@ -689,14 +593,10 @@ def sample_list_log_metrics(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -714,7 +614,9 @@ def sample_list_log_metrics(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -742,15 +644,14 @@ def sample_list_log_metrics(): # Done; return the response. return response - def get_log_metric( - self, - request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def get_log_metric(self, + request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Gets a logs-based metric. .. code-block:: python @@ -820,14 +721,10 @@ def sample_get_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -845,9 +742,9 @@ def sample_get_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("metric_name", request.metric_name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("metric_name", request.metric_name), + )), ) # Validate the universe domain. @@ -864,16 +761,15 @@ def sample_get_log_metric(): # Done; return the response. return response - def create_log_metric( - self, - request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, - *, - parent: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def create_log_metric(self, + request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates a logs-based metric. .. code-block:: python @@ -959,14 +855,10 @@ def sample_create_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, metric] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -986,7 +878,9 @@ def sample_create_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1003,16 +897,15 @@ def sample_create_log_metric(): # Done; return the response. return response - def update_log_metric( - self, - request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def update_log_metric(self, + request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates or updates a logs-based metric. .. code-block:: python @@ -1097,14 +990,10 @@ def sample_update_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name, metric] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1124,9 +1013,9 @@ def sample_update_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("metric_name", request.metric_name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("metric_name", request.metric_name), + )), ) # Validate the universe domain. @@ -1143,15 +1032,14 @@ def sample_update_log_metric(): # Done; return the response. return response - def delete_log_metric( - self, - request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_log_metric(self, + request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a logs-based metric. .. code-block:: python @@ -1202,14 +1090,10 @@ def sample_delete_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1227,9 +1111,9 @@ def sample_delete_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("metric_name", request.metric_name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("metric_name", request.metric_name), + )), ) # Validate the universe domain. @@ -1298,7 +1182,8 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1307,11 +1192,7 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1361,7 +1242,8 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1370,11 +1252,7 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1427,24 +1305,25 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("MetricsServiceV2Client",) +__all__ = ( + "MetricsServiceV2Client", +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index 5e8c203f0a9f..362c7a9f93e5 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -17,23 +17,23 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import google.api_core +from google.cloud.logging_v2 import gapic_version as package_version + import google.auth # type: ignore -import google.protobuf -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.api_core from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.cloud.logging_v2 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore +import google.protobuf + from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ # Check once at module load time whether google-api-core's wrap_method supports @@ -48,29 +48,28 @@ class MetricsServiceV2Transport(abc.ABC): """Abstract transport class for MetricsServiceV2.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-platform.read-only", - "https://www.googleapis.com/auth/logging.admin", - "https://www.googleapis.com/auth/logging.read", - "https://www.googleapis.com/auth/logging.write", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + 'https://www.googleapis.com/auth/logging.admin', + 'https://www.googleapis.com/auth/logging.read', + 'https://www.googleapis.com/auth/logging.write', ) - DEFAULT_HOST: str = "logging.googleapis.com" + DEFAULT_HOST: str = 'logging.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -112,43 +111,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host self._client_options = client_options @@ -175,12 +162,7 @@ def _wrap_method(self, func, *args, **kwargs): # of google-api-core is installed (which does not accept client_options, etc.). # Excluded from coverage because our CI and testing environments always install # a modern version of google-api-core that supports tracing. - for k in [ - "client_options", - "method_name", - "is_streaming", - "kind", - ]: # pragma: NO COVER + for k in ["client_options", "method_name", "is_streaming", "kind"]: # pragma: NO COVER kwargs.pop(k, None) # pragma: NO COVER return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER @@ -276,63 +258,60 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def list_log_metrics( - self, - ) -> Callable[ - [logging_metrics.ListLogMetricsRequest], - Union[ - logging_metrics.ListLogMetricsResponse, - Awaitable[logging_metrics.ListLogMetricsResponse], - ], - ]: + def list_log_metrics(self) -> Callable[ + [logging_metrics.ListLogMetricsRequest], + Union[ + logging_metrics.ListLogMetricsResponse, + Awaitable[logging_metrics.ListLogMetricsResponse] + ]]: raise NotImplementedError() @property - def get_log_metric( - self, - ) -> Callable[ - [logging_metrics.GetLogMetricRequest], - Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], - ]: + def get_log_metric(self) -> Callable[ + [logging_metrics.GetLogMetricRequest], + Union[ + logging_metrics.LogMetric, + Awaitable[logging_metrics.LogMetric] + ]]: raise NotImplementedError() @property - def create_log_metric( - self, - ) -> Callable[ - [logging_metrics.CreateLogMetricRequest], - Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], - ]: + def create_log_metric(self) -> Callable[ + [logging_metrics.CreateLogMetricRequest], + Union[ + logging_metrics.LogMetric, + Awaitable[logging_metrics.LogMetric] + ]]: raise NotImplementedError() @property - def update_log_metric( - self, - ) -> Callable[ - [logging_metrics.UpdateLogMetricRequest], - Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], - ]: + def update_log_metric(self) -> Callable[ + [logging_metrics.UpdateLogMetricRequest], + Union[ + logging_metrics.LogMetric, + Awaitable[logging_metrics.LogMetric] + ]]: raise NotImplementedError() @property - def delete_log_metric( - self, - ) -> Callable[ - [logging_metrics.DeleteLogMetricRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_log_metric(self) -> Callable[ + [logging_metrics.DeleteLogMetricRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property @@ -340,10 +319,7 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[ - operations_pb2.ListOperationsResponse, - Awaitable[operations_pb2.ListOperationsResponse], - ], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], ]: raise NotImplementedError() @@ -370,4 +346,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("MetricsServiceV2Transport",) +__all__ = ( + 'MetricsServiceV2Transport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index 8b3f065959fb..a92efdd6ab6c 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -17,19 +17,16 @@ import logging as std_logging import pickle import warnings -from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ( - ClientInterceptor, # type: ignore[attr-defined] - ) + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 - # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -37,21 +34,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -import google.protobuf.message -import proto # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import proto # type: ignore -from .base import DEFAULT_CLIENT_INFO, MetricsServiceV2Transport +from google.cloud.logging_v2.types import logging_metrics +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from .base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -61,9 +58,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -84,7 +79,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.logging.v2.MetricsServiceV2", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -95,11 +90,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -114,7 +105,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.logging.v2.MetricsServiceV2", "rpcName": client_call_details.method, "response": grpc_response, @@ -136,35 +127,32 @@ class MetricsServiceV2GrpcTransport(MetricsServiceV2Transport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "logging.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], + def __init__(self, *, + host: str = 'logging.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], + ] ] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -300,17 +288,9 @@ def __init__( channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) - ) - is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None and otel_interceptor not in channel_interceptors - and not any( - getattr(i, "_is_otel_interceptor", None) is True - for i in channel_interceptors - ) + and not any(getattr(i, "_is_otel_interceptor", None) is True for i in channel_interceptors) ): channel_interceptors.append(otel_interceptor) @@ -319,28 +299,22 @@ def __init__( "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors( - self._grpc_channel, channel_interceptors - ) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "logging.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'logging.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -376,20 +350,19 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property - def list_log_metrics( - self, - ) -> Callable[ - [logging_metrics.ListLogMetricsRequest], logging_metrics.ListLogMetricsResponse - ]: + def list_log_metrics(self) -> Callable[ + [logging_metrics.ListLogMetricsRequest], + logging_metrics.ListLogMetricsResponse]: r"""Return a callable for the list log metrics method over gRPC. Lists logs-based metrics. @@ -404,18 +377,18 @@ def list_log_metrics( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_log_metrics" not in self._stubs: - self._stubs["list_log_metrics"] = self._logged_channel.unary_unary( - "/google.logging.v2.MetricsServiceV2/ListLogMetrics", + if 'list_log_metrics' not in self._stubs: + self._stubs['list_log_metrics'] = self._logged_channel.unary_unary( + '/google.logging.v2.MetricsServiceV2/ListLogMetrics', request_serializer=logging_metrics.ListLogMetricsRequest.serialize, response_deserializer=logging_metrics.ListLogMetricsResponse.deserialize, ) - return self._stubs["list_log_metrics"] + return self._stubs['list_log_metrics'] @property - def get_log_metric( - self, - ) -> Callable[[logging_metrics.GetLogMetricRequest], logging_metrics.LogMetric]: + def get_log_metric(self) -> Callable[ + [logging_metrics.GetLogMetricRequest], + logging_metrics.LogMetric]: r"""Return a callable for the get log metric method over gRPC. Gets a logs-based metric. @@ -430,18 +403,18 @@ def get_log_metric( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_log_metric" not in self._stubs: - self._stubs["get_log_metric"] = self._logged_channel.unary_unary( - "/google.logging.v2.MetricsServiceV2/GetLogMetric", + if 'get_log_metric' not in self._stubs: + self._stubs['get_log_metric'] = self._logged_channel.unary_unary( + '/google.logging.v2.MetricsServiceV2/GetLogMetric', request_serializer=logging_metrics.GetLogMetricRequest.serialize, response_deserializer=logging_metrics.LogMetric.deserialize, ) - return self._stubs["get_log_metric"] + return self._stubs['get_log_metric'] @property - def create_log_metric( - self, - ) -> Callable[[logging_metrics.CreateLogMetricRequest], logging_metrics.LogMetric]: + def create_log_metric(self) -> Callable[ + [logging_metrics.CreateLogMetricRequest], + logging_metrics.LogMetric]: r"""Return a callable for the create log metric method over gRPC. Creates a logs-based metric. @@ -456,18 +429,18 @@ def create_log_metric( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_log_metric" not in self._stubs: - self._stubs["create_log_metric"] = self._logged_channel.unary_unary( - "/google.logging.v2.MetricsServiceV2/CreateLogMetric", + if 'create_log_metric' not in self._stubs: + self._stubs['create_log_metric'] = self._logged_channel.unary_unary( + '/google.logging.v2.MetricsServiceV2/CreateLogMetric', request_serializer=logging_metrics.CreateLogMetricRequest.serialize, response_deserializer=logging_metrics.LogMetric.deserialize, ) - return self._stubs["create_log_metric"] + return self._stubs['create_log_metric'] @property - def update_log_metric( - self, - ) -> Callable[[logging_metrics.UpdateLogMetricRequest], logging_metrics.LogMetric]: + def update_log_metric(self) -> Callable[ + [logging_metrics.UpdateLogMetricRequest], + logging_metrics.LogMetric]: r"""Return a callable for the update log metric method over gRPC. Creates or updates a logs-based metric. @@ -482,18 +455,18 @@ def update_log_metric( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_log_metric" not in self._stubs: - self._stubs["update_log_metric"] = self._logged_channel.unary_unary( - "/google.logging.v2.MetricsServiceV2/UpdateLogMetric", + if 'update_log_metric' not in self._stubs: + self._stubs['update_log_metric'] = self._logged_channel.unary_unary( + '/google.logging.v2.MetricsServiceV2/UpdateLogMetric', request_serializer=logging_metrics.UpdateLogMetricRequest.serialize, response_deserializer=logging_metrics.LogMetric.deserialize, ) - return self._stubs["update_log_metric"] + return self._stubs['update_log_metric'] @property - def delete_log_metric( - self, - ) -> Callable[[logging_metrics.DeleteLogMetricRequest], empty_pb2.Empty]: + def delete_log_metric(self) -> Callable[ + [logging_metrics.DeleteLogMetricRequest], + empty_pb2.Empty]: r"""Return a callable for the delete log metric method over gRPC. Deletes a logs-based metric. @@ -508,13 +481,13 @@ def delete_log_metric( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_log_metric" not in self._stubs: - self._stubs["delete_log_metric"] = self._logged_channel.unary_unary( - "/google.logging.v2.MetricsServiceV2/DeleteLogMetric", + if 'delete_log_metric' not in self._stubs: + self._stubs['delete_log_metric'] = self._logged_channel.unary_unary( + '/google.logging.v2.MetricsServiceV2/DeleteLogMetric', request_serializer=logging_metrics.DeleteLogMetricRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_log_metric"] + return self._stubs['delete_log_metric'] def close(self): self._logged_channel.close() @@ -523,7 +496,8 @@ def close(self): def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC.""" + r"""Return a callable for the cancel_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -540,7 +514,8 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -556,10 +531,9 @@ def get_operation( @property def list_operations( self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse - ]: - r"""Return a callable for the list_operations method over gRPC.""" + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -577,4 +551,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("MetricsServiceV2GrpcTransport",) +__all__ = ( + 'MetricsServiceV2GrpcTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py index a9b4f7214230..0d26bf0e3fbd 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py @@ -13,46 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import inspect import json import logging as std_logging import os import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings -from collections import OrderedDict -from http import HTTPStatus -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import google.protobuf +from google.cloud.logging_v2 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.logging_v2 import gapic_version as package_version -from google.cloud.logging_v2._compat import ( - get_api_endpoint, - get_default_mtls_endpoint, - get_universe_domain, - read_environment_variables, - should_use_client_cert, -) -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -61,7 +44,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -75,16 +57,15 @@ _LOGGER = std_logging.getLogger(__name__) +from google.cloud.logging_v2.services.config_service_v2 import pagers +from google.cloud.logging_v2.types import logging_config +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from google.cloud.logging_v2.services.config_service_v2 import pagers -from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore - -from .transports.base import DEFAULT_CLIENT_INFO, ConfigServiceV2Transport +from .transports.base import ConfigServiceV2Transport, DEFAULT_CLIENT_INFO from .transports.grpc import ConfigServiceV2GrpcTransport from .transports.grpc_asyncio import ConfigServiceV2GrpcAsyncIOTransport @@ -96,15 +77,13 @@ class BaseConfigServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[ConfigServiceV2Transport]] _transport_registry["grpc"] = ConfigServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = ConfigServiceV2GrpcAsyncIOTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[ConfigServiceV2Transport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ConfigServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -164,7 +143,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BaseConfigServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -181,220 +161,139 @@ def transport(self) -> ConfigServiceV2Transport: return self._transport @staticmethod - def cmek_settings_path( - project: str, - ) -> str: + def cmek_settings_path(project: str,) -> str: """Returns a fully-qualified cmek_settings string.""" - return "projects/{project}/cmekSettings".format( - project=project, - ) + return "projects/{project}/cmekSettings".format(project=project, ) @staticmethod - def parse_cmek_settings_path(path: str) -> Dict[str, str]: + def parse_cmek_settings_path(path: str) -> Dict[str,str]: """Parses a cmek_settings path into its component segments.""" m = re.match(r"^projects/(?P.+?)/cmekSettings$", path) return m.groupdict() if m else {} @staticmethod - def link_path( - project: str, - location: str, - bucket: str, - link: str, - ) -> str: + def link_path(project: str,location: str,bucket: str,link: str,) -> str: """Returns a fully-qualified link string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format( - project=project, - location=location, - bucket=bucket, - link=link, - ) + return "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format(project=project, location=location, bucket=bucket, link=link, ) @staticmethod - def parse_link_path(path: str) -> Dict[str, str]: + def parse_link_path(path: str) -> Dict[str,str]: """Parses a link path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/links/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/links/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_bucket_path( - project: str, - location: str, - bucket: str, - ) -> str: + def log_bucket_path(project: str,location: str,bucket: str,) -> str: """Returns a fully-qualified log_bucket string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}".format( - project=project, - location=location, - bucket=bucket, - ) + return "projects/{project}/locations/{location}/buckets/{bucket}".format(project=project, location=location, bucket=bucket, ) @staticmethod - def parse_log_bucket_path(path: str) -> Dict[str, str]: + def parse_log_bucket_path(path: str) -> Dict[str,str]: """Parses a log_bucket path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_exclusion_path( - project: str, - exclusion: str, - ) -> str: + def log_exclusion_path(project: str,exclusion: str,) -> str: """Returns a fully-qualified log_exclusion string.""" - return "projects/{project}/exclusions/{exclusion}".format( - project=project, - exclusion=exclusion, - ) + return "projects/{project}/exclusions/{exclusion}".format(project=project, exclusion=exclusion, ) @staticmethod - def parse_log_exclusion_path(path: str) -> Dict[str, str]: + def parse_log_exclusion_path(path: str) -> Dict[str,str]: """Parses a log_exclusion path into its component segments.""" m = re.match(r"^projects/(?P.+?)/exclusions/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_sink_path( - project: str, - sink: str, - ) -> str: + def log_sink_path(project: str,sink: str,) -> str: """Returns a fully-qualified log_sink string.""" - return "projects/{project}/sinks/{sink}".format( - project=project, - sink=sink, - ) + return "projects/{project}/sinks/{sink}".format(project=project, sink=sink, ) @staticmethod - def parse_log_sink_path(path: str) -> Dict[str, str]: + def parse_log_sink_path(path: str) -> Dict[str,str]: """Parses a log_sink path into its component segments.""" m = re.match(r"^projects/(?P.+?)/sinks/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_view_path( - project: str, - location: str, - bucket: str, - view: str, - ) -> str: + def log_view_path(project: str,location: str,bucket: str,view: str,) -> str: """Returns a fully-qualified log_view string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format( - project=project, - location=location, - bucket=bucket, - view=view, - ) + return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format(project=project, location=location, bucket=bucket, view=view, ) @staticmethod - def parse_log_view_path(path: str) -> Dict[str, str]: + def parse_log_view_path(path: str) -> Dict[str,str]: """Parses a log_view path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def settings_path( - project: str, - ) -> str: + def settings_path(project: str,) -> str: """Returns a fully-qualified settings string.""" - return "projects/{project}/settings".format( - project=project, - ) + return "projects/{project}/settings".format(project=project, ) @staticmethod - def parse_settings_path(path: str) -> Dict[str, str]: + def parse_settings_path(path: str) -> Dict[str,str]: """Parses a settings path into its component segments.""" m = re.match(r"^projects/(?P.+?)/settings$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -426,18 +325,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -450,10 +345,8 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -492,18 +385,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -536,18 +426,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[ - str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the base config service v2 client. Args: @@ -602,23 +486,13 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - read_environment_variables() - ) - self._client_cert_source = BaseConfigServiceV2Client._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = get_universe_domain( - universe_domain_opt, - self._universe_domain_env, - default_universe=BaseConfigServiceV2Client._DEFAULT_UNIVERSE, - ) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() + self._client_cert_source = BaseConfigServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=BaseConfigServiceV2Client._DEFAULT_UNIVERSE) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -630,9 +504,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -641,40 +513,35 @@ def __init__( if transport_provided: # transport is a ConfigServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = cast(ConfigServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = self._api_endpoint or get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=BaseConfigServiceV2Client._DEFAULT_UNIVERSE, - default_mtls_endpoint=BaseConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=BaseConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" - or (self._use_mtls_endpoint == "auto" and self._client_cert_source), - ) + self._api_endpoint = (self._api_endpoint or + get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=BaseConfigServiceV2Client._DEFAULT_UNIVERSE, + default_mtls_endpoint=BaseConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=BaseConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" or ( + self._use_mtls_endpoint == "auto" and self._client_cert_source + ), + )) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[ConfigServiceV2Transport], Callable[..., ConfigServiceV2Transport] - ] = ( + transport_init: Union[Type[ConfigServiceV2Transport], Callable[..., ConfigServiceV2Transport]] = ( BaseConfigServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ConfigServiceV2Transport], transport) @@ -703,46 +570,33 @@ def __init__( "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **( - {"client_options": client_options} - if client_options is not None - else {} - ), + **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.BaseConfigServiceV2Client`.", - extra={ + extra = { "serviceName": "google.logging.v2.ConfigServiceV2", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.logging.v2.ConfigServiceV2", "credentialsType": None, - }, + } ) - def list_buckets( - self, - request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBucketsPager: + def list_buckets(self, + request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketsPager: r"""Lists log buckets. .. code-block:: python @@ -814,14 +668,10 @@ def sample_list_buckets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -839,7 +689,9 @@ def sample_list_buckets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -867,14 +719,13 @@ def sample_list_buckets(): # Done; return the response. return response - def get_bucket( - self, - request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def get_bucket(self, + request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Gets a log bucket. .. code-block:: python @@ -933,7 +784,9 @@ def sample_get_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -950,14 +803,13 @@ def sample_get_bucket(): # Done; return the response. return response - def create_bucket_async( - self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_bucket_async(self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a log bucket asynchronously that can be used to store log entries. After a bucket has been created, the bucket's location @@ -1027,7 +879,9 @@ def sample_create_bucket_async(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1052,14 +906,13 @@ def sample_create_bucket_async(): # Done; return the response. return response - def update_bucket_async( - self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_bucket_async(self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates a log bucket asynchronously. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -1131,7 +984,9 @@ def sample_update_bucket_async(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1156,14 +1011,13 @@ def sample_update_bucket_async(): # Done; return the response. return response - def create_bucket( - self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def create_bucket(self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Creates a log bucket that can be used to store log entries. After a bucket has been created, the bucket's location cannot be changed. @@ -1225,7 +1079,9 @@ def sample_create_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1242,14 +1098,13 @@ def sample_create_bucket(): # Done; return the response. return response - def update_bucket( - self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def update_bucket(self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Updates a log bucket. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -1314,7 +1169,9 @@ def sample_update_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1331,14 +1188,13 @@ def sample_update_bucket(): # Done; return the response. return response - def delete_bucket( - self, - request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_bucket(self, + request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a log bucket. Changes the bucket's ``lifecycle_state`` to the @@ -1393,7 +1249,9 @@ def sample_delete_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1407,14 +1265,13 @@ def sample_delete_bucket(): metadata=metadata, ) - def undelete_bucket( - self, - request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def undelete_bucket(self, + request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Undeletes a log bucket. A bucket that has been deleted can be undeleted within the grace period of 7 days. @@ -1466,7 +1323,9 @@ def sample_undelete_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1480,15 +1339,14 @@ def sample_undelete_bucket(): metadata=metadata, ) - def _list_views( - self, - request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListViewsPager: + def _list_views(self, + request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListViewsPager: r"""Lists views on a log bucket. .. code-block:: python @@ -1552,14 +1410,10 @@ def sample_list_views(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1577,7 +1431,9 @@ def sample_list_views(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1605,14 +1461,13 @@ def sample_list_views(): # Done; return the response. return response - def _get_view( - self, - request: Optional[Union[logging_config.GetViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def _get_view(self, + request: Optional[Union[logging_config.GetViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Gets a view on a log bucket.. .. code-block:: python @@ -1671,7 +1526,9 @@ def sample_get_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1688,14 +1545,13 @@ def sample_get_view(): # Done; return the response. return response - def _create_view( - self, - request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def _create_view(self, + request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Creates a view over log entries in a log bucket. A bucket may contain a maximum of 30 views. @@ -1756,7 +1612,9 @@ def sample_create_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1773,14 +1631,13 @@ def sample_create_view(): # Done; return the response. return response - def _update_view( - self, - request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def _update_view(self, + request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Updates a view on a log bucket. This method replaces the following fields in the existing view with values from the new view: ``filter``. If an ``UNAVAILABLE`` error is returned, this @@ -1843,7 +1700,9 @@ def sample_update_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1860,14 +1719,13 @@ def sample_update_view(): # Done; return the response. return response - def _delete_view( - self, - request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def _delete_view(self, + request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is returned, this indicates that system is not in a state where it can delete the view. If this occurs, please try again in a few @@ -1920,7 +1778,9 @@ def sample_delete_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1934,15 +1794,14 @@ def sample_delete_view(): metadata=metadata, ) - def _list_sinks( - self, - request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListSinksPager: + def _list_sinks(self, + request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSinksPager: r"""Lists sinks. .. code-block:: python @@ -2009,14 +1868,10 @@ def sample_list_sinks(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2034,7 +1889,9 @@ def sample_list_sinks(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2062,15 +1919,14 @@ def sample_list_sinks(): # Done; return the response. return response - def _get_sink( - self, - request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def _get_sink(self, + request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Gets a sink. .. code-block:: python @@ -2144,14 +2000,10 @@ def sample_get_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2169,9 +2021,9 @@ def sample_get_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("sink_name", request.sink_name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("sink_name", request.sink_name), + )), ) # Validate the universe domain. @@ -2188,16 +2040,15 @@ def sample_get_sink(): # Done; return the response. return response - def _create_sink( - self, - request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def _create_sink(self, + request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not @@ -2287,14 +2138,10 @@ def sample_create_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, sink] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2314,7 +2161,9 @@ def sample_create_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2331,17 +2180,16 @@ def sample_create_sink(): # Done; return the response. return response - def _update_sink( - self, - request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def _update_sink(self, + request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: ``destination``, and ``filter``. @@ -2455,14 +2303,10 @@ def sample_update_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name, sink, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2484,9 +2328,9 @@ def sample_update_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("sink_name", request.sink_name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("sink_name", request.sink_name), + )), ) # Validate the universe domain. @@ -2503,15 +2347,14 @@ def sample_update_sink(): # Done; return the response. return response - def _delete_sink( - self, - request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def _delete_sink(self, + request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a sink. If the sink has a unique ``writer_identity``, then that service account is also deleted. @@ -2571,14 +2414,10 @@ def sample_delete_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2596,9 +2435,9 @@ def sample_delete_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("sink_name", request.sink_name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("sink_name", request.sink_name), + )), ) # Validate the universe domain. @@ -2612,17 +2451,16 @@ def sample_delete_sink(): metadata=metadata, ) - def _create_link( - self, - request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - link: Optional[logging_config.Link] = None, - link_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def _create_link(self, + request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + link: Optional[logging_config.Link] = None, + link_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Asynchronously creates a linked dataset in BigQuery which makes it possible to use BigQuery to read the logs stored in the log bucket. A log bucket may currently @@ -2710,14 +2548,10 @@ def sample_create_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, link, link_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2739,7 +2573,9 @@ def sample_create_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2764,15 +2600,14 @@ def sample_create_link(): # Done; return the response. return response - def _delete_link( - self, - request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def _delete_link(self, + request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes a link. This will also delete the corresponding BigQuery linked dataset. @@ -2848,14 +2683,10 @@ def sample_delete_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2873,7 +2704,9 @@ def sample_delete_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2898,15 +2731,14 @@ def sample_delete_link(): # Done; return the response. return response - def _list_links( - self, - request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLinksPager: + def _list_links(self, + request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLinksPager: r"""Lists links. .. code-block:: python @@ -2972,14 +2804,10 @@ def sample_list_links(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2997,7 +2825,9 @@ def sample_list_links(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3025,15 +2855,14 @@ def sample_list_links(): # Done; return the response. return response - def _get_link( - self, - request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Link: + def _get_link(self, + request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Link: r"""Gets a link. .. code-block:: python @@ -3094,14 +2923,10 @@ def sample_get_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3119,7 +2944,9 @@ def sample_get_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3136,15 +2963,14 @@ def sample_get_link(): # Done; return the response. return response - def _list_exclusions( - self, - request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListExclusionsPager: + def _list_exclusions(self, + request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExclusionsPager: r"""Lists all the exclusions on the \_Default sink in a parent resource. @@ -3212,14 +3038,10 @@ def sample_list_exclusions(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3237,7 +3059,9 @@ def sample_list_exclusions(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3265,15 +3089,14 @@ def sample_list_exclusions(): # Done; return the response. return response - def _get_exclusion( - self, - request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def _get_exclusion(self, + request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Gets the description of an exclusion in the \_Default sink. .. code-block:: python @@ -3345,14 +3168,10 @@ def sample_get_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3370,7 +3189,9 @@ def sample_get_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3387,16 +3208,15 @@ def sample_get_exclusion(): # Done; return the response. return response - def _create_exclusion( - self, - request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, - *, - parent: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def _create_exclusion(self, + request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, + *, + parent: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Creates a new exclusion in the \_Default sink in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. @@ -3485,14 +3305,10 @@ def sample_create_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, exclusion] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3512,7 +3328,9 @@ def sample_create_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3529,17 +3347,16 @@ def sample_create_exclusion(): # Done; return the response. return response - def _update_exclusion( - self, - request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def _update_exclusion(self, + request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Changes one or more properties of an existing exclusion in the \_Default sink. @@ -3639,14 +3456,10 @@ def sample_update_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, exclusion, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3668,7 +3481,9 @@ def sample_update_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3685,15 +3500,14 @@ def sample_update_exclusion(): # Done; return the response. return response - def _delete_exclusion( - self, - request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def _delete_exclusion(self, + request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes an exclusion in the \_Default sink. .. code-block:: python @@ -3752,14 +3566,10 @@ def sample_delete_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3777,7 +3587,9 @@ def sample_delete_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3791,14 +3603,13 @@ def sample_delete_exclusion(): metadata=metadata, ) - def _get_cmek_settings( - self, - request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + def _get_cmek_settings(self, + request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Gets the Logging CMEK settings for the given resource. Note: CMEK for the Log Router can be configured for Google Cloud @@ -3881,7 +3692,9 @@ def sample_get_cmek_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -3898,14 +3711,13 @@ def sample_get_cmek_settings(): # Done; return the response. return response - def _update_cmek_settings( - self, - request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + def _update_cmek_settings(self, + request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Updates the Log Router CMEK settings for the given resource. Note: CMEK for the Log Router can currently only be configured @@ -3993,7 +3805,9 @@ def sample_update_cmek_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -4010,15 +3824,14 @@ def sample_update_cmek_settings(): # Done; return the response. return response - def _get_settings( - self, - request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + def _get_settings(self, + request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Gets the Log Router settings for the given resource. Note: Settings for the Log Router can be get for Google Cloud @@ -4108,14 +3921,10 @@ def sample_get_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4133,7 +3942,9 @@ def sample_get_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -4150,16 +3961,15 @@ def sample_get_settings(): # Done; return the response. return response - def _update_settings( - self, - request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, - *, - settings: Optional[logging_config.Settings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + def _update_settings(self, + request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, + *, + settings: Optional[logging_config.Settings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Updates the Log Router settings for the given resource. Note: Settings for the Log Router can currently only be @@ -4256,14 +4066,10 @@ def sample_update_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [settings, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4283,7 +4089,9 @@ def sample_update_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -4300,14 +4108,13 @@ def sample_update_settings(): # Done; return the response. return response - def _copy_log_entries( - self, - request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def _copy_log_entries(self, + request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Copies a set of log entries from a log bucket to a Cloud Storage bucket. @@ -4450,7 +4257,8 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -4459,11 +4267,7 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -4513,7 +4317,8 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -4522,11 +4327,7 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -4579,24 +4380,25 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("BaseConfigServiceV2Client",) +__all__ = ( + "BaseConfigServiceV2Client", +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py index 97dbac19187d..89638bbf0c72 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -17,23 +17,24 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import google.api_core +from google.cloud.logging_v2 import gapic_version as package_version + import google.auth # type: ignore -import google.protobuf -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.api_core from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.cloud.logging_v2 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore +import google.protobuf + from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ # Check once at module load time whether google-api-core's wrap_method supports @@ -48,28 +49,27 @@ class ConfigServiceV2Transport(abc.ABC): """Abstract transport class for ConfigServiceV2.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-platform.read-only", - "https://www.googleapis.com/auth/logging.admin", - "https://www.googleapis.com/auth/logging.read", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + 'https://www.googleapis.com/auth/logging.admin', + 'https://www.googleapis.com/auth/logging.read', ) - DEFAULT_HOST: str = "logging.googleapis.com" + DEFAULT_HOST: str = 'logging.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -111,43 +111,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host self._client_options = client_options @@ -174,12 +162,7 @@ def _wrap_method(self, func, *args, **kwargs): # of google-api-core is installed (which does not accept client_options, etc.). # Excluded from coverage because our CI and testing environments always install # a modern version of google-api-core that supports tracing. - for k in [ - "client_options", - "method_name", - "is_streaming", - "kind", - ]: # pragma: NO COVER + for k in ["client_options", "method_name", "is_streaming", "kind"]: # pragma: NO COVER kwargs.pop(k, None) # pragma: NO COVER return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER @@ -470,14 +453,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -487,306 +470,291 @@ def operations_client(self): raise NotImplementedError() @property - def list_buckets( - self, - ) -> Callable[ - [logging_config.ListBucketsRequest], - Union[ - logging_config.ListBucketsResponse, - Awaitable[logging_config.ListBucketsResponse], - ], - ]: + def list_buckets(self) -> Callable[ + [logging_config.ListBucketsRequest], + Union[ + logging_config.ListBucketsResponse, + Awaitable[logging_config.ListBucketsResponse] + ]]: raise NotImplementedError() @property - def get_bucket( - self, - ) -> Callable[ - [logging_config.GetBucketRequest], - Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], - ]: + def get_bucket(self) -> Callable[ + [logging_config.GetBucketRequest], + Union[ + logging_config.LogBucket, + Awaitable[logging_config.LogBucket] + ]]: raise NotImplementedError() @property - def create_bucket_async( - self, - ) -> Callable[ - [logging_config.CreateBucketRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_bucket_async(self) -> Callable[ + [logging_config.CreateBucketRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def update_bucket_async( - self, - ) -> Callable[ - [logging_config.UpdateBucketRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def update_bucket_async(self) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def create_bucket( - self, - ) -> Callable[ - [logging_config.CreateBucketRequest], - Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], - ]: + def create_bucket(self) -> Callable[ + [logging_config.CreateBucketRequest], + Union[ + logging_config.LogBucket, + Awaitable[logging_config.LogBucket] + ]]: raise NotImplementedError() @property - def update_bucket( - self, - ) -> Callable[ - [logging_config.UpdateBucketRequest], - Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], - ]: + def update_bucket(self) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[ + logging_config.LogBucket, + Awaitable[logging_config.LogBucket] + ]]: raise NotImplementedError() @property - def delete_bucket( - self, - ) -> Callable[ - [logging_config.DeleteBucketRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_bucket(self) -> Callable[ + [logging_config.DeleteBucketRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def undelete_bucket( - self, - ) -> Callable[ - [logging_config.UndeleteBucketRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def undelete_bucket(self) -> Callable[ + [logging_config.UndeleteBucketRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def list_views( - self, - ) -> Callable[ - [logging_config.ListViewsRequest], - Union[ - logging_config.ListViewsResponse, - Awaitable[logging_config.ListViewsResponse], - ], - ]: + def list_views(self) -> Callable[ + [logging_config.ListViewsRequest], + Union[ + logging_config.ListViewsResponse, + Awaitable[logging_config.ListViewsResponse] + ]]: raise NotImplementedError() @property - def get_view( - self, - ) -> Callable[ - [logging_config.GetViewRequest], - Union[logging_config.LogView, Awaitable[logging_config.LogView]], - ]: + def get_view(self) -> Callable[ + [logging_config.GetViewRequest], + Union[ + logging_config.LogView, + Awaitable[logging_config.LogView] + ]]: raise NotImplementedError() @property - def create_view( - self, - ) -> Callable[ - [logging_config.CreateViewRequest], - Union[logging_config.LogView, Awaitable[logging_config.LogView]], - ]: + def create_view(self) -> Callable[ + [logging_config.CreateViewRequest], + Union[ + logging_config.LogView, + Awaitable[logging_config.LogView] + ]]: raise NotImplementedError() @property - def update_view( - self, - ) -> Callable[ - [logging_config.UpdateViewRequest], - Union[logging_config.LogView, Awaitable[logging_config.LogView]], - ]: + def update_view(self) -> Callable[ + [logging_config.UpdateViewRequest], + Union[ + logging_config.LogView, + Awaitable[logging_config.LogView] + ]]: raise NotImplementedError() @property - def delete_view( - self, - ) -> Callable[ - [logging_config.DeleteViewRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_view(self) -> Callable[ + [logging_config.DeleteViewRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def list_sinks( - self, - ) -> Callable[ - [logging_config.ListSinksRequest], - Union[ - logging_config.ListSinksResponse, - Awaitable[logging_config.ListSinksResponse], - ], - ]: + def list_sinks(self) -> Callable[ + [logging_config.ListSinksRequest], + Union[ + logging_config.ListSinksResponse, + Awaitable[logging_config.ListSinksResponse] + ]]: raise NotImplementedError() @property - def get_sink( - self, - ) -> Callable[ - [logging_config.GetSinkRequest], - Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], - ]: + def get_sink(self) -> Callable[ + [logging_config.GetSinkRequest], + Union[ + logging_config.LogSink, + Awaitable[logging_config.LogSink] + ]]: raise NotImplementedError() @property - def create_sink( - self, - ) -> Callable[ - [logging_config.CreateSinkRequest], - Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], - ]: + def create_sink(self) -> Callable[ + [logging_config.CreateSinkRequest], + Union[ + logging_config.LogSink, + Awaitable[logging_config.LogSink] + ]]: raise NotImplementedError() @property - def update_sink( - self, - ) -> Callable[ - [logging_config.UpdateSinkRequest], - Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], - ]: + def update_sink(self) -> Callable[ + [logging_config.UpdateSinkRequest], + Union[ + logging_config.LogSink, + Awaitable[logging_config.LogSink] + ]]: raise NotImplementedError() @property - def delete_sink( - self, - ) -> Callable[ - [logging_config.DeleteSinkRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_sink(self) -> Callable[ + [logging_config.DeleteSinkRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def create_link( - self, - ) -> Callable[ - [logging_config.CreateLinkRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_link(self) -> Callable[ + [logging_config.CreateLinkRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def delete_link( - self, - ) -> Callable[ - [logging_config.DeleteLinkRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def delete_link(self) -> Callable[ + [logging_config.DeleteLinkRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def list_links( - self, - ) -> Callable[ - [logging_config.ListLinksRequest], - Union[ - logging_config.ListLinksResponse, - Awaitable[logging_config.ListLinksResponse], - ], - ]: + def list_links(self) -> Callable[ + [logging_config.ListLinksRequest], + Union[ + logging_config.ListLinksResponse, + Awaitable[logging_config.ListLinksResponse] + ]]: raise NotImplementedError() @property - def get_link( - self, - ) -> Callable[ - [logging_config.GetLinkRequest], - Union[logging_config.Link, Awaitable[logging_config.Link]], - ]: + def get_link(self) -> Callable[ + [logging_config.GetLinkRequest], + Union[ + logging_config.Link, + Awaitable[logging_config.Link] + ]]: raise NotImplementedError() @property - def list_exclusions( - self, - ) -> Callable[ - [logging_config.ListExclusionsRequest], - Union[ - logging_config.ListExclusionsResponse, - Awaitable[logging_config.ListExclusionsResponse], - ], - ]: + def list_exclusions(self) -> Callable[ + [logging_config.ListExclusionsRequest], + Union[ + logging_config.ListExclusionsResponse, + Awaitable[logging_config.ListExclusionsResponse] + ]]: raise NotImplementedError() @property - def get_exclusion( - self, - ) -> Callable[ - [logging_config.GetExclusionRequest], - Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], - ]: + def get_exclusion(self) -> Callable[ + [logging_config.GetExclusionRequest], + Union[ + logging_config.LogExclusion, + Awaitable[logging_config.LogExclusion] + ]]: raise NotImplementedError() @property - def create_exclusion( - self, - ) -> Callable[ - [logging_config.CreateExclusionRequest], - Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], - ]: + def create_exclusion(self) -> Callable[ + [logging_config.CreateExclusionRequest], + Union[ + logging_config.LogExclusion, + Awaitable[logging_config.LogExclusion] + ]]: raise NotImplementedError() @property - def update_exclusion( - self, - ) -> Callable[ - [logging_config.UpdateExclusionRequest], - Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], - ]: + def update_exclusion(self) -> Callable[ + [logging_config.UpdateExclusionRequest], + Union[ + logging_config.LogExclusion, + Awaitable[logging_config.LogExclusion] + ]]: raise NotImplementedError() @property - def delete_exclusion( - self, - ) -> Callable[ - [logging_config.DeleteExclusionRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_exclusion(self) -> Callable[ + [logging_config.DeleteExclusionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def get_cmek_settings( - self, - ) -> Callable[ - [logging_config.GetCmekSettingsRequest], - Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], - ]: + def get_cmek_settings(self) -> Callable[ + [logging_config.GetCmekSettingsRequest], + Union[ + logging_config.CmekSettings, + Awaitable[logging_config.CmekSettings] + ]]: raise NotImplementedError() @property - def update_cmek_settings( - self, - ) -> Callable[ - [logging_config.UpdateCmekSettingsRequest], - Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], - ]: + def update_cmek_settings(self) -> Callable[ + [logging_config.UpdateCmekSettingsRequest], + Union[ + logging_config.CmekSettings, + Awaitable[logging_config.CmekSettings] + ]]: raise NotImplementedError() @property - def get_settings( - self, - ) -> Callable[ - [logging_config.GetSettingsRequest], - Union[logging_config.Settings, Awaitable[logging_config.Settings]], - ]: + def get_settings(self) -> Callable[ + [logging_config.GetSettingsRequest], + Union[ + logging_config.Settings, + Awaitable[logging_config.Settings] + ]]: raise NotImplementedError() @property - def update_settings( - self, - ) -> Callable[ - [logging_config.UpdateSettingsRequest], - Union[logging_config.Settings, Awaitable[logging_config.Settings]], - ]: + def update_settings(self) -> Callable[ + [logging_config.UpdateSettingsRequest], + Union[ + logging_config.Settings, + Awaitable[logging_config.Settings] + ]]: raise NotImplementedError() @property - def copy_log_entries( - self, - ) -> Callable[ - [logging_config.CopyLogEntriesRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def copy_log_entries(self) -> Callable[ + [logging_config.CopyLogEntriesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property @@ -794,10 +762,7 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[ - operations_pb2.ListOperationsResponse, - Awaitable[operations_pb2.ListOperationsResponse], - ], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], ]: raise NotImplementedError() @@ -824,4 +789,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("ConfigServiceV2Transport",) +__all__ = ( + 'ConfigServiceV2Transport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index 0fd4a31ba7f8..164e83c216d9 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -17,19 +17,17 @@ import logging as std_logging import pickle import warnings -from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ( - ClientInterceptor, # type: ignore[attr-defined] - ) + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1, operations_v1 - +from google.api_core import gapic_v1 # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -37,21 +35,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -import google.protobuf.message -import proto # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import proto # type: ignore -from .base import DEFAULT_CLIENT_INFO, ConfigServiceV2Transport +from google.cloud.logging_v2.types import logging_config +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from .base import ConfigServiceV2Transport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -61,9 +59,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -84,7 +80,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.logging.v2.ConfigServiceV2", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -95,11 +91,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -114,7 +106,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.logging.v2.ConfigServiceV2", "rpcName": client_call_details.method, "response": grpc_response, @@ -136,35 +128,32 @@ class ConfigServiceV2GrpcTransport(ConfigServiceV2Transport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "logging.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], + def __init__(self, *, + host: str = 'logging.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], + ] ] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -301,17 +290,9 @@ def __init__( channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) - ) - is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None and otel_interceptor not in channel_interceptors - and not any( - getattr(i, "_is_otel_interceptor", None) is True - for i in channel_interceptors - ) + and not any(getattr(i, "_is_otel_interceptor", None) is True for i in channel_interceptors) ): channel_interceptors.append(otel_interceptor) @@ -320,28 +301,22 @@ def __init__( "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors( - self._grpc_channel, channel_interceptors - ) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "logging.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'logging.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -377,12 +352,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -402,11 +378,9 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def list_buckets( - self, - ) -> Callable[ - [logging_config.ListBucketsRequest], logging_config.ListBucketsResponse - ]: + def list_buckets(self) -> Callable[ + [logging_config.ListBucketsRequest], + logging_config.ListBucketsResponse]: r"""Return a callable for the list buckets method over gRPC. Lists log buckets. @@ -421,18 +395,18 @@ def list_buckets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_buckets" not in self._stubs: - self._stubs["list_buckets"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/ListBuckets", + if 'list_buckets' not in self._stubs: + self._stubs['list_buckets'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/ListBuckets', request_serializer=logging_config.ListBucketsRequest.serialize, response_deserializer=logging_config.ListBucketsResponse.deserialize, ) - return self._stubs["list_buckets"] + return self._stubs['list_buckets'] @property - def get_bucket( - self, - ) -> Callable[[logging_config.GetBucketRequest], logging_config.LogBucket]: + def get_bucket(self) -> Callable[ + [logging_config.GetBucketRequest], + logging_config.LogBucket]: r"""Return a callable for the get bucket method over gRPC. Gets a log bucket. @@ -447,18 +421,18 @@ def get_bucket( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_bucket" not in self._stubs: - self._stubs["get_bucket"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetBucket", + if 'get_bucket' not in self._stubs: + self._stubs['get_bucket'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetBucket', request_serializer=logging_config.GetBucketRequest.serialize, response_deserializer=logging_config.LogBucket.deserialize, ) - return self._stubs["get_bucket"] + return self._stubs['get_bucket'] @property - def create_bucket_async( - self, - ) -> Callable[[logging_config.CreateBucketRequest], operations_pb2.Operation]: + def create_bucket_async(self) -> Callable[ + [logging_config.CreateBucketRequest], + operations_pb2.Operation]: r"""Return a callable for the create bucket async method over gRPC. Creates a log bucket asynchronously that can be used @@ -476,18 +450,18 @@ def create_bucket_async( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_bucket_async" not in self._stubs: - self._stubs["create_bucket_async"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CreateBucketAsync", + if 'create_bucket_async' not in self._stubs: + self._stubs['create_bucket_async'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CreateBucketAsync', request_serializer=logging_config.CreateBucketRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_bucket_async"] + return self._stubs['create_bucket_async'] @property - def update_bucket_async( - self, - ) -> Callable[[logging_config.UpdateBucketRequest], operations_pb2.Operation]: + def update_bucket_async(self) -> Callable[ + [logging_config.UpdateBucketRequest], + operations_pb2.Operation]: r"""Return a callable for the update bucket async method over gRPC. Updates a log bucket asynchronously. @@ -508,18 +482,18 @@ def update_bucket_async( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_bucket_async" not in self._stubs: - self._stubs["update_bucket_async"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateBucketAsync", + if 'update_bucket_async' not in self._stubs: + self._stubs['update_bucket_async'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateBucketAsync', request_serializer=logging_config.UpdateBucketRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["update_bucket_async"] + return self._stubs['update_bucket_async'] @property - def create_bucket( - self, - ) -> Callable[[logging_config.CreateBucketRequest], logging_config.LogBucket]: + def create_bucket(self) -> Callable[ + [logging_config.CreateBucketRequest], + logging_config.LogBucket]: r"""Return a callable for the create bucket method over gRPC. Creates a log bucket that can be used to store log @@ -536,18 +510,18 @@ def create_bucket( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_bucket" not in self._stubs: - self._stubs["create_bucket"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CreateBucket", + if 'create_bucket' not in self._stubs: + self._stubs['create_bucket'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CreateBucket', request_serializer=logging_config.CreateBucketRequest.serialize, response_deserializer=logging_config.LogBucket.deserialize, ) - return self._stubs["create_bucket"] + return self._stubs['create_bucket'] @property - def update_bucket( - self, - ) -> Callable[[logging_config.UpdateBucketRequest], logging_config.LogBucket]: + def update_bucket(self) -> Callable[ + [logging_config.UpdateBucketRequest], + logging_config.LogBucket]: r"""Return a callable for the update bucket method over gRPC. Updates a log bucket. @@ -568,18 +542,18 @@ def update_bucket( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_bucket" not in self._stubs: - self._stubs["update_bucket"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateBucket", + if 'update_bucket' not in self._stubs: + self._stubs['update_bucket'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateBucket', request_serializer=logging_config.UpdateBucketRequest.serialize, response_deserializer=logging_config.LogBucket.deserialize, ) - return self._stubs["update_bucket"] + return self._stubs['update_bucket'] @property - def delete_bucket( - self, - ) -> Callable[[logging_config.DeleteBucketRequest], empty_pb2.Empty]: + def delete_bucket(self) -> Callable[ + [logging_config.DeleteBucketRequest], + empty_pb2.Empty]: r"""Return a callable for the delete bucket method over gRPC. Deletes a log bucket. @@ -599,18 +573,18 @@ def delete_bucket( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_bucket" not in self._stubs: - self._stubs["delete_bucket"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/DeleteBucket", + if 'delete_bucket' not in self._stubs: + self._stubs['delete_bucket'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/DeleteBucket', request_serializer=logging_config.DeleteBucketRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_bucket"] + return self._stubs['delete_bucket'] @property - def undelete_bucket( - self, - ) -> Callable[[logging_config.UndeleteBucketRequest], empty_pb2.Empty]: + def undelete_bucket(self) -> Callable[ + [logging_config.UndeleteBucketRequest], + empty_pb2.Empty]: r"""Return a callable for the undelete bucket method over gRPC. Undeletes a log bucket. A bucket that has been @@ -627,18 +601,18 @@ def undelete_bucket( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "undelete_bucket" not in self._stubs: - self._stubs["undelete_bucket"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UndeleteBucket", + if 'undelete_bucket' not in self._stubs: + self._stubs['undelete_bucket'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UndeleteBucket', request_serializer=logging_config.UndeleteBucketRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["undelete_bucket"] + return self._stubs['undelete_bucket'] @property - def list_views( - self, - ) -> Callable[[logging_config.ListViewsRequest], logging_config.ListViewsResponse]: + def list_views(self) -> Callable[ + [logging_config.ListViewsRequest], + logging_config.ListViewsResponse]: r"""Return a callable for the list views method over gRPC. Lists views on a log bucket. @@ -653,18 +627,18 @@ def list_views( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_views" not in self._stubs: - self._stubs["list_views"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/ListViews", + if 'list_views' not in self._stubs: + self._stubs['list_views'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/ListViews', request_serializer=logging_config.ListViewsRequest.serialize, response_deserializer=logging_config.ListViewsResponse.deserialize, ) - return self._stubs["list_views"] + return self._stubs['list_views'] @property - def get_view( - self, - ) -> Callable[[logging_config.GetViewRequest], logging_config.LogView]: + def get_view(self) -> Callable[ + [logging_config.GetViewRequest], + logging_config.LogView]: r"""Return a callable for the get view method over gRPC. Gets a view on a log bucket.. @@ -679,18 +653,18 @@ def get_view( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_view" not in self._stubs: - self._stubs["get_view"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetView", + if 'get_view' not in self._stubs: + self._stubs['get_view'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetView', request_serializer=logging_config.GetViewRequest.serialize, response_deserializer=logging_config.LogView.deserialize, ) - return self._stubs["get_view"] + return self._stubs['get_view'] @property - def create_view( - self, - ) -> Callable[[logging_config.CreateViewRequest], logging_config.LogView]: + def create_view(self) -> Callable[ + [logging_config.CreateViewRequest], + logging_config.LogView]: r"""Return a callable for the create view method over gRPC. Creates a view over log entries in a log bucket. A @@ -706,18 +680,18 @@ def create_view( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_view" not in self._stubs: - self._stubs["create_view"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CreateView", + if 'create_view' not in self._stubs: + self._stubs['create_view'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CreateView', request_serializer=logging_config.CreateViewRequest.serialize, response_deserializer=logging_config.LogView.deserialize, ) - return self._stubs["create_view"] + return self._stubs['create_view'] @property - def update_view( - self, - ) -> Callable[[logging_config.UpdateViewRequest], logging_config.LogView]: + def update_view(self) -> Callable[ + [logging_config.UpdateViewRequest], + logging_config.LogView]: r"""Return a callable for the update view method over gRPC. Updates a view on a log bucket. This method replaces the @@ -736,18 +710,18 @@ def update_view( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_view" not in self._stubs: - self._stubs["update_view"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateView", + if 'update_view' not in self._stubs: + self._stubs['update_view'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateView', request_serializer=logging_config.UpdateViewRequest.serialize, response_deserializer=logging_config.LogView.deserialize, ) - return self._stubs["update_view"] + return self._stubs['update_view'] @property - def delete_view( - self, - ) -> Callable[[logging_config.DeleteViewRequest], empty_pb2.Empty]: + def delete_view(self) -> Callable[ + [logging_config.DeleteViewRequest], + empty_pb2.Empty]: r"""Return a callable for the delete view method over gRPC. Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is @@ -765,18 +739,18 @@ def delete_view( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_view" not in self._stubs: - self._stubs["delete_view"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/DeleteView", + if 'delete_view' not in self._stubs: + self._stubs['delete_view'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/DeleteView', request_serializer=logging_config.DeleteViewRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_view"] + return self._stubs['delete_view'] @property - def list_sinks( - self, - ) -> Callable[[logging_config.ListSinksRequest], logging_config.ListSinksResponse]: + def list_sinks(self) -> Callable[ + [logging_config.ListSinksRequest], + logging_config.ListSinksResponse]: r"""Return a callable for the list sinks method over gRPC. Lists sinks. @@ -791,18 +765,18 @@ def list_sinks( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_sinks" not in self._stubs: - self._stubs["list_sinks"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/ListSinks", + if 'list_sinks' not in self._stubs: + self._stubs['list_sinks'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/ListSinks', request_serializer=logging_config.ListSinksRequest.serialize, response_deserializer=logging_config.ListSinksResponse.deserialize, ) - return self._stubs["list_sinks"] + return self._stubs['list_sinks'] @property - def get_sink( - self, - ) -> Callable[[logging_config.GetSinkRequest], logging_config.LogSink]: + def get_sink(self) -> Callable[ + [logging_config.GetSinkRequest], + logging_config.LogSink]: r"""Return a callable for the get sink method over gRPC. Gets a sink. @@ -817,18 +791,18 @@ def get_sink( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_sink" not in self._stubs: - self._stubs["get_sink"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetSink", + if 'get_sink' not in self._stubs: + self._stubs['get_sink'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetSink', request_serializer=logging_config.GetSinkRequest.serialize, response_deserializer=logging_config.LogSink.deserialize, ) - return self._stubs["get_sink"] + return self._stubs['get_sink'] @property - def create_sink( - self, - ) -> Callable[[logging_config.CreateSinkRequest], logging_config.LogSink]: + def create_sink(self) -> Callable[ + [logging_config.CreateSinkRequest], + logging_config.LogSink]: r"""Return a callable for the create sink method over gRPC. Creates a sink that exports specified log entries to a @@ -847,18 +821,18 @@ def create_sink( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_sink" not in self._stubs: - self._stubs["create_sink"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CreateSink", + if 'create_sink' not in self._stubs: + self._stubs['create_sink'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CreateSink', request_serializer=logging_config.CreateSinkRequest.serialize, response_deserializer=logging_config.LogSink.deserialize, ) - return self._stubs["create_sink"] + return self._stubs['create_sink'] @property - def update_sink( - self, - ) -> Callable[[logging_config.UpdateSinkRequest], logging_config.LogSink]: + def update_sink(self) -> Callable[ + [logging_config.UpdateSinkRequest], + logging_config.LogSink]: r"""Return a callable for the update sink method over gRPC. Updates a sink. This method replaces the following fields in the @@ -878,18 +852,18 @@ def update_sink( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_sink" not in self._stubs: - self._stubs["update_sink"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateSink", + if 'update_sink' not in self._stubs: + self._stubs['update_sink'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateSink', request_serializer=logging_config.UpdateSinkRequest.serialize, response_deserializer=logging_config.LogSink.deserialize, ) - return self._stubs["update_sink"] + return self._stubs['update_sink'] @property - def delete_sink( - self, - ) -> Callable[[logging_config.DeleteSinkRequest], empty_pb2.Empty]: + def delete_sink(self) -> Callable[ + [logging_config.DeleteSinkRequest], + empty_pb2.Empty]: r"""Return a callable for the delete sink method over gRPC. Deletes a sink. If the sink has a unique ``writer_identity``, @@ -905,18 +879,18 @@ def delete_sink( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_sink" not in self._stubs: - self._stubs["delete_sink"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/DeleteSink", + if 'delete_sink' not in self._stubs: + self._stubs['delete_sink'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/DeleteSink', request_serializer=logging_config.DeleteSinkRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_sink"] + return self._stubs['delete_sink'] @property - def create_link( - self, - ) -> Callable[[logging_config.CreateLinkRequest], operations_pb2.Operation]: + def create_link(self) -> Callable[ + [logging_config.CreateLinkRequest], + operations_pb2.Operation]: r"""Return a callable for the create link method over gRPC. Asynchronously creates a linked dataset in BigQuery @@ -934,18 +908,18 @@ def create_link( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_link" not in self._stubs: - self._stubs["create_link"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CreateLink", + if 'create_link' not in self._stubs: + self._stubs['create_link'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CreateLink', request_serializer=logging_config.CreateLinkRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_link"] + return self._stubs['create_link'] @property - def delete_link( - self, - ) -> Callable[[logging_config.DeleteLinkRequest], operations_pb2.Operation]: + def delete_link(self) -> Callable[ + [logging_config.DeleteLinkRequest], + operations_pb2.Operation]: r"""Return a callable for the delete link method over gRPC. Deletes a link. This will also delete the @@ -961,18 +935,18 @@ def delete_link( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_link" not in self._stubs: - self._stubs["delete_link"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/DeleteLink", + if 'delete_link' not in self._stubs: + self._stubs['delete_link'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/DeleteLink', request_serializer=logging_config.DeleteLinkRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["delete_link"] + return self._stubs['delete_link'] @property - def list_links( - self, - ) -> Callable[[logging_config.ListLinksRequest], logging_config.ListLinksResponse]: + def list_links(self) -> Callable[ + [logging_config.ListLinksRequest], + logging_config.ListLinksResponse]: r"""Return a callable for the list links method over gRPC. Lists links. @@ -987,18 +961,18 @@ def list_links( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_links" not in self._stubs: - self._stubs["list_links"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/ListLinks", + if 'list_links' not in self._stubs: + self._stubs['list_links'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/ListLinks', request_serializer=logging_config.ListLinksRequest.serialize, response_deserializer=logging_config.ListLinksResponse.deserialize, ) - return self._stubs["list_links"] + return self._stubs['list_links'] @property - def get_link( - self, - ) -> Callable[[logging_config.GetLinkRequest], logging_config.Link]: + def get_link(self) -> Callable[ + [logging_config.GetLinkRequest], + logging_config.Link]: r"""Return a callable for the get link method over gRPC. Gets a link. @@ -1013,20 +987,18 @@ def get_link( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_link" not in self._stubs: - self._stubs["get_link"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetLink", + if 'get_link' not in self._stubs: + self._stubs['get_link'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetLink', request_serializer=logging_config.GetLinkRequest.serialize, response_deserializer=logging_config.Link.deserialize, ) - return self._stubs["get_link"] + return self._stubs['get_link'] @property - def list_exclusions( - self, - ) -> Callable[ - [logging_config.ListExclusionsRequest], logging_config.ListExclusionsResponse - ]: + def list_exclusions(self) -> Callable[ + [logging_config.ListExclusionsRequest], + logging_config.ListExclusionsResponse]: r"""Return a callable for the list exclusions method over gRPC. Lists all the exclusions on the \_Default sink in a parent @@ -1042,18 +1014,18 @@ def list_exclusions( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_exclusions" not in self._stubs: - self._stubs["list_exclusions"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/ListExclusions", + if 'list_exclusions' not in self._stubs: + self._stubs['list_exclusions'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/ListExclusions', request_serializer=logging_config.ListExclusionsRequest.serialize, response_deserializer=logging_config.ListExclusionsResponse.deserialize, ) - return self._stubs["list_exclusions"] + return self._stubs['list_exclusions'] @property - def get_exclusion( - self, - ) -> Callable[[logging_config.GetExclusionRequest], logging_config.LogExclusion]: + def get_exclusion(self) -> Callable[ + [logging_config.GetExclusionRequest], + logging_config.LogExclusion]: r"""Return a callable for the get exclusion method over gRPC. Gets the description of an exclusion in the \_Default sink. @@ -1068,18 +1040,18 @@ def get_exclusion( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_exclusion" not in self._stubs: - self._stubs["get_exclusion"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetExclusion", + if 'get_exclusion' not in self._stubs: + self._stubs['get_exclusion'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetExclusion', request_serializer=logging_config.GetExclusionRequest.serialize, response_deserializer=logging_config.LogExclusion.deserialize, ) - return self._stubs["get_exclusion"] + return self._stubs['get_exclusion'] @property - def create_exclusion( - self, - ) -> Callable[[logging_config.CreateExclusionRequest], logging_config.LogExclusion]: + def create_exclusion(self) -> Callable[ + [logging_config.CreateExclusionRequest], + logging_config.LogExclusion]: r"""Return a callable for the create exclusion method over gRPC. Creates a new exclusion in the \_Default sink in a specified @@ -1096,18 +1068,18 @@ def create_exclusion( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_exclusion" not in self._stubs: - self._stubs["create_exclusion"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CreateExclusion", + if 'create_exclusion' not in self._stubs: + self._stubs['create_exclusion'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CreateExclusion', request_serializer=logging_config.CreateExclusionRequest.serialize, response_deserializer=logging_config.LogExclusion.deserialize, ) - return self._stubs["create_exclusion"] + return self._stubs['create_exclusion'] @property - def update_exclusion( - self, - ) -> Callable[[logging_config.UpdateExclusionRequest], logging_config.LogExclusion]: + def update_exclusion(self) -> Callable[ + [logging_config.UpdateExclusionRequest], + logging_config.LogExclusion]: r"""Return a callable for the update exclusion method over gRPC. Changes one or more properties of an existing exclusion in the @@ -1123,18 +1095,18 @@ def update_exclusion( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_exclusion" not in self._stubs: - self._stubs["update_exclusion"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateExclusion", + if 'update_exclusion' not in self._stubs: + self._stubs['update_exclusion'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateExclusion', request_serializer=logging_config.UpdateExclusionRequest.serialize, response_deserializer=logging_config.LogExclusion.deserialize, ) - return self._stubs["update_exclusion"] + return self._stubs['update_exclusion'] @property - def delete_exclusion( - self, - ) -> Callable[[logging_config.DeleteExclusionRequest], empty_pb2.Empty]: + def delete_exclusion(self) -> Callable[ + [logging_config.DeleteExclusionRequest], + empty_pb2.Empty]: r"""Return a callable for the delete exclusion method over gRPC. Deletes an exclusion in the \_Default sink. @@ -1149,18 +1121,18 @@ def delete_exclusion( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_exclusion" not in self._stubs: - self._stubs["delete_exclusion"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/DeleteExclusion", + if 'delete_exclusion' not in self._stubs: + self._stubs['delete_exclusion'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/DeleteExclusion', request_serializer=logging_config.DeleteExclusionRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_exclusion"] + return self._stubs['delete_exclusion'] @property - def get_cmek_settings( - self, - ) -> Callable[[logging_config.GetCmekSettingsRequest], logging_config.CmekSettings]: + def get_cmek_settings(self) -> Callable[ + [logging_config.GetCmekSettingsRequest], + logging_config.CmekSettings]: r"""Return a callable for the get cmek settings method over gRPC. Gets the Logging CMEK settings for the given resource. @@ -1184,20 +1156,18 @@ def get_cmek_settings( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_cmek_settings" not in self._stubs: - self._stubs["get_cmek_settings"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetCmekSettings", + if 'get_cmek_settings' not in self._stubs: + self._stubs['get_cmek_settings'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetCmekSettings', request_serializer=logging_config.GetCmekSettingsRequest.serialize, response_deserializer=logging_config.CmekSettings.deserialize, ) - return self._stubs["get_cmek_settings"] + return self._stubs['get_cmek_settings'] @property - def update_cmek_settings( - self, - ) -> Callable[ - [logging_config.UpdateCmekSettingsRequest], logging_config.CmekSettings - ]: + def update_cmek_settings(self) -> Callable[ + [logging_config.UpdateCmekSettingsRequest], + logging_config.CmekSettings]: r"""Return a callable for the update cmek settings method over gRPC. Updates the Log Router CMEK settings for the given resource. @@ -1226,18 +1196,18 @@ def update_cmek_settings( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_cmek_settings" not in self._stubs: - self._stubs["update_cmek_settings"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateCmekSettings", + if 'update_cmek_settings' not in self._stubs: + self._stubs['update_cmek_settings'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateCmekSettings', request_serializer=logging_config.UpdateCmekSettingsRequest.serialize, response_deserializer=logging_config.CmekSettings.deserialize, ) - return self._stubs["update_cmek_settings"] + return self._stubs['update_cmek_settings'] @property - def get_settings( - self, - ) -> Callable[[logging_config.GetSettingsRequest], logging_config.Settings]: + def get_settings(self) -> Callable[ + [logging_config.GetSettingsRequest], + logging_config.Settings]: r"""Return a callable for the get settings method over gRPC. Gets the Log Router settings for the given resource. @@ -1262,18 +1232,18 @@ def get_settings( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_settings" not in self._stubs: - self._stubs["get_settings"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/GetSettings", + if 'get_settings' not in self._stubs: + self._stubs['get_settings'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/GetSettings', request_serializer=logging_config.GetSettingsRequest.serialize, response_deserializer=logging_config.Settings.deserialize, ) - return self._stubs["get_settings"] + return self._stubs['get_settings'] @property - def update_settings( - self, - ) -> Callable[[logging_config.UpdateSettingsRequest], logging_config.Settings]: + def update_settings(self) -> Callable[ + [logging_config.UpdateSettingsRequest], + logging_config.Settings]: r"""Return a callable for the update settings method over gRPC. Updates the Log Router settings for the given resource. @@ -1305,18 +1275,18 @@ def update_settings( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_settings" not in self._stubs: - self._stubs["update_settings"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/UpdateSettings", + if 'update_settings' not in self._stubs: + self._stubs['update_settings'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/UpdateSettings', request_serializer=logging_config.UpdateSettingsRequest.serialize, response_deserializer=logging_config.Settings.deserialize, ) - return self._stubs["update_settings"] + return self._stubs['update_settings'] @property - def copy_log_entries( - self, - ) -> Callable[[logging_config.CopyLogEntriesRequest], operations_pb2.Operation]: + def copy_log_entries(self) -> Callable[ + [logging_config.CopyLogEntriesRequest], + operations_pb2.Operation]: r"""Return a callable for the copy log entries method over gRPC. Copies a set of log entries from a log bucket to a @@ -1332,13 +1302,13 @@ def copy_log_entries( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "copy_log_entries" not in self._stubs: - self._stubs["copy_log_entries"] = self._logged_channel.unary_unary( - "/google.logging.v2.ConfigServiceV2/CopyLogEntries", + if 'copy_log_entries' not in self._stubs: + self._stubs['copy_log_entries'] = self._logged_channel.unary_unary( + '/google.logging.v2.ConfigServiceV2/CopyLogEntries', request_serializer=logging_config.CopyLogEntriesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["copy_log_entries"] + return self._stubs['copy_log_entries'] def close(self): self._logged_channel.close() @@ -1347,7 +1317,8 @@ def close(self): def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC.""" + r"""Return a callable for the cancel_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1364,7 +1335,8 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1380,10 +1352,9 @@ def get_operation( @property def list_operations( self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse - ]: - r"""Return a callable for the list_operations method over gRPC.""" + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1401,4 +1372,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("ConfigServiceV2GrpcTransport",) +__all__ = ( + 'ConfigServiceV2GrpcTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py index 40c01d7305c8..1a479a753bae 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -13,48 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import inspect import json import logging as std_logging import os import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast import warnings -from collections import OrderedDict -from http import HTTPStatus -from typing import ( - Callable, - Dict, - Iterable, - Iterator, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import google.protobuf +from google.cloud.logging_v2 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.logging_v2 import gapic_version as package_version -from google.cloud.logging_v2._compat import ( - get_api_endpoint, - get_default_mtls_endpoint, - get_universe_domain, - read_environment_variables, - should_use_client_cert, -) -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -63,7 +44,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -77,12 +57,12 @@ _LOGGER = std_logging.getLogger(__name__) -import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore from google.cloud.logging_v2.services.logging_service_v2 import pagers -from google.cloud.logging_v2.types import log_entry, logging -from google.longrunning import operations_pb2 # type: ignore - -from .transports.base import DEFAULT_CLIENT_INFO, LoggingServiceV2Transport +from google.cloud.logging_v2.types import log_entry +from google.cloud.logging_v2.types import logging +from google.longrunning import operations_pb2 # type: ignore +import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore +from .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO from .transports.grpc import LoggingServiceV2GrpcTransport from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport @@ -94,15 +74,13 @@ class LoggingServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[LoggingServiceV2Transport]] _transport_registry["grpc"] = LoggingServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = LoggingServiceV2GrpcAsyncIOTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[LoggingServiceV2Transport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[LoggingServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -162,7 +140,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LoggingServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -179,103 +158,73 @@ def transport(self) -> LoggingServiceV2Transport: return self._transport @staticmethod - def log_path( - project: str, - log: str, - ) -> str: + def log_path(project: str,log: str,) -> str: """Returns a fully-qualified log string.""" - return "projects/{project}/logs/{log}".format( - project=project, - log=log, - ) + return "projects/{project}/logs/{log}".format(project=project, log=log, ) @staticmethod - def parse_log_path(path: str) -> Dict[str, str]: + def parse_log_path(path: str) -> Dict[str,str]: """Parses a log path into its component segments.""" m = re.match(r"^projects/(?P.+?)/logs/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -307,18 +256,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -331,10 +276,8 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -373,18 +316,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -417,18 +357,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[ - str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the logging service v2 client. Args: @@ -483,23 +417,13 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - read_environment_variables() - ) - self._client_cert_source = LoggingServiceV2Client._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = get_universe_domain( - universe_domain_opt, - self._universe_domain_env, - default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE, - ) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() + self._client_cert_source = LoggingServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -511,9 +435,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -522,41 +444,35 @@ def __init__( if transport_provided: # transport is a LoggingServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = cast(LoggingServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = self._api_endpoint or get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE, - default_mtls_endpoint=LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" - or (self._use_mtls_endpoint == "auto" and self._client_cert_source), - ) + self._api_endpoint = (self._api_endpoint or + get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=LoggingServiceV2Client._DEFAULT_UNIVERSE, + default_mtls_endpoint=LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" or ( + self._use_mtls_endpoint == "auto" and self._client_cert_source + ), + )) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[LoggingServiceV2Transport], - Callable[..., LoggingServiceV2Transport], - ] = ( + transport_init: Union[Type[LoggingServiceV2Transport], Callable[..., LoggingServiceV2Transport]] = ( LoggingServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., LoggingServiceV2Transport], transport) @@ -585,46 +501,33 @@ def __init__( "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **( - {"client_options": client_options} - if client_options is not None - else {} - ), + **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.LoggingServiceV2Client`.", - extra={ + extra = { "serviceName": "google.logging.v2.LoggingServiceV2", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.logging.v2.LoggingServiceV2", "credentialsType": None, - }, + } ) - def delete_log( - self, - request: Optional[Union[logging.DeleteLogRequest, dict]] = None, - *, - log_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_log(self, + request: Optional[Union[logging.DeleteLogRequest, dict]] = None, + *, + log_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes all the log entries in a log for the \_Default Log Bucket. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be @@ -687,14 +590,10 @@ def sample_delete_log(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -712,7 +611,9 @@ def sample_delete_log(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("log_name", request.log_name), + )), ) # Validate the universe domain. @@ -726,18 +627,17 @@ def sample_delete_log(): metadata=metadata, ) - def write_log_entries( - self, - request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, - *, - log_name: Optional[str] = None, - resource: Optional[monitored_resource_pb2.MonitoredResource] = None, - labels: Optional[MutableMapping[str, str]] = None, - entries: Optional[MutableSequence[log_entry.LogEntry]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging.WriteLogEntriesResponse: + def write_log_entries(self, + request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, + *, + log_name: Optional[str] = None, + resource: Optional[monitored_resource_pb2.MonitoredResource] = None, + labels: Optional[MutableMapping[str, str]] = None, + entries: Optional[MutableSequence[log_entry.LogEntry]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging.WriteLogEntriesResponse: r"""Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent @@ -880,14 +780,10 @@ def sample_write_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name, resource, labels, entries] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -922,17 +818,16 @@ def sample_write_log_entries(): # Done; return the response. return response - def list_log_entries( - self, - request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, - *, - resource_names: Optional[MutableSequence[str]] = None, - filter: Optional[str] = None, - order_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogEntriesPager: + def list_log_entries(self, + request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, + *, + resource_names: Optional[MutableSequence[str]] = None, + filter: Optional[str] = None, + order_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogEntriesPager: r"""Lists log entries. Use this method to retrieve log entries that originated from a project/folder/organization/billing account. For ways to export log entries, see `Exporting @@ -1035,14 +930,10 @@ def sample_list_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [resource_names, filter, order_by] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1086,16 +977,13 @@ def sample_list_log_entries(): # Done; return the response. return response - def list_monitored_resource_descriptors( - self, - request: Optional[ - Union[logging.ListMonitoredResourceDescriptorsRequest, dict] - ] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMonitoredResourceDescriptorsPager: + def list_monitored_resource_descriptors(self, + request: Optional[Union[logging.ListMonitoredResourceDescriptorsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMonitoredResourceDescriptorsPager: r"""Lists the descriptors for monitored resource types used by Logging. @@ -1154,9 +1042,7 @@ def sample_list_monitored_resource_descriptors(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.list_monitored_resource_descriptors - ] + rpc = self._transport._wrapped_methods[self._transport.list_monitored_resource_descriptors] # Validate the universe domain. self._validate_universe_domain() @@ -1183,15 +1069,14 @@ def sample_list_monitored_resource_descriptors(): # Done; return the response. return response - def list_logs( - self, - request: Optional[Union[logging.ListLogsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogsPager: + def list_logs(self, + request: Optional[Union[logging.ListLogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogsPager: r"""Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have entries are listed. @@ -1258,14 +1143,10 @@ def sample_list_logs(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1283,7 +1164,9 @@ def sample_list_logs(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1311,14 +1194,13 @@ def sample_list_logs(): # Done; return the response. return response - def tail_log_entries( - self, - requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Iterable[logging.TailLogEntriesResponse]: + def tail_log_entries(self, + requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[logging.TailLogEntriesResponse]: r"""Streaming read of log entries as they are ingested. Until the stream is terminated, it will continue reading logs. @@ -1449,7 +1331,8 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1458,11 +1341,7 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1512,7 +1391,8 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1521,11 +1401,7 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1578,24 +1454,25 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("LoggingServiceV2Client",) +__all__ = ( + "LoggingServiceV2Client", +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index 82763d3d459b..5be4cc6ca83e 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -17,23 +17,23 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import google.api_core +from google.cloud.logging_v2 import gapic_version as package_version + import google.auth # type: ignore -import google.protobuf -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.api_core from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.cloud.logging_v2 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore +import google.protobuf + from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ # Check once at module load time whether google-api-core's wrap_method supports @@ -48,29 +48,28 @@ class LoggingServiceV2Transport(abc.ABC): """Abstract transport class for LoggingServiceV2.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-platform.read-only", - "https://www.googleapis.com/auth/logging.admin", - "https://www.googleapis.com/auth/logging.read", - "https://www.googleapis.com/auth/logging.write", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + 'https://www.googleapis.com/auth/logging.admin', + 'https://www.googleapis.com/auth/logging.read', + 'https://www.googleapis.com/auth/logging.write', ) - DEFAULT_HOST: str = "logging.googleapis.com" + DEFAULT_HOST: str = 'logging.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -112,43 +111,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host self._client_options = client_options @@ -175,12 +162,7 @@ def _wrap_method(self, func, *args, **kwargs): # of google-api-core is installed (which does not accept client_options, etc.). # Excluded from coverage because our CI and testing environments always install # a modern version of google-api-core that supports tracing. - for k in [ - "client_options", - "method_name", - "is_streaming", - "kind", - ]: # pragma: NO COVER + for k in ["client_options", "method_name", "is_streaming", "kind"]: # pragma: NO COVER kwargs.pop(k, None) # pragma: NO COVER return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER @@ -305,77 +287,69 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def delete_log( - self, - ) -> Callable[ - [logging.DeleteLogRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] - ]: + def delete_log(self) -> Callable[ + [logging.DeleteLogRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def write_log_entries( - self, - ) -> Callable[ - [logging.WriteLogEntriesRequest], - Union[ - logging.WriteLogEntriesResponse, Awaitable[logging.WriteLogEntriesResponse] - ], - ]: + def write_log_entries(self) -> Callable[ + [logging.WriteLogEntriesRequest], + Union[ + logging.WriteLogEntriesResponse, + Awaitable[logging.WriteLogEntriesResponse] + ]]: raise NotImplementedError() @property - def list_log_entries( - self, - ) -> Callable[ - [logging.ListLogEntriesRequest], - Union[ - logging.ListLogEntriesResponse, Awaitable[logging.ListLogEntriesResponse] - ], - ]: + def list_log_entries(self) -> Callable[ + [logging.ListLogEntriesRequest], + Union[ + logging.ListLogEntriesResponse, + Awaitable[logging.ListLogEntriesResponse] + ]]: raise NotImplementedError() @property - def list_monitored_resource_descriptors( - self, - ) -> Callable[ - [logging.ListMonitoredResourceDescriptorsRequest], - Union[ - logging.ListMonitoredResourceDescriptorsResponse, - Awaitable[logging.ListMonitoredResourceDescriptorsResponse], - ], - ]: + def list_monitored_resource_descriptors(self) -> Callable[ + [logging.ListMonitoredResourceDescriptorsRequest], + Union[ + logging.ListMonitoredResourceDescriptorsResponse, + Awaitable[logging.ListMonitoredResourceDescriptorsResponse] + ]]: raise NotImplementedError() @property - def list_logs( - self, - ) -> Callable[ - [logging.ListLogsRequest], - Union[logging.ListLogsResponse, Awaitable[logging.ListLogsResponse]], - ]: + def list_logs(self) -> Callable[ + [logging.ListLogsRequest], + Union[ + logging.ListLogsResponse, + Awaitable[logging.ListLogsResponse] + ]]: raise NotImplementedError() @property - def tail_log_entries( - self, - ) -> Callable[ - [logging.TailLogEntriesRequest], - Union[ - logging.TailLogEntriesResponse, Awaitable[logging.TailLogEntriesResponse] - ], - ]: + def tail_log_entries(self) -> Callable[ + [logging.TailLogEntriesRequest], + Union[ + logging.TailLogEntriesResponse, + Awaitable[logging.TailLogEntriesResponse] + ]]: raise NotImplementedError() @property @@ -383,10 +357,7 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[ - operations_pb2.ListOperationsResponse, - Awaitable[operations_pb2.ListOperationsResponse], - ], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], ]: raise NotImplementedError() @@ -413,4 +384,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("LoggingServiceV2Transport",) +__all__ = ( + 'LoggingServiceV2Transport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index bd4c44c84030..5e994ee69806 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -17,19 +17,16 @@ import logging as std_logging import pickle import warnings -from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ( - ClientInterceptor, # type: ignore[attr-defined] - ) + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 - # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -37,21 +34,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -import google.protobuf.message -import proto # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import proto # type: ignore -from .base import DEFAULT_CLIENT_INFO, LoggingServiceV2Transport +from google.cloud.logging_v2.types import logging +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from .base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -61,9 +58,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -84,7 +79,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.logging.v2.LoggingServiceV2", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -95,11 +90,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -114,7 +105,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.logging.v2.LoggingServiceV2", "rpcName": client_call_details.method, "response": grpc_response, @@ -136,35 +127,32 @@ class LoggingServiceV2GrpcTransport(LoggingServiceV2Transport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "logging.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], + def __init__(self, *, + host: str = 'logging.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], + ] ] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -300,17 +288,9 @@ def __init__( channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) - ) - is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None and otel_interceptor not in channel_interceptors - and not any( - getattr(i, "_is_otel_interceptor", None) is True - for i in channel_interceptors - ) + and not any(getattr(i, "_is_otel_interceptor", None) is True for i in channel_interceptors) ): channel_interceptors.append(otel_interceptor) @@ -319,28 +299,22 @@ def __init__( "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors( - self._grpc_channel, channel_interceptors - ) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "logging.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'logging.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -376,16 +350,19 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property - def delete_log(self) -> Callable[[logging.DeleteLogRequest], empty_pb2.Empty]: + def delete_log(self) -> Callable[ + [logging.DeleteLogRequest], + empty_pb2.Empty]: r"""Return a callable for the delete log method over gRPC. Deletes all the log entries in a log for the \_Default Log @@ -404,18 +381,18 @@ def delete_log(self) -> Callable[[logging.DeleteLogRequest], empty_pb2.Empty]: # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_log" not in self._stubs: - self._stubs["delete_log"] = self._logged_channel.unary_unary( - "/google.logging.v2.LoggingServiceV2/DeleteLog", + if 'delete_log' not in self._stubs: + self._stubs['delete_log'] = self._logged_channel.unary_unary( + '/google.logging.v2.LoggingServiceV2/DeleteLog', request_serializer=logging.DeleteLogRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_log"] + return self._stubs['delete_log'] @property - def write_log_entries( - self, - ) -> Callable[[logging.WriteLogEntriesRequest], logging.WriteLogEntriesResponse]: + def write_log_entries(self) -> Callable[ + [logging.WriteLogEntriesRequest], + logging.WriteLogEntriesResponse]: r"""Return a callable for the write log entries method over gRPC. Writes log entries to Logging. This API method is the @@ -436,18 +413,18 @@ def write_log_entries( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "write_log_entries" not in self._stubs: - self._stubs["write_log_entries"] = self._logged_channel.unary_unary( - "/google.logging.v2.LoggingServiceV2/WriteLogEntries", + if 'write_log_entries' not in self._stubs: + self._stubs['write_log_entries'] = self._logged_channel.unary_unary( + '/google.logging.v2.LoggingServiceV2/WriteLogEntries', request_serializer=logging.WriteLogEntriesRequest.serialize, response_deserializer=logging.WriteLogEntriesResponse.deserialize, ) - return self._stubs["write_log_entries"] + return self._stubs['write_log_entries'] @property - def list_log_entries( - self, - ) -> Callable[[logging.ListLogEntriesRequest], logging.ListLogEntriesResponse]: + def list_log_entries(self) -> Callable[ + [logging.ListLogEntriesRequest], + logging.ListLogEntriesResponse]: r"""Return a callable for the list log entries method over gRPC. Lists log entries. Use this method to retrieve log entries that @@ -465,21 +442,18 @@ def list_log_entries( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_log_entries" not in self._stubs: - self._stubs["list_log_entries"] = self._logged_channel.unary_unary( - "/google.logging.v2.LoggingServiceV2/ListLogEntries", + if 'list_log_entries' not in self._stubs: + self._stubs['list_log_entries'] = self._logged_channel.unary_unary( + '/google.logging.v2.LoggingServiceV2/ListLogEntries', request_serializer=logging.ListLogEntriesRequest.serialize, response_deserializer=logging.ListLogEntriesResponse.deserialize, ) - return self._stubs["list_log_entries"] + return self._stubs['list_log_entries'] @property - def list_monitored_resource_descriptors( - self, - ) -> Callable[ - [logging.ListMonitoredResourceDescriptorsRequest], - logging.ListMonitoredResourceDescriptorsResponse, - ]: + def list_monitored_resource_descriptors(self) -> Callable[ + [logging.ListMonitoredResourceDescriptorsRequest], + logging.ListMonitoredResourceDescriptorsResponse]: r"""Return a callable for the list monitored resource descriptors method over gRPC. @@ -496,20 +470,18 @@ def list_monitored_resource_descriptors( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_monitored_resource_descriptors" not in self._stubs: - self._stubs["list_monitored_resource_descriptors"] = ( - self._logged_channel.unary_unary( - "/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors", - request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize, - response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize, - ) + if 'list_monitored_resource_descriptors' not in self._stubs: + self._stubs['list_monitored_resource_descriptors'] = self._logged_channel.unary_unary( + '/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors', + request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize, + response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize, ) - return self._stubs["list_monitored_resource_descriptors"] + return self._stubs['list_monitored_resource_descriptors'] @property - def list_logs( - self, - ) -> Callable[[logging.ListLogsRequest], logging.ListLogsResponse]: + def list_logs(self) -> Callable[ + [logging.ListLogsRequest], + logging.ListLogsResponse]: r"""Return a callable for the list logs method over gRPC. Lists the logs in projects, organizations, folders, @@ -526,18 +498,18 @@ def list_logs( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_logs" not in self._stubs: - self._stubs["list_logs"] = self._logged_channel.unary_unary( - "/google.logging.v2.LoggingServiceV2/ListLogs", + if 'list_logs' not in self._stubs: + self._stubs['list_logs'] = self._logged_channel.unary_unary( + '/google.logging.v2.LoggingServiceV2/ListLogs', request_serializer=logging.ListLogsRequest.serialize, response_deserializer=logging.ListLogsResponse.deserialize, ) - return self._stubs["list_logs"] + return self._stubs['list_logs'] @property - def tail_log_entries( - self, - ) -> Callable[[logging.TailLogEntriesRequest], logging.TailLogEntriesResponse]: + def tail_log_entries(self) -> Callable[ + [logging.TailLogEntriesRequest], + logging.TailLogEntriesResponse]: r"""Return a callable for the tail log entries method over gRPC. Streaming read of log entries as they are ingested. @@ -554,13 +526,13 @@ def tail_log_entries( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "tail_log_entries" not in self._stubs: - self._stubs["tail_log_entries"] = self._logged_channel.stream_stream( - "/google.logging.v2.LoggingServiceV2/TailLogEntries", + if 'tail_log_entries' not in self._stubs: + self._stubs['tail_log_entries'] = self._logged_channel.stream_stream( + '/google.logging.v2.LoggingServiceV2/TailLogEntries', request_serializer=logging.TailLogEntriesRequest.serialize, response_deserializer=logging.TailLogEntriesResponse.deserialize, ) - return self._stubs["tail_log_entries"] + return self._stubs['tail_log_entries'] def close(self): self._logged_channel.close() @@ -569,7 +541,8 @@ def close(self): def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC.""" + r"""Return a callable for the cancel_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -586,7 +559,8 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -602,10 +576,9 @@ def get_operation( @property def list_operations( self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse - ]: - r"""Return a callable for the list_operations method over gRPC.""" + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -623,4 +596,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("LoggingServiceV2GrpcTransport",) +__all__ = ( + 'LoggingServiceV2GrpcTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py index d7c96031b7f4..9ba7f3a26ace 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -13,46 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import inspect import json import logging as std_logging import os import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings -from collections import OrderedDict -from http import HTTPStatus -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import google.protobuf +from google.cloud.logging_v2 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.logging_v2 import gapic_version as package_version -from google.cloud.logging_v2._compat import ( - get_api_endpoint, - get_default_mtls_endpoint, - get_universe_domain, - read_environment_variables, - should_use_client_cert, -) -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -61,7 +44,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -75,14 +57,13 @@ _LOGGER = std_logging.getLogger(__name__) +from google.cloud.logging_v2.services.metrics_service_v2 import pagers +from google.cloud.logging_v2.types import logging_metrics +from google.longrunning import operations_pb2 # type: ignore import google.api.distribution_pb2 as distribution_pb2 # type: ignore import google.api.metric_pb2 as metric_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from google.cloud.logging_v2.services.metrics_service_v2 import pagers -from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore - -from .transports.base import DEFAULT_CLIENT_INFO, MetricsServiceV2Transport +from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO from .transports.grpc import MetricsServiceV2GrpcTransport from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport @@ -94,15 +75,13 @@ class BaseMetricsServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[MetricsServiceV2Transport]] _transport_registry["grpc"] = MetricsServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[MetricsServiceV2Transport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[MetricsServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -162,7 +141,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BaseMetricsServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -179,103 +159,73 @@ def transport(self) -> MetricsServiceV2Transport: return self._transport @staticmethod - def log_metric_path( - project: str, - metric: str, - ) -> str: + def log_metric_path(project: str,metric: str,) -> str: """Returns a fully-qualified log_metric string.""" - return "projects/{project}/metrics/{metric}".format( - project=project, - metric=metric, - ) + return "projects/{project}/metrics/{metric}".format(project=project, metric=metric, ) @staticmethod - def parse_log_metric_path(path: str) -> Dict[str, str]: + def parse_log_metric_path(path: str) -> Dict[str,str]: """Parses a log_metric path into its component segments.""" m = re.match(r"^projects/(?P.+?)/metrics/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -307,18 +257,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -331,10 +277,8 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -373,18 +317,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -417,18 +358,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[ - str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the base metrics service v2 client. Args: @@ -483,23 +418,13 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - read_environment_variables() - ) - self._client_cert_source = BaseMetricsServiceV2Client._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = get_universe_domain( - universe_domain_opt, - self._universe_domain_env, - default_universe=BaseMetricsServiceV2Client._DEFAULT_UNIVERSE, - ) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() + self._client_cert_source = BaseMetricsServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=BaseMetricsServiceV2Client._DEFAULT_UNIVERSE) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -511,9 +436,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -522,41 +445,35 @@ def __init__( if transport_provided: # transport is a MetricsServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = cast(MetricsServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = self._api_endpoint or get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=BaseMetricsServiceV2Client._DEFAULT_UNIVERSE, - default_mtls_endpoint=BaseMetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=BaseMetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" - or (self._use_mtls_endpoint == "auto" and self._client_cert_source), - ) + self._api_endpoint = (self._api_endpoint or + get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=BaseMetricsServiceV2Client._DEFAULT_UNIVERSE, + default_mtls_endpoint=BaseMetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=BaseMetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" or ( + self._use_mtls_endpoint == "auto" and self._client_cert_source + ), + )) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[MetricsServiceV2Transport], - Callable[..., MetricsServiceV2Transport], - ] = ( + transport_init: Union[Type[MetricsServiceV2Transport], Callable[..., MetricsServiceV2Transport]] = ( BaseMetricsServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., MetricsServiceV2Transport], transport) @@ -585,46 +502,33 @@ def __init__( "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **( - {"client_options": client_options} - if client_options is not None - else {} - ), + **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.BaseMetricsServiceV2Client`.", - extra={ + extra = { "serviceName": "google.logging.v2.MetricsServiceV2", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.logging.v2.MetricsServiceV2", "credentialsType": None, - }, + } ) - def _list_log_metrics( - self, - request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogMetricsPager: + def _list_log_metrics(self, + request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogMetricsPager: r"""Lists logs-based metrics. .. code-block:: python @@ -689,14 +593,10 @@ def sample_list_log_metrics(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -714,7 +614,9 @@ def sample_list_log_metrics(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -742,15 +644,14 @@ def sample_list_log_metrics(): # Done; return the response. return response - def _get_log_metric( - self, - request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def _get_log_metric(self, + request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Gets a logs-based metric. .. code-block:: python @@ -820,14 +721,10 @@ def sample_get_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -845,9 +742,9 @@ def sample_get_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("metric_name", request.metric_name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("metric_name", request.metric_name), + )), ) # Validate the universe domain. @@ -864,16 +761,15 @@ def sample_get_log_metric(): # Done; return the response. return response - def _create_log_metric( - self, - request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, - *, - parent: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def _create_log_metric(self, + request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates a logs-based metric. .. code-block:: python @@ -959,14 +855,10 @@ def sample_create_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, metric] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -986,7 +878,9 @@ def sample_create_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1003,16 +897,15 @@ def sample_create_log_metric(): # Done; return the response. return response - def _update_log_metric( - self, - request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def _update_log_metric(self, + request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates or updates a logs-based metric. .. code-block:: python @@ -1097,14 +990,10 @@ def sample_update_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name, metric] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1124,9 +1013,9 @@ def sample_update_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("metric_name", request.metric_name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("metric_name", request.metric_name), + )), ) # Validate the universe domain. @@ -1143,15 +1032,14 @@ def sample_update_log_metric(): # Done; return the response. return response - def _delete_log_metric( - self, - request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def _delete_log_metric(self, + request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a logs-based metric. .. code-block:: python @@ -1202,14 +1090,10 @@ def sample_delete_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1227,9 +1111,9 @@ def sample_delete_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("metric_name", request.metric_name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("metric_name", request.metric_name), + )), ) # Validate the universe domain. @@ -1298,7 +1182,8 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1307,11 +1192,7 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1361,7 +1242,8 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1370,11 +1252,7 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1427,24 +1305,25 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("BaseMetricsServiceV2Client",) +__all__ = ( + "BaseMetricsServiceV2Client", +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index 5e8c203f0a9f..362c7a9f93e5 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -17,23 +17,23 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import google.api_core +from google.cloud.logging_v2 import gapic_version as package_version + import google.auth # type: ignore -import google.protobuf -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.api_core from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.cloud.logging_v2 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore +import google.protobuf + from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ # Check once at module load time whether google-api-core's wrap_method supports @@ -48,29 +48,28 @@ class MetricsServiceV2Transport(abc.ABC): """Abstract transport class for MetricsServiceV2.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-platform.read-only", - "https://www.googleapis.com/auth/logging.admin", - "https://www.googleapis.com/auth/logging.read", - "https://www.googleapis.com/auth/logging.write", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + 'https://www.googleapis.com/auth/logging.admin', + 'https://www.googleapis.com/auth/logging.read', + 'https://www.googleapis.com/auth/logging.write', ) - DEFAULT_HOST: str = "logging.googleapis.com" + DEFAULT_HOST: str = 'logging.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -112,43 +111,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host self._client_options = client_options @@ -175,12 +162,7 @@ def _wrap_method(self, func, *args, **kwargs): # of google-api-core is installed (which does not accept client_options, etc.). # Excluded from coverage because our CI and testing environments always install # a modern version of google-api-core that supports tracing. - for k in [ - "client_options", - "method_name", - "is_streaming", - "kind", - ]: # pragma: NO COVER + for k in ["client_options", "method_name", "is_streaming", "kind"]: # pragma: NO COVER kwargs.pop(k, None) # pragma: NO COVER return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER @@ -276,63 +258,60 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def list_log_metrics( - self, - ) -> Callable[ - [logging_metrics.ListLogMetricsRequest], - Union[ - logging_metrics.ListLogMetricsResponse, - Awaitable[logging_metrics.ListLogMetricsResponse], - ], - ]: + def list_log_metrics(self) -> Callable[ + [logging_metrics.ListLogMetricsRequest], + Union[ + logging_metrics.ListLogMetricsResponse, + Awaitable[logging_metrics.ListLogMetricsResponse] + ]]: raise NotImplementedError() @property - def get_log_metric( - self, - ) -> Callable[ - [logging_metrics.GetLogMetricRequest], - Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], - ]: + def get_log_metric(self) -> Callable[ + [logging_metrics.GetLogMetricRequest], + Union[ + logging_metrics.LogMetric, + Awaitable[logging_metrics.LogMetric] + ]]: raise NotImplementedError() @property - def create_log_metric( - self, - ) -> Callable[ - [logging_metrics.CreateLogMetricRequest], - Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], - ]: + def create_log_metric(self) -> Callable[ + [logging_metrics.CreateLogMetricRequest], + Union[ + logging_metrics.LogMetric, + Awaitable[logging_metrics.LogMetric] + ]]: raise NotImplementedError() @property - def update_log_metric( - self, - ) -> Callable[ - [logging_metrics.UpdateLogMetricRequest], - Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], - ]: + def update_log_metric(self) -> Callable[ + [logging_metrics.UpdateLogMetricRequest], + Union[ + logging_metrics.LogMetric, + Awaitable[logging_metrics.LogMetric] + ]]: raise NotImplementedError() @property - def delete_log_metric( - self, - ) -> Callable[ - [logging_metrics.DeleteLogMetricRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_log_metric(self) -> Callable[ + [logging_metrics.DeleteLogMetricRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property @@ -340,10 +319,7 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[ - operations_pb2.ListOperationsResponse, - Awaitable[operations_pb2.ListOperationsResponse], - ], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], ]: raise NotImplementedError() @@ -370,4 +346,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("MetricsServiceV2Transport",) +__all__ = ( + 'MetricsServiceV2Transport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index 8b3f065959fb..a92efdd6ab6c 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -17,19 +17,16 @@ import logging as std_logging import pickle import warnings -from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ( - ClientInterceptor, # type: ignore[attr-defined] - ) + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 - # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -37,21 +34,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -import google.protobuf.message -import proto # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import proto # type: ignore -from .base import DEFAULT_CLIENT_INFO, MetricsServiceV2Transport +from google.cloud.logging_v2.types import logging_metrics +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from .base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -61,9 +58,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -84,7 +79,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.logging.v2.MetricsServiceV2", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -95,11 +90,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -114,7 +105,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.logging.v2.MetricsServiceV2", "rpcName": client_call_details.method, "response": grpc_response, @@ -136,35 +127,32 @@ class MetricsServiceV2GrpcTransport(MetricsServiceV2Transport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "logging.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], + def __init__(self, *, + host: str = 'logging.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], + ] ] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -300,17 +288,9 @@ def __init__( channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) - ) - is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None and otel_interceptor not in channel_interceptors - and not any( - getattr(i, "_is_otel_interceptor", None) is True - for i in channel_interceptors - ) + and not any(getattr(i, "_is_otel_interceptor", None) is True for i in channel_interceptors) ): channel_interceptors.append(otel_interceptor) @@ -319,28 +299,22 @@ def __init__( "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors( - self._grpc_channel, channel_interceptors - ) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "logging.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'logging.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -376,20 +350,19 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property - def list_log_metrics( - self, - ) -> Callable[ - [logging_metrics.ListLogMetricsRequest], logging_metrics.ListLogMetricsResponse - ]: + def list_log_metrics(self) -> Callable[ + [logging_metrics.ListLogMetricsRequest], + logging_metrics.ListLogMetricsResponse]: r"""Return a callable for the list log metrics method over gRPC. Lists logs-based metrics. @@ -404,18 +377,18 @@ def list_log_metrics( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_log_metrics" not in self._stubs: - self._stubs["list_log_metrics"] = self._logged_channel.unary_unary( - "/google.logging.v2.MetricsServiceV2/ListLogMetrics", + if 'list_log_metrics' not in self._stubs: + self._stubs['list_log_metrics'] = self._logged_channel.unary_unary( + '/google.logging.v2.MetricsServiceV2/ListLogMetrics', request_serializer=logging_metrics.ListLogMetricsRequest.serialize, response_deserializer=logging_metrics.ListLogMetricsResponse.deserialize, ) - return self._stubs["list_log_metrics"] + return self._stubs['list_log_metrics'] @property - def get_log_metric( - self, - ) -> Callable[[logging_metrics.GetLogMetricRequest], logging_metrics.LogMetric]: + def get_log_metric(self) -> Callable[ + [logging_metrics.GetLogMetricRequest], + logging_metrics.LogMetric]: r"""Return a callable for the get log metric method over gRPC. Gets a logs-based metric. @@ -430,18 +403,18 @@ def get_log_metric( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_log_metric" not in self._stubs: - self._stubs["get_log_metric"] = self._logged_channel.unary_unary( - "/google.logging.v2.MetricsServiceV2/GetLogMetric", + if 'get_log_metric' not in self._stubs: + self._stubs['get_log_metric'] = self._logged_channel.unary_unary( + '/google.logging.v2.MetricsServiceV2/GetLogMetric', request_serializer=logging_metrics.GetLogMetricRequest.serialize, response_deserializer=logging_metrics.LogMetric.deserialize, ) - return self._stubs["get_log_metric"] + return self._stubs['get_log_metric'] @property - def create_log_metric( - self, - ) -> Callable[[logging_metrics.CreateLogMetricRequest], logging_metrics.LogMetric]: + def create_log_metric(self) -> Callable[ + [logging_metrics.CreateLogMetricRequest], + logging_metrics.LogMetric]: r"""Return a callable for the create log metric method over gRPC. Creates a logs-based metric. @@ -456,18 +429,18 @@ def create_log_metric( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_log_metric" not in self._stubs: - self._stubs["create_log_metric"] = self._logged_channel.unary_unary( - "/google.logging.v2.MetricsServiceV2/CreateLogMetric", + if 'create_log_metric' not in self._stubs: + self._stubs['create_log_metric'] = self._logged_channel.unary_unary( + '/google.logging.v2.MetricsServiceV2/CreateLogMetric', request_serializer=logging_metrics.CreateLogMetricRequest.serialize, response_deserializer=logging_metrics.LogMetric.deserialize, ) - return self._stubs["create_log_metric"] + return self._stubs['create_log_metric'] @property - def update_log_metric( - self, - ) -> Callable[[logging_metrics.UpdateLogMetricRequest], logging_metrics.LogMetric]: + def update_log_metric(self) -> Callable[ + [logging_metrics.UpdateLogMetricRequest], + logging_metrics.LogMetric]: r"""Return a callable for the update log metric method over gRPC. Creates or updates a logs-based metric. @@ -482,18 +455,18 @@ def update_log_metric( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_log_metric" not in self._stubs: - self._stubs["update_log_metric"] = self._logged_channel.unary_unary( - "/google.logging.v2.MetricsServiceV2/UpdateLogMetric", + if 'update_log_metric' not in self._stubs: + self._stubs['update_log_metric'] = self._logged_channel.unary_unary( + '/google.logging.v2.MetricsServiceV2/UpdateLogMetric', request_serializer=logging_metrics.UpdateLogMetricRequest.serialize, response_deserializer=logging_metrics.LogMetric.deserialize, ) - return self._stubs["update_log_metric"] + return self._stubs['update_log_metric'] @property - def delete_log_metric( - self, - ) -> Callable[[logging_metrics.DeleteLogMetricRequest], empty_pb2.Empty]: + def delete_log_metric(self) -> Callable[ + [logging_metrics.DeleteLogMetricRequest], + empty_pb2.Empty]: r"""Return a callable for the delete log metric method over gRPC. Deletes a logs-based metric. @@ -508,13 +481,13 @@ def delete_log_metric( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_log_metric" not in self._stubs: - self._stubs["delete_log_metric"] = self._logged_channel.unary_unary( - "/google.logging.v2.MetricsServiceV2/DeleteLogMetric", + if 'delete_log_metric' not in self._stubs: + self._stubs['delete_log_metric'] = self._logged_channel.unary_unary( + '/google.logging.v2.MetricsServiceV2/DeleteLogMetric', request_serializer=logging_metrics.DeleteLogMetricRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_log_metric"] + return self._stubs['delete_log_metric'] def close(self): self._logged_channel.close() @@ -523,7 +496,8 @@ def close(self): def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC.""" + r"""Return a callable for the cancel_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -540,7 +514,8 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -556,10 +531,9 @@ def get_operation( @property def list_operations( self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse - ]: - r"""Return a callable for the list_operations method over gRPC.""" + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -577,4 +551,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("MetricsServiceV2GrpcTransport",) +__all__ = ( + 'MetricsServiceV2GrpcTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py index 3424c66def78..57171bc73dd9 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -13,46 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import inspect import json import logging as std_logging import os import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings -from collections import OrderedDict -from http import HTTPStatus -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import google.protobuf +from google.cloud.redis_v1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 +from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.redis_v1 import gapic_version as package_version -from google.cloud.redis_v1._compat import ( - get_api_endpoint, - get_default_mtls_endpoint, - get_universe_domain, - read_environment_variables, - should_use_client_cert, -) -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -61,7 +44,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -75,27 +57,24 @@ _LOGGER = std_logging.getLogger(__name__) +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.redis_v1.services.cloud_redis import pagers +from google.cloud.redis_v1.types import cloud_redis +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.redis_v1.services.cloud_redis import pagers -from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore - -from .transports.base import DEFAULT_CLIENT_INFO, CloudRedisTransport +from .transports.base import CloudRedisTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CloudRedisGrpcTransport from .transports.grpc_asyncio import CloudRedisGrpcAsyncIOTransport from .transports.rest import CloudRedisRestTransport - ASYNC_REST_EXCEPTION = None try: from .transports.rest_asyncio import AsyncCloudRedisRestTransport - HAS_ASYNC_REST_DEPENDENCIES = True -except ImportError as e: # pragma: NO COVER +except ImportError as e: # pragma: NO COVER HAS_ASYNC_REST_DEPENDENCIES = False ASYNC_REST_EXCEPTION = e @@ -107,7 +86,6 @@ class CloudRedisClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[CloudRedisTransport]] _transport_registry["grpc"] = CloudRedisGrpcTransport _transport_registry["grpc_asyncio"] = CloudRedisGrpcAsyncIOTransport @@ -115,10 +93,9 @@ class CloudRedisClientMeta(type): if HAS_ASYNC_REST_DEPENDENCIES: # pragma: NO COVER _transport_registry["rest_asyncio"] = AsyncCloudRedisRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[CloudRedisTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[CloudRedisTransport]: """Returns an appropriate transport class. Args: @@ -129,9 +106,7 @@ def get_transport_class( The transport class to use. """ # If a specific transport is requested, return that one. - if ( - label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES - ): # pragma: NO COVER + if label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES: # pragma: NO COVER raise ASYNC_REST_EXCEPTION if label: return cls._transport_registry[label] @@ -203,7 +178,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CloudRedisClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -220,108 +196,73 @@ def transport(self) -> CloudRedisTransport: return self._transport @staticmethod - def instance_path( - project: str, - location: str, - instance: str, - ) -> str: + def instance_path(project: str,location: str,instance: str,) -> str: """Returns a fully-qualified instance string.""" - return "projects/{project}/locations/{location}/instances/{instance}".format( - project=project, - location=location, - instance=instance, - ) + return "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) @staticmethod - def parse_instance_path(path: str) -> Dict[str, str]: + def parse_instance_path(path: str) -> Dict[str,str]: """Parses a instance path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -353,18 +294,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -377,10 +314,8 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -419,18 +354,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -463,16 +395,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the cloud redis client. Args: @@ -530,23 +458,13 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - read_environment_variables() - ) - self._client_cert_source = CloudRedisClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = get_universe_domain( - universe_domain_opt, - self._universe_domain_env, - default_universe=CloudRedisClient._DEFAULT_UNIVERSE, - ) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() + self._client_cert_source = CloudRedisClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=CloudRedisClient._DEFAULT_UNIVERSE) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -558,9 +476,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -569,31 +485,30 @@ def __init__( if transport_provided: # transport is a CloudRedisTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = cast(CloudRedisTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = self._api_endpoint or get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=CloudRedisClient._DEFAULT_UNIVERSE, - default_mtls_endpoint=CloudRedisClient.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=CloudRedisClient._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" - or (self._use_mtls_endpoint == "auto" and self._client_cert_source), - ) + self._api_endpoint = (self._api_endpoint or + get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=CloudRedisClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=CloudRedisClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=CloudRedisClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" or ( + self._use_mtls_endpoint == "auto" and self._client_cert_source + ), + )) if not transport_provided: - transport_init: Union[ - Type[CloudRedisTransport], Callable[..., CloudRedisTransport] - ] = ( + transport_init: Union[Type[CloudRedisTransport], Callable[..., CloudRedisTransport]] = ( CloudRedisClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., CloudRedisTransport], transport) @@ -606,12 +521,9 @@ def __init__( "google.api_core.client_options.ClientOptions.quota_project_id": self._client_options.quota_project_id, "google.api_core.client_options.ClientOptions.client_cert_source": self._client_options.client_cert_source, "google.api_core.client_options.ClientOptions.api_audience": self._client_options.api_audience, + } - provided_unsupported_params = [ - name - for name, value in unsupported_params.items() - if value is not None - ] + provided_unsupported_params = [name for name, value in unsupported_params.items() if value is not None] if provided_unsupported_params: raise core_exceptions.AsyncRestUnsupportedParameterError( # type: ignore f"The following provided parameters are not supported for `transport=rest_asyncio`: {', '.join(provided_unsupported_params)}" @@ -625,12 +537,8 @@ def __init__( import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) # When OpenTelemetry tracing is enabled, pass client_options to the transport # so it can wire tracing interceptors and method spans. @@ -656,46 +564,33 @@ def __init__( "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **( - {"client_options": client_options} - if client_options is not None - else {} - ), + **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.redis_v1.CloudRedisClient`.", - extra={ + extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.cloud.redis.v1.CloudRedis", "credentialsType": None, - }, + } ) - def list_instances( - self, - request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListInstancesPager: + def list_instances(self, + request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListInstancesPager: r"""Lists all Redis instances owned by a project in either the specified location (region) or all locations. @@ -768,14 +663,10 @@ def sample_list_instances(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -793,7 +684,9 @@ def sample_list_instances(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -821,15 +714,14 @@ def sample_list_instances(): # Done; return the response. return response - def get_instance( - self, - request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_redis.Instance: + def get_instance(self, + request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.Instance: r"""Gets the details of a specific Redis instance. .. code-block:: python @@ -886,14 +778,10 @@ def sample_get_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -911,7 +799,9 @@ def sample_get_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -928,15 +818,14 @@ def sample_get_instance(): # Done; return the response. return response - def get_instance_auth_string( - self, - request: Optional[Union[cloud_redis.GetInstanceAuthStringRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_redis.InstanceAuthString: + def get_instance_auth_string(self, + request: Optional[Union[cloud_redis.GetInstanceAuthStringRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.InstanceAuthString: r"""Gets the AUTH string for a Redis instance. If AUTH is not enabled for the instance the response will be empty. This information is not included in the details returned @@ -996,14 +885,10 @@ def sample_get_instance_auth_string(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1021,7 +906,9 @@ def sample_get_instance_auth_string(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1038,17 +925,16 @@ def sample_get_instance_auth_string(): # Done; return the response. return response - def create_instance( - self, - request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, - *, - parent: Optional[str] = None, - instance_id: Optional[str] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_instance(self, + request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance_id: Optional[str] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a Redis instance based on the specified tier and memory size. @@ -1154,14 +1040,10 @@ def sample_create_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, instance_id, instance] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1183,7 +1065,9 @@ def sample_create_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1208,16 +1092,15 @@ def sample_create_instance(): # Done; return the response. return response - def update_instance( - self, - request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, - *, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_instance(self, + request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, + *, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates the metadata and configuration of a specific Redis instance. Completed longrunning.Operation will contain the new @@ -1307,14 +1190,10 @@ def sample_update_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [update_mask, instance] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1334,9 +1213,9 @@ def sample_update_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("instance.name", request.instance.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("instance.name", request.instance.name), + )), ) # Validate the universe domain. @@ -1361,16 +1240,15 @@ def sample_update_instance(): # Done; return the response. return response - def upgrade_instance( - self, - request: Optional[Union[cloud_redis.UpgradeInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - redis_version: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def upgrade_instance(self, + request: Optional[Union[cloud_redis.UpgradeInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + redis_version: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Upgrades Redis instance to the newer Redis version specified in the request. @@ -1445,14 +1323,10 @@ def sample_upgrade_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, redis_version] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1472,7 +1346,9 @@ def sample_upgrade_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1497,16 +1373,15 @@ def sample_upgrade_instance(): # Done; return the response. return response - def import_instance( - self, - request: Optional[Union[cloud_redis.ImportInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - input_config: Optional[cloud_redis.InputConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def import_instance(self, + request: Optional[Union[cloud_redis.ImportInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + input_config: Optional[cloud_redis.InputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. Redis may stop serving during this operation. Instance @@ -1591,14 +1466,10 @@ def sample_import_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, input_config] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1618,7 +1489,9 @@ def sample_import_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1643,16 +1516,15 @@ def sample_import_instance(): # Done; return the response. return response - def export_instance( - self, - request: Optional[Union[cloud_redis.ExportInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - output_config: Optional[cloud_redis.OutputConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def export_instance(self, + request: Optional[Union[cloud_redis.ExportInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + output_config: Optional[cloud_redis.OutputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Export Redis instance data into a Redis RDB format file in Cloud Storage. Redis will continue serving during this operation. @@ -1734,14 +1606,10 @@ def sample_export_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, output_config] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1761,7 +1629,9 @@ def sample_export_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1786,18 +1656,15 @@ def sample_export_instance(): # Done; return the response. return response - def failover_instance( - self, - request: Optional[Union[cloud_redis.FailoverInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - data_protection_mode: Optional[ - cloud_redis.FailoverInstanceRequest.DataProtectionMode - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def failover_instance(self, + request: Optional[Union[cloud_redis.FailoverInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + data_protection_mode: Optional[cloud_redis.FailoverInstanceRequest.DataProtectionMode] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Initiates a failover of the primary node to current replica node for a specific STANDARD tier Cloud Memorystore for Redis instance. @@ -1873,14 +1740,10 @@ def sample_failover_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, data_protection_mode] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1900,7 +1763,9 @@ def sample_failover_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1925,15 +1790,14 @@ def sample_failover_instance(): # Done; return the response. return response - def delete_instance( - self, - request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_instance(self, + request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes a specific Redis instance. Instance stops serving and data is deleted. @@ -2007,14 +1871,10 @@ def sample_delete_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2032,7 +1892,9 @@ def sample_delete_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2057,19 +1919,16 @@ def sample_delete_instance(): # Done; return the response. return response - def reschedule_maintenance( - self, - request: Optional[Union[cloud_redis.RescheduleMaintenanceRequest, dict]] = None, - *, - name: Optional[str] = None, - reschedule_type: Optional[ - cloud_redis.RescheduleMaintenanceRequest.RescheduleType - ] = None, - schedule_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def reschedule_maintenance(self, + request: Optional[Union[cloud_redis.RescheduleMaintenanceRequest, dict]] = None, + *, + name: Optional[str] = None, + reschedule_type: Optional[cloud_redis.RescheduleMaintenanceRequest.RescheduleType] = None, + schedule_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Reschedule maintenance for a given instance in a given project and location. @@ -2152,14 +2011,10 @@ def sample_reschedule_maintenance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, reschedule_type, schedule_time] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2181,7 +2036,9 @@ def sample_reschedule_maintenance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2261,7 +2118,8 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2270,11 +2128,7 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -2324,7 +2178,8 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2333,11 +2188,7 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -2391,19 +2242,15 @@ def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def cancel_operation( self, @@ -2450,19 +2297,15 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def wait_operation( self, @@ -2512,7 +2355,8 @@ def wait_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2521,11 +2365,7 @@ def wait_operation( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -2575,7 +2415,8 @@ def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2584,11 +2425,7 @@ def get_location( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -2638,7 +2475,8 @@ def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -2647,11 +2485,7 @@ def list_locations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -2660,9 +2494,9 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("CloudRedisClient",) +__all__ = ( + "CloudRedisClient", +) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py index 4e35e31a04f6..427dd8e5c7b6 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -17,23 +17,24 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import google.api_core +from google.cloud.redis_v1 import gapic_version as package_version + import google.auth # type: ignore -import google.protobuf +import google.api_core from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.redis_v1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.location import locations_pb2 # type: ignore from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.longrunning import operations_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ # Check once at module load time whether google-api-core's wrap_method supports @@ -47,24 +48,25 @@ class CloudRedisTransport(abc.ABC): """Abstract transport class for CloudRedis.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) - DEFAULT_HOST: str = "redis.googleapis.com" + DEFAULT_HOST: str = 'redis.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -106,43 +108,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host self._client_options = client_options @@ -169,12 +159,7 @@ def _wrap_method(self, func, *args, **kwargs): # of google-api-core is installed (which does not accept client_options, etc.). # Excluded from coverage because our CI and testing environments always install # a modern version of google-api-core that supports tracing. - for k in [ - "client_options", - "method_name", - "is_streaming", - "kind", - ]: # pragma: NO COVER + for k in ["client_options", "method_name", "is_streaming", "kind"]: # pragma: NO COVER kwargs.pop(k, None) # pragma: NO COVER return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER @@ -282,14 +267,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -299,107 +284,102 @@ def operations_client(self): raise NotImplementedError() @property - def list_instances( - self, - ) -> Callable[ - [cloud_redis.ListInstancesRequest], - Union[ - cloud_redis.ListInstancesResponse, - Awaitable[cloud_redis.ListInstancesResponse], - ], - ]: + def list_instances(self) -> Callable[ + [cloud_redis.ListInstancesRequest], + Union[ + cloud_redis.ListInstancesResponse, + Awaitable[cloud_redis.ListInstancesResponse] + ]]: raise NotImplementedError() @property - def get_instance( - self, - ) -> Callable[ - [cloud_redis.GetInstanceRequest], - Union[cloud_redis.Instance, Awaitable[cloud_redis.Instance]], - ]: + def get_instance(self) -> Callable[ + [cloud_redis.GetInstanceRequest], + Union[ + cloud_redis.Instance, + Awaitable[cloud_redis.Instance] + ]]: raise NotImplementedError() @property - def get_instance_auth_string( - self, - ) -> Callable[ - [cloud_redis.GetInstanceAuthStringRequest], - Union[ - cloud_redis.InstanceAuthString, Awaitable[cloud_redis.InstanceAuthString] - ], - ]: + def get_instance_auth_string(self) -> Callable[ + [cloud_redis.GetInstanceAuthStringRequest], + Union[ + cloud_redis.InstanceAuthString, + Awaitable[cloud_redis.InstanceAuthString] + ]]: raise NotImplementedError() @property - def create_instance( - self, - ) -> Callable[ - [cloud_redis.CreateInstanceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_instance(self) -> Callable[ + [cloud_redis.CreateInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def update_instance( - self, - ) -> Callable[ - [cloud_redis.UpdateInstanceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def update_instance(self) -> Callable[ + [cloud_redis.UpdateInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def upgrade_instance( - self, - ) -> Callable[ - [cloud_redis.UpgradeInstanceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def upgrade_instance(self) -> Callable[ + [cloud_redis.UpgradeInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def import_instance( - self, - ) -> Callable[ - [cloud_redis.ImportInstanceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def import_instance(self) -> Callable[ + [cloud_redis.ImportInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def export_instance( - self, - ) -> Callable[ - [cloud_redis.ExportInstanceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def export_instance(self) -> Callable[ + [cloud_redis.ExportInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def failover_instance( - self, - ) -> Callable[ - [cloud_redis.FailoverInstanceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def failover_instance(self) -> Callable[ + [cloud_redis.FailoverInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def delete_instance( - self, - ) -> Callable[ - [cloud_redis.DeleteInstanceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def delete_instance(self) -> Callable[ + [cloud_redis.DeleteInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def reschedule_maintenance( - self, - ) -> Callable[ - [cloud_redis.RescheduleMaintenanceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def reschedule_maintenance(self) -> Callable[ + [cloud_redis.RescheduleMaintenanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property @@ -407,10 +387,7 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[ - operations_pb2.ListOperationsResponse, - Awaitable[operations_pb2.ListOperationsResponse], - ], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], ]: raise NotImplementedError() @@ -451,8 +428,7 @@ def wait_operation( raise NotImplementedError() @property - def get_location( - self, + def get_location(self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -460,14 +436,10 @@ def get_location( raise NotImplementedError() @property - def list_locations( - self, + def list_locations(self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[ - locations_pb2.ListLocationsResponse, - Awaitable[locations_pb2.ListLocationsResponse], - ], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], ]: raise NotImplementedError() @@ -476,4 +448,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("CloudRedisTransport",) +__all__ = ( + 'CloudRedisTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index 6850f12fd7bc..c337eb6c75a9 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -17,19 +17,17 @@ import logging as std_logging import pickle import warnings -from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ( - ClientInterceptor, # type: ignore[attr-defined] - ) + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1, operations_v1 - +from google.api_core import gapic_v1 # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -37,21 +35,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore -import google.protobuf.message -import proto # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message -from .base import DEFAULT_CLIENT_INFO, CloudRedisTransport +import proto # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.redis_v1.types import cloud_redis +from google.longrunning import operations_pb2 # type: ignore +from .base import CloudRedisTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -61,9 +59,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -84,7 +80,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -95,11 +91,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -114,7 +106,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": client_call_details.method, "response": grpc_response, @@ -156,35 +148,32 @@ class CloudRedisGrpcTransport(CloudRedisTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "redis.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], + def __init__(self, *, + host: str = 'redis.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], + ] ] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -321,17 +310,9 @@ def __init__( channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) - ) - is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None and otel_interceptor not in channel_interceptors - and not any( - getattr(i, "_is_otel_interceptor", None) is True - for i in channel_interceptors - ) + and not any(getattr(i, "_is_otel_interceptor", None) is True for i in channel_interceptors) ): channel_interceptors.append(otel_interceptor) @@ -340,28 +321,22 @@ def __init__( "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors( - self._grpc_channel, channel_interceptors - ) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "redis.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'redis.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -397,12 +372,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -422,11 +398,9 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def list_instances( - self, - ) -> Callable[ - [cloud_redis.ListInstancesRequest], cloud_redis.ListInstancesResponse - ]: + def list_instances(self) -> Callable[ + [cloud_redis.ListInstancesRequest], + cloud_redis.ListInstancesResponse]: r"""Return a callable for the list instances method over gRPC. Lists all Redis instances owned by a project in either the @@ -450,18 +424,18 @@ def list_instances( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_instances" not in self._stubs: - self._stubs["list_instances"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/ListInstances", + if 'list_instances' not in self._stubs: + self._stubs['list_instances'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/ListInstances', request_serializer=cloud_redis.ListInstancesRequest.serialize, response_deserializer=cloud_redis.ListInstancesResponse.deserialize, ) - return self._stubs["list_instances"] + return self._stubs['list_instances'] @property - def get_instance( - self, - ) -> Callable[[cloud_redis.GetInstanceRequest], cloud_redis.Instance]: + def get_instance(self) -> Callable[ + [cloud_redis.GetInstanceRequest], + cloud_redis.Instance]: r"""Return a callable for the get instance method over gRPC. Gets the details of a specific Redis instance. @@ -476,20 +450,18 @@ def get_instance( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_instance" not in self._stubs: - self._stubs["get_instance"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/GetInstance", + if 'get_instance' not in self._stubs: + self._stubs['get_instance'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/GetInstance', request_serializer=cloud_redis.GetInstanceRequest.serialize, response_deserializer=cloud_redis.Instance.deserialize, ) - return self._stubs["get_instance"] + return self._stubs['get_instance'] @property - def get_instance_auth_string( - self, - ) -> Callable[ - [cloud_redis.GetInstanceAuthStringRequest], cloud_redis.InstanceAuthString - ]: + def get_instance_auth_string(self) -> Callable[ + [cloud_redis.GetInstanceAuthStringRequest], + cloud_redis.InstanceAuthString]: r"""Return a callable for the get instance auth string method over gRPC. Gets the AUTH string for a Redis instance. If AUTH is @@ -507,18 +479,18 @@ def get_instance_auth_string( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_instance_auth_string" not in self._stubs: - self._stubs["get_instance_auth_string"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/GetInstanceAuthString", + if 'get_instance_auth_string' not in self._stubs: + self._stubs['get_instance_auth_string'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/GetInstanceAuthString', request_serializer=cloud_redis.GetInstanceAuthStringRequest.serialize, response_deserializer=cloud_redis.InstanceAuthString.deserialize, ) - return self._stubs["get_instance_auth_string"] + return self._stubs['get_instance_auth_string'] @property - def create_instance( - self, - ) -> Callable[[cloud_redis.CreateInstanceRequest], operations_pb2.Operation]: + def create_instance(self) -> Callable[ + [cloud_redis.CreateInstanceRequest], + operations_pb2.Operation]: r"""Return a callable for the create instance method over gRPC. Creates a Redis instance based on the specified tier and memory @@ -546,18 +518,18 @@ def create_instance( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_instance" not in self._stubs: - self._stubs["create_instance"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/CreateInstance", + if 'create_instance' not in self._stubs: + self._stubs['create_instance'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/CreateInstance', request_serializer=cloud_redis.CreateInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_instance"] + return self._stubs['create_instance'] @property - def update_instance( - self, - ) -> Callable[[cloud_redis.UpdateInstanceRequest], operations_pb2.Operation]: + def update_instance(self) -> Callable[ + [cloud_redis.UpdateInstanceRequest], + operations_pb2.Operation]: r"""Return a callable for the update instance method over gRPC. Updates the metadata and configuration of a specific @@ -577,18 +549,18 @@ def update_instance( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_instance" not in self._stubs: - self._stubs["update_instance"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/UpdateInstance", + if 'update_instance' not in self._stubs: + self._stubs['update_instance'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/UpdateInstance', request_serializer=cloud_redis.UpdateInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["update_instance"] + return self._stubs['update_instance'] @property - def upgrade_instance( - self, - ) -> Callable[[cloud_redis.UpgradeInstanceRequest], operations_pb2.Operation]: + def upgrade_instance(self) -> Callable[ + [cloud_redis.UpgradeInstanceRequest], + operations_pb2.Operation]: r"""Return a callable for the upgrade instance method over gRPC. Upgrades Redis instance to the newer Redis version @@ -604,18 +576,18 @@ def upgrade_instance( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "upgrade_instance" not in self._stubs: - self._stubs["upgrade_instance"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/UpgradeInstance", + if 'upgrade_instance' not in self._stubs: + self._stubs['upgrade_instance'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/UpgradeInstance', request_serializer=cloud_redis.UpgradeInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["upgrade_instance"] + return self._stubs['upgrade_instance'] @property - def import_instance( - self, - ) -> Callable[[cloud_redis.ImportInstanceRequest], operations_pb2.Operation]: + def import_instance(self) -> Callable[ + [cloud_redis.ImportInstanceRequest], + operations_pb2.Operation]: r"""Return a callable for the import instance method over gRPC. Import a Redis RDB snapshot file from Cloud Storage @@ -638,18 +610,18 @@ def import_instance( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "import_instance" not in self._stubs: - self._stubs["import_instance"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/ImportInstance", + if 'import_instance' not in self._stubs: + self._stubs['import_instance'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/ImportInstance', request_serializer=cloud_redis.ImportInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["import_instance"] + return self._stubs['import_instance'] @property - def export_instance( - self, - ) -> Callable[[cloud_redis.ExportInstanceRequest], operations_pb2.Operation]: + def export_instance(self) -> Callable[ + [cloud_redis.ExportInstanceRequest], + operations_pb2.Operation]: r"""Return a callable for the export instance method over gRPC. Export Redis instance data into a Redis RDB format @@ -669,18 +641,18 @@ def export_instance( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "export_instance" not in self._stubs: - self._stubs["export_instance"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/ExportInstance", + if 'export_instance' not in self._stubs: + self._stubs['export_instance'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/ExportInstance', request_serializer=cloud_redis.ExportInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["export_instance"] + return self._stubs['export_instance'] @property - def failover_instance( - self, - ) -> Callable[[cloud_redis.FailoverInstanceRequest], operations_pb2.Operation]: + def failover_instance(self) -> Callable[ + [cloud_redis.FailoverInstanceRequest], + operations_pb2.Operation]: r"""Return a callable for the failover instance method over gRPC. Initiates a failover of the primary node to current @@ -697,18 +669,18 @@ def failover_instance( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "failover_instance" not in self._stubs: - self._stubs["failover_instance"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/FailoverInstance", + if 'failover_instance' not in self._stubs: + self._stubs['failover_instance'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/FailoverInstance', request_serializer=cloud_redis.FailoverInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["failover_instance"] + return self._stubs['failover_instance'] @property - def delete_instance( - self, - ) -> Callable[[cloud_redis.DeleteInstanceRequest], operations_pb2.Operation]: + def delete_instance(self) -> Callable[ + [cloud_redis.DeleteInstanceRequest], + operations_pb2.Operation]: r"""Return a callable for the delete instance method over gRPC. Deletes a specific Redis instance. Instance stops @@ -724,18 +696,18 @@ def delete_instance( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_instance" not in self._stubs: - self._stubs["delete_instance"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/DeleteInstance", + if 'delete_instance' not in self._stubs: + self._stubs['delete_instance'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/DeleteInstance', request_serializer=cloud_redis.DeleteInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["delete_instance"] + return self._stubs['delete_instance'] @property - def reschedule_maintenance( - self, - ) -> Callable[[cloud_redis.RescheduleMaintenanceRequest], operations_pb2.Operation]: + def reschedule_maintenance(self) -> Callable[ + [cloud_redis.RescheduleMaintenanceRequest], + operations_pb2.Operation]: r"""Return a callable for the reschedule maintenance method over gRPC. Reschedule maintenance for a given instance in a @@ -751,13 +723,13 @@ def reschedule_maintenance( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "reschedule_maintenance" not in self._stubs: - self._stubs["reschedule_maintenance"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/RescheduleMaintenance", + if 'reschedule_maintenance' not in self._stubs: + self._stubs['reschedule_maintenance'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/RescheduleMaintenance', request_serializer=cloud_redis.RescheduleMaintenanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["reschedule_maintenance"] + return self._stubs['reschedule_maintenance'] def close(self): self._logged_channel.close() @@ -766,7 +738,8 @@ def close(self): def delete_operation( self, ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC.""" + r"""Return a callable for the delete_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -783,7 +756,8 @@ def delete_operation( def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC.""" + r"""Return a callable for the cancel_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -800,7 +774,8 @@ def cancel_operation( def wait_operation( self, ) -> Callable[[operations_pb2.WaitOperationRequest], None]: - r"""Return a callable for the wait_operation method over gRPC.""" + r"""Return a callable for the wait_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -817,7 +792,8 @@ def wait_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -833,10 +809,9 @@ def get_operation( @property def list_operations( self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse - ]: - r"""Return a callable for the list_operations method over gRPC.""" + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -852,10 +827,9 @@ def list_operations( @property def list_locations( self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse - ]: - r"""Return a callable for the list locations method over gRPC.""" + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -872,7 +846,8 @@ def list_locations( def get_location( self, ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC.""" + r"""Return a callable for the list locations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -890,4 +865,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("CloudRedisGrpcTransport",) +__all__ = ( + 'CloudRedisGrpcTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py index b8f416d64e8d..00cee860fecc 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py @@ -13,46 +13,29 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import inspect import json import logging as std_logging import os import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings -from collections import OrderedDict -from http import HTTPStatus -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import google.protobuf +from google.cloud.redis_v1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 +from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.redis_v1 import gapic_version as package_version -from google.cloud.redis_v1._compat import ( - get_api_endpoint, - get_default_mtls_endpoint, - get_universe_domain, - read_environment_variables, - should_use_client_cert, -) -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -61,7 +44,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -75,27 +57,24 @@ _LOGGER = std_logging.getLogger(__name__) +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.redis_v1.services.cloud_redis import pagers +from google.cloud.redis_v1.types import cloud_redis +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.redis_v1.services.cloud_redis import pagers -from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore - -from .transports.base import DEFAULT_CLIENT_INFO, CloudRedisTransport +from .transports.base import CloudRedisTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CloudRedisGrpcTransport from .transports.grpc_asyncio import CloudRedisGrpcAsyncIOTransport from .transports.rest import CloudRedisRestTransport - ASYNC_REST_EXCEPTION = None try: from .transports.rest_asyncio import AsyncCloudRedisRestTransport - HAS_ASYNC_REST_DEPENDENCIES = True -except ImportError as e: # pragma: NO COVER +except ImportError as e: # pragma: NO COVER HAS_ASYNC_REST_DEPENDENCIES = False ASYNC_REST_EXCEPTION = e @@ -107,7 +86,6 @@ class CloudRedisClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[CloudRedisTransport]] _transport_registry["grpc"] = CloudRedisGrpcTransport _transport_registry["grpc_asyncio"] = CloudRedisGrpcAsyncIOTransport @@ -115,10 +93,9 @@ class CloudRedisClientMeta(type): if HAS_ASYNC_REST_DEPENDENCIES: # pragma: NO COVER _transport_registry["rest_asyncio"] = AsyncCloudRedisRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[CloudRedisTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[CloudRedisTransport]: """Returns an appropriate transport class. Args: @@ -129,9 +106,7 @@ def get_transport_class( The transport class to use. """ # If a specific transport is requested, return that one. - if ( - label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES - ): # pragma: NO COVER + if label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES: # pragma: NO COVER raise ASYNC_REST_EXCEPTION if label: return cls._transport_registry[label] @@ -203,7 +178,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CloudRedisClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -220,108 +196,73 @@ def transport(self) -> CloudRedisTransport: return self._transport @staticmethod - def instance_path( - project: str, - location: str, - instance: str, - ) -> str: + def instance_path(project: str,location: str,instance: str,) -> str: """Returns a fully-qualified instance string.""" - return "projects/{project}/locations/{location}/instances/{instance}".format( - project=project, - location=location, - instance=instance, - ) + return "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) @staticmethod - def parse_instance_path(path: str) -> Dict[str, str]: + def parse_instance_path(path: str) -> Dict[str,str]: """Parses a instance path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -353,18 +294,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -377,10 +314,8 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -419,18 +354,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -463,16 +395,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the cloud redis client. Args: @@ -530,23 +458,13 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - read_environment_variables() - ) - self._client_cert_source = CloudRedisClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = get_universe_domain( - universe_domain_opt, - self._universe_domain_env, - default_universe=CloudRedisClient._DEFAULT_UNIVERSE, - ) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() + self._client_cert_source = CloudRedisClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=CloudRedisClient._DEFAULT_UNIVERSE) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -558,9 +476,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -569,31 +485,30 @@ def __init__( if transport_provided: # transport is a CloudRedisTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = cast(CloudRedisTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = self._api_endpoint or get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=CloudRedisClient._DEFAULT_UNIVERSE, - default_mtls_endpoint=CloudRedisClient.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=CloudRedisClient._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" - or (self._use_mtls_endpoint == "auto" and self._client_cert_source), - ) + self._api_endpoint = (self._api_endpoint or + get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=CloudRedisClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=CloudRedisClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=CloudRedisClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" or ( + self._use_mtls_endpoint == "auto" and self._client_cert_source + ), + )) if not transport_provided: - transport_init: Union[ - Type[CloudRedisTransport], Callable[..., CloudRedisTransport] - ] = ( + transport_init: Union[Type[CloudRedisTransport], Callable[..., CloudRedisTransport]] = ( CloudRedisClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., CloudRedisTransport], transport) @@ -606,12 +521,9 @@ def __init__( "google.api_core.client_options.ClientOptions.quota_project_id": self._client_options.quota_project_id, "google.api_core.client_options.ClientOptions.client_cert_source": self._client_options.client_cert_source, "google.api_core.client_options.ClientOptions.api_audience": self._client_options.api_audience, + } - provided_unsupported_params = [ - name - for name, value in unsupported_params.items() - if value is not None - ] + provided_unsupported_params = [name for name, value in unsupported_params.items() if value is not None] if provided_unsupported_params: raise core_exceptions.AsyncRestUnsupportedParameterError( # type: ignore f"The following provided parameters are not supported for `transport=rest_asyncio`: {', '.join(provided_unsupported_params)}" @@ -625,12 +537,8 @@ def __init__( import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) # When OpenTelemetry tracing is enabled, pass client_options to the transport # so it can wire tracing interceptors and method spans. @@ -656,46 +564,33 @@ def __init__( "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **( - {"client_options": client_options} - if client_options is not None - else {} - ), + **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.redis_v1.CloudRedisClient`.", - extra={ + extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.cloud.redis.v1.CloudRedis", "credentialsType": None, - }, + } ) - def list_instances( - self, - request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListInstancesPager: + def list_instances(self, + request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListInstancesPager: r"""Lists all Redis instances owned by a project in either the specified location (region) or all locations. @@ -768,14 +663,10 @@ def sample_list_instances(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -793,7 +684,9 @@ def sample_list_instances(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -821,15 +714,14 @@ def sample_list_instances(): # Done; return the response. return response - def get_instance( - self, - request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_redis.Instance: + def get_instance(self, + request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.Instance: r"""Gets the details of a specific Redis instance. .. code-block:: python @@ -886,14 +778,10 @@ def sample_get_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -911,7 +799,9 @@ def sample_get_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -928,17 +818,16 @@ def sample_get_instance(): # Done; return the response. return response - def create_instance( - self, - request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, - *, - parent: Optional[str] = None, - instance_id: Optional[str] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_instance(self, + request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance_id: Optional[str] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a Redis instance based on the specified tier and memory size. @@ -1044,14 +933,10 @@ def sample_create_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, instance_id, instance] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1073,7 +958,9 @@ def sample_create_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1098,16 +985,15 @@ def sample_create_instance(): # Done; return the response. return response - def update_instance( - self, - request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, - *, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_instance(self, + request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, + *, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates the metadata and configuration of a specific Redis instance. Completed longrunning.Operation will contain the new @@ -1197,14 +1083,10 @@ def sample_update_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [update_mask, instance] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1224,9 +1106,9 @@ def sample_update_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("instance.name", request.instance.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("instance.name", request.instance.name), + )), ) # Validate the universe domain. @@ -1251,15 +1133,14 @@ def sample_update_instance(): # Done; return the response. return response - def delete_instance( - self, - request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_instance(self, + request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes a specific Redis instance. Instance stops serving and data is deleted. @@ -1333,14 +1214,10 @@ def sample_delete_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1358,7 +1235,9 @@ def sample_delete_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1438,7 +1317,8 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1447,11 +1327,7 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1501,7 +1377,8 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1510,11 +1387,7 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1568,19 +1441,15 @@ def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def cancel_operation( self, @@ -1627,19 +1496,15 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def wait_operation( self, @@ -1689,7 +1554,8 @@ def wait_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1698,11 +1564,7 @@ def wait_operation( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1752,7 +1614,8 @@ def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1761,11 +1624,7 @@ def get_location( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1815,7 +1674,8 @@ def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1824,11 +1684,7 @@ def list_locations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1837,9 +1693,9 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("CloudRedisClient",) +__all__ = ( + "CloudRedisClient", +) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py index fb2d6e770f83..644738588d8f 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -17,23 +17,24 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import google.api_core +from google.cloud.redis_v1 import gapic_version as package_version + import google.auth # type: ignore -import google.protobuf +import google.api_core from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.redis_v1 import gapic_version as package_version +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.location import locations_pb2 # type: ignore from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.longrunning import operations_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ # Check once at module load time whether google-api-core's wrap_method supports @@ -47,24 +48,25 @@ class CloudRedisTransport(abc.ABC): """Abstract transport class for CloudRedis.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) - DEFAULT_HOST: str = "redis.googleapis.com" + DEFAULT_HOST: str = 'redis.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -106,43 +108,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host self._client_options = client_options @@ -169,12 +159,7 @@ def _wrap_method(self, func, *args, **kwargs): # of google-api-core is installed (which does not accept client_options, etc.). # Excluded from coverage because our CI and testing environments always install # a modern version of google-api-core that supports tracing. - for k in [ - "client_options", - "method_name", - "is_streaming", - "kind", - ]: # pragma: NO COVER + for k in ["client_options", "method_name", "is_streaming", "kind"]: # pragma: NO COVER kwargs.pop(k, None) # pragma: NO COVER return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER @@ -246,14 +231,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -263,51 +248,48 @@ def operations_client(self): raise NotImplementedError() @property - def list_instances( - self, - ) -> Callable[ - [cloud_redis.ListInstancesRequest], - Union[ - cloud_redis.ListInstancesResponse, - Awaitable[cloud_redis.ListInstancesResponse], - ], - ]: + def list_instances(self) -> Callable[ + [cloud_redis.ListInstancesRequest], + Union[ + cloud_redis.ListInstancesResponse, + Awaitable[cloud_redis.ListInstancesResponse] + ]]: raise NotImplementedError() @property - def get_instance( - self, - ) -> Callable[ - [cloud_redis.GetInstanceRequest], - Union[cloud_redis.Instance, Awaitable[cloud_redis.Instance]], - ]: + def get_instance(self) -> Callable[ + [cloud_redis.GetInstanceRequest], + Union[ + cloud_redis.Instance, + Awaitable[cloud_redis.Instance] + ]]: raise NotImplementedError() @property - def create_instance( - self, - ) -> Callable[ - [cloud_redis.CreateInstanceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_instance(self) -> Callable[ + [cloud_redis.CreateInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def update_instance( - self, - ) -> Callable[ - [cloud_redis.UpdateInstanceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def update_instance(self) -> Callable[ + [cloud_redis.UpdateInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def delete_instance( - self, - ) -> Callable[ - [cloud_redis.DeleteInstanceRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def delete_instance(self) -> Callable[ + [cloud_redis.DeleteInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property @@ -315,10 +297,7 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[ - operations_pb2.ListOperationsResponse, - Awaitable[operations_pb2.ListOperationsResponse], - ], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], ]: raise NotImplementedError() @@ -359,8 +338,7 @@ def wait_operation( raise NotImplementedError() @property - def get_location( - self, + def get_location(self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -368,14 +346,10 @@ def get_location( raise NotImplementedError() @property - def list_locations( - self, + def list_locations(self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[ - locations_pb2.ListLocationsResponse, - Awaitable[locations_pb2.ListLocationsResponse], - ], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], ]: raise NotImplementedError() @@ -384,4 +358,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("CloudRedisTransport",) +__all__ = ( + 'CloudRedisTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py index 3af833da0007..f17d519b5563 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/grpc.py @@ -17,19 +17,17 @@ import logging as std_logging import pickle import warnings -from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ( - ClientInterceptor, # type: ignore[attr-defined] - ) + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1, operations_v1 - +from google.api_core import gapic_v1 # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -37,21 +35,21 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore -import google.protobuf.message -import proto # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import proto # type: ignore -from .base import DEFAULT_CLIENT_INFO, CloudRedisTransport +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.redis_v1.types import cloud_redis +from google.longrunning import operations_pb2 # type: ignore +from .base import CloudRedisTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -61,9 +59,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -84,7 +80,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -95,11 +91,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -114,7 +106,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": client_call_details.method, "response": grpc_response, @@ -156,35 +148,32 @@ class CloudRedisGrpcTransport(CloudRedisTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "redis.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], + def __init__(self, *, + host: str = 'redis.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], + ] ] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -321,17 +310,9 @@ def __init__( channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) - ) - is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None and otel_interceptor not in channel_interceptors - and not any( - getattr(i, "_is_otel_interceptor", None) is True - for i in channel_interceptors - ) + and not any(getattr(i, "_is_otel_interceptor", None) is True for i in channel_interceptors) ): channel_interceptors.append(otel_interceptor) @@ -340,28 +321,22 @@ def __init__( "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors( - self._grpc_channel, channel_interceptors - ) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "redis.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'redis.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -397,12 +372,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -422,11 +398,9 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def list_instances( - self, - ) -> Callable[ - [cloud_redis.ListInstancesRequest], cloud_redis.ListInstancesResponse - ]: + def list_instances(self) -> Callable[ + [cloud_redis.ListInstancesRequest], + cloud_redis.ListInstancesResponse]: r"""Return a callable for the list instances method over gRPC. Lists all Redis instances owned by a project in either the @@ -450,18 +424,18 @@ def list_instances( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_instances" not in self._stubs: - self._stubs["list_instances"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/ListInstances", + if 'list_instances' not in self._stubs: + self._stubs['list_instances'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/ListInstances', request_serializer=cloud_redis.ListInstancesRequest.serialize, response_deserializer=cloud_redis.ListInstancesResponse.deserialize, ) - return self._stubs["list_instances"] + return self._stubs['list_instances'] @property - def get_instance( - self, - ) -> Callable[[cloud_redis.GetInstanceRequest], cloud_redis.Instance]: + def get_instance(self) -> Callable[ + [cloud_redis.GetInstanceRequest], + cloud_redis.Instance]: r"""Return a callable for the get instance method over gRPC. Gets the details of a specific Redis instance. @@ -476,18 +450,18 @@ def get_instance( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_instance" not in self._stubs: - self._stubs["get_instance"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/GetInstance", + if 'get_instance' not in self._stubs: + self._stubs['get_instance'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/GetInstance', request_serializer=cloud_redis.GetInstanceRequest.serialize, response_deserializer=cloud_redis.Instance.deserialize, ) - return self._stubs["get_instance"] + return self._stubs['get_instance'] @property - def create_instance( - self, - ) -> Callable[[cloud_redis.CreateInstanceRequest], operations_pb2.Operation]: + def create_instance(self) -> Callable[ + [cloud_redis.CreateInstanceRequest], + operations_pb2.Operation]: r"""Return a callable for the create instance method over gRPC. Creates a Redis instance based on the specified tier and memory @@ -515,18 +489,18 @@ def create_instance( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_instance" not in self._stubs: - self._stubs["create_instance"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/CreateInstance", + if 'create_instance' not in self._stubs: + self._stubs['create_instance'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/CreateInstance', request_serializer=cloud_redis.CreateInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_instance"] + return self._stubs['create_instance'] @property - def update_instance( - self, - ) -> Callable[[cloud_redis.UpdateInstanceRequest], operations_pb2.Operation]: + def update_instance(self) -> Callable[ + [cloud_redis.UpdateInstanceRequest], + operations_pb2.Operation]: r"""Return a callable for the update instance method over gRPC. Updates the metadata and configuration of a specific @@ -546,18 +520,18 @@ def update_instance( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_instance" not in self._stubs: - self._stubs["update_instance"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/UpdateInstance", + if 'update_instance' not in self._stubs: + self._stubs['update_instance'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/UpdateInstance', request_serializer=cloud_redis.UpdateInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["update_instance"] + return self._stubs['update_instance'] @property - def delete_instance( - self, - ) -> Callable[[cloud_redis.DeleteInstanceRequest], operations_pb2.Operation]: + def delete_instance(self) -> Callable[ + [cloud_redis.DeleteInstanceRequest], + operations_pb2.Operation]: r"""Return a callable for the delete instance method over gRPC. Deletes a specific Redis instance. Instance stops @@ -573,13 +547,13 @@ def delete_instance( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_instance" not in self._stubs: - self._stubs["delete_instance"] = self._logged_channel.unary_unary( - "/google.cloud.redis.v1.CloudRedis/DeleteInstance", + if 'delete_instance' not in self._stubs: + self._stubs['delete_instance'] = self._logged_channel.unary_unary( + '/google.cloud.redis.v1.CloudRedis/DeleteInstance', request_serializer=cloud_redis.DeleteInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["delete_instance"] + return self._stubs['delete_instance'] def close(self): self._logged_channel.close() @@ -588,7 +562,8 @@ def close(self): def delete_operation( self, ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC.""" + r"""Return a callable for the delete_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -605,7 +580,8 @@ def delete_operation( def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC.""" + r"""Return a callable for the cancel_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -622,7 +598,8 @@ def cancel_operation( def wait_operation( self, ) -> Callable[[operations_pb2.WaitOperationRequest], None]: - r"""Return a callable for the wait_operation method over gRPC.""" + r"""Return a callable for the wait_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -639,7 +616,8 @@ def wait_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -655,10 +633,9 @@ def get_operation( @property def list_operations( self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse - ]: - r"""Return a callable for the list_operations method over gRPC.""" + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -674,10 +651,9 @@ def list_operations( @property def list_locations( self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse - ]: - r"""Return a callable for the list locations method over gRPC.""" + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -694,7 +670,8 @@ def list_locations( def get_location( self, ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC.""" + r"""Return a callable for the list locations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -712,4 +689,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("CloudRedisGrpcTransport",) +__all__ = ( + 'CloudRedisGrpcTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py index 4ef4e9304d0e..1e22b8de746f 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py @@ -13,48 +13,31 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import inspect import json import logging as std_logging import os import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import uuid import warnings -from collections import OrderedDict -from http import HTTPStatus -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import google.protobuf +from google.cloud.storagebatchoperations_v1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 +from google.cloud.storagebatchoperations_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.storagebatchoperations_v1._compat import setup_request_id from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.storagebatchoperations_v1 import gapic_version as package_version -from google.cloud.storagebatchoperations_v1._compat import ( - get_api_endpoint, - get_default_mtls_endpoint, - get_universe_domain, - read_environment_variables, - setup_request_id, - should_use_client_cert, -) -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -63,7 +46,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -77,20 +59,15 @@ _LOGGER = std_logging.getLogger(__name__) +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.storagebatchoperations_v1.services.storage_batch_operations import pagers +from google.cloud.storagebatchoperations_v1.types import storage_batch_operations +from google.cloud.storagebatchoperations_v1.types import storage_batch_operations_types +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.storagebatchoperations_v1.services.storage_batch_operations import ( - pagers, -) -from google.cloud.storagebatchoperations_v1.types import ( - storage_batch_operations, - storage_batch_operations_types, -) -from google.longrunning import operations_pb2 # type: ignore - -from .transports.base import DEFAULT_CLIENT_INFO, StorageBatchOperationsTransport +from .transports.base import StorageBatchOperationsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import StorageBatchOperationsGrpcTransport from .transports.grpc_asyncio import StorageBatchOperationsGrpcAsyncIOTransport from .transports.rest import StorageBatchOperationsRestTransport @@ -103,16 +80,14 @@ class StorageBatchOperationsClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[StorageBatchOperationsTransport]] _transport_registry["grpc"] = StorageBatchOperationsGrpcTransport _transport_registry["grpc_asyncio"] = StorageBatchOperationsGrpcAsyncIOTransport _transport_registry["rest"] = StorageBatchOperationsRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[StorageBatchOperationsTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[StorageBatchOperationsTransport]: """Returns an appropriate transport class. Args: @@ -177,7 +152,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: StorageBatchOperationsClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -194,156 +170,95 @@ def transport(self) -> StorageBatchOperationsTransport: return self._transport @staticmethod - def bucket_operation_path( - project: str, - location: str, - job: str, - bucket_operation: str, - ) -> str: + def bucket_operation_path(project: str,location: str,job: str,bucket_operation: str,) -> str: """Returns a fully-qualified bucket_operation string.""" - return "projects/{project}/locations/{location}/jobs/{job}/bucketOperations/{bucket_operation}".format( - project=project, - location=location, - job=job, - bucket_operation=bucket_operation, - ) + return "projects/{project}/locations/{location}/jobs/{job}/bucketOperations/{bucket_operation}".format(project=project, location=location, job=job, bucket_operation=bucket_operation, ) @staticmethod - def parse_bucket_operation_path(path: str) -> Dict[str, str]: + def parse_bucket_operation_path(path: str) -> Dict[str,str]: """Parses a bucket_operation path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)/bucketOperations/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)/bucketOperations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def crypto_key_path( - project: str, - location: str, - key_ring: str, - crypto_key: str, - ) -> str: + def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( - project=project, - location=location, - key_ring=key_ring, - crypto_key=crypto_key, - ) + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str, str]: + def parse_crypto_key_path(path: str) -> Dict[str,str]: """Parses a crypto_key path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def job_path( - project: str, - location: str, - job: str, - ) -> str: + def job_path(project: str,location: str,job: str,) -> str: """Returns a fully-qualified job string.""" - return "projects/{project}/locations/{location}/jobs/{job}".format( - project=project, - location=location, - job=job, - ) + return "projects/{project}/locations/{location}/jobs/{job}".format(project=project, location=location, job=job, ) @staticmethod - def parse_job_path(path: str) -> Dict[str, str]: + def parse_job_path(path: str) -> Dict[str,str]: """Parses a job path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -375,18 +290,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = should_use_client_cert() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -399,10 +310,8 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -441,18 +350,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -485,20 +391,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[ - str, - StorageBatchOperationsTransport, - Callable[..., StorageBatchOperationsTransport], - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, StorageBatchOperationsTransport, Callable[..., StorageBatchOperationsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the storage batch operations client. Args: @@ -556,23 +454,13 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - read_environment_variables() - ) - self._client_cert_source = StorageBatchOperationsClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = get_universe_domain( - universe_domain_opt, - self._universe_domain_env, - default_universe=StorageBatchOperationsClient._DEFAULT_UNIVERSE, - ) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() + self._client_cert_source = StorageBatchOperationsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env, default_universe=StorageBatchOperationsClient._DEFAULT_UNIVERSE) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -584,9 +472,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -595,41 +481,35 @@ def __init__( if transport_provided: # transport is a StorageBatchOperationsTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = cast(StorageBatchOperationsTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = self._api_endpoint or get_api_endpoint( - api_override=self._client_options.api_endpoint, - universe_domain=self._universe_domain, - default_universe=StorageBatchOperationsClient._DEFAULT_UNIVERSE, - default_mtls_endpoint=StorageBatchOperationsClient.DEFAULT_MTLS_ENDPOINT, - default_endpoint_template=StorageBatchOperationsClient._DEFAULT_ENDPOINT_TEMPLATE, - use_mtls=self._use_mtls_endpoint == "always" - or (self._use_mtls_endpoint == "auto" and self._client_cert_source), - ) + self._api_endpoint = (self._api_endpoint or + get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=StorageBatchOperationsClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=StorageBatchOperationsClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=StorageBatchOperationsClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" or ( + self._use_mtls_endpoint == "auto" and self._client_cert_source + ), + )) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[StorageBatchOperationsTransport], - Callable[..., StorageBatchOperationsTransport], - ] = ( + transport_init: Union[Type[StorageBatchOperationsTransport], Callable[..., StorageBatchOperationsTransport]] = ( StorageBatchOperationsClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., StorageBatchOperationsTransport], transport) @@ -658,46 +538,33 @@ def __init__( "client_info": client_info, "always_use_jwt_access": True, "api_audience": self._client_options.api_audience, - **( - {"client_options": client_options} - if client_options is not None - else {} - ), + **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient`.", - extra={ + extra = { "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "credentialsType": None, - }, + } ) - def list_jobs( - self, - request: Optional[Union[storage_batch_operations.ListJobsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListJobsPager: + def list_jobs(self, + request: Optional[Union[storage_batch_operations.ListJobsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListJobsPager: r"""Lists Jobs in a given project. .. code-block:: python @@ -758,14 +625,10 @@ def sample_list_jobs(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -783,7 +646,9 @@ def sample_list_jobs(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -811,15 +676,14 @@ def sample_list_jobs(): # Done; return the response. return response - def get_job( - self, - request: Optional[Union[storage_batch_operations.GetJobRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_batch_operations_types.Job: + def get_job(self, + request: Optional[Union[storage_batch_operations.GetJobRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations_types.Job: r"""Gets a batch job. .. code-block:: python @@ -876,14 +740,10 @@ def sample_get_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -901,7 +761,9 @@ def sample_get_job(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -918,19 +780,16 @@ def sample_get_job(): # Done; return the response. return response - def create_job( - self, - request: Optional[ - Union[storage_batch_operations.CreateJobRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - job: Optional[storage_batch_operations_types.Job] = None, - job_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_job(self, + request: Optional[Union[storage_batch_operations.CreateJobRequest, dict]] = None, + *, + parent: Optional[str] = None, + job: Optional[storage_batch_operations_types.Job] = None, + job_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a batch job. .. code-block:: python @@ -1014,14 +873,10 @@ def sample_create_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, job, job_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1043,10 +898,12 @@ def sample_create_job(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) - setup_request_id(request, "request_id", False) + setup_request_id(request, 'request_id', False) # Validate the universe domain. self._validate_universe_domain() @@ -1070,17 +927,14 @@ def sample_create_job(): # Done; return the response. return response - def delete_job( - self, - request: Optional[ - Union[storage_batch_operations.DeleteJobRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_job(self, + request: Optional[Union[storage_batch_operations.DeleteJobRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a batch job. .. code-block:: python @@ -1128,14 +982,10 @@ def sample_delete_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1153,10 +1003,12 @@ def sample_delete_job(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) - setup_request_id(request, "request_id", False) + setup_request_id(request, 'request_id', False) # Validate the universe domain. self._validate_universe_domain() @@ -1169,17 +1021,14 @@ def sample_delete_job(): metadata=metadata, ) - def cancel_job( - self, - request: Optional[ - Union[storage_batch_operations.CancelJobRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_batch_operations.CancelJobResponse: + def cancel_job(self, + request: Optional[Union[storage_batch_operations.CancelJobRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations.CancelJobResponse: r"""Cancels a batch job. .. code-block:: python @@ -1234,14 +1083,10 @@ def sample_cancel_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1259,10 +1104,12 @@ def sample_cancel_job(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) - setup_request_id(request, "request_id", False) + setup_request_id(request, 'request_id', False) # Validate the universe domain. self._validate_universe_domain() @@ -1278,17 +1125,14 @@ def sample_cancel_job(): # Done; return the response. return response - def list_bucket_operations( - self, - request: Optional[ - Union[storage_batch_operations.ListBucketOperationsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBucketOperationsPager: + def list_bucket_operations(self, + request: Optional[Union[storage_batch_operations.ListBucketOperationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketOperationsPager: r"""Lists BucketOperations in a given project and job. .. code-block:: python @@ -1350,20 +1194,14 @@ def sample_list_bucket_operations(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, storage_batch_operations.ListBucketOperationsRequest - ): + if not isinstance(request, storage_batch_operations.ListBucketOperationsRequest): request = storage_batch_operations.ListBucketOperationsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -1377,7 +1215,9 @@ def sample_list_bucket_operations(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1405,17 +1245,14 @@ def sample_list_bucket_operations(): # Done; return the response. return response - def get_bucket_operation( - self, - request: Optional[ - Union[storage_batch_operations.GetBucketOperationRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_batch_operations_types.BucketOperation: + def get_bucket_operation(self, + request: Optional[Union[storage_batch_operations.GetBucketOperationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations_types.BucketOperation: r"""Gets a BucketOperation. .. code-block:: python @@ -1474,14 +1311,10 @@ def sample_get_bucket_operation(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1499,7 +1332,9 @@ def sample_get_bucket_operation(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1571,7 +1406,8 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1580,11 +1416,7 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1634,7 +1466,8 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1643,11 +1476,7 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1701,19 +1530,15 @@ def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def cancel_operation( self, @@ -1760,19 +1585,15 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) def get_location( self, @@ -1816,7 +1637,8 @@ def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1825,11 +1647,7 @@ def get_location( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1879,7 +1697,8 @@ def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request_pb.name),)), ) # Validate the universe domain. @@ -1888,11 +1707,7 @@ def list_locations( try: # Send the request. response = rpc( - request_pb, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request_pb, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1901,9 +1716,9 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("StorageBatchOperationsClient",) +__all__ = ( + "StorageBatchOperationsClient", +) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py index f5c35519a8ef..cc97421f7935 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py @@ -17,27 +17,26 @@ import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import google.api_core +from google.cloud.storagebatchoperations_v1 import gapic_version as package_version + import google.auth # type: ignore -import google.protobuf -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.api_core from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.storagebatchoperations_v1 import gapic_version as package_version -from google.cloud.storagebatchoperations_v1.types import ( - storage_batch_operations, - storage_batch_operations_types, -) -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.storagebatchoperations_v1.types import storage_batch_operations +from google.cloud.storagebatchoperations_v1.types import storage_batch_operations_types +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ # Check once at module load time whether google-api-core's wrap_method supports @@ -51,24 +50,25 @@ class StorageBatchOperationsTransport(abc.ABC): """Abstract transport class for StorageBatchOperations.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) - DEFAULT_HOST: str = "storagebatchoperations.googleapis.com" + DEFAULT_HOST: str = 'storagebatchoperations.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -110,43 +110,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host self._client_options = client_options @@ -173,12 +161,7 @@ def _wrap_method(self, func, *args, **kwargs): # of google-api-core is installed (which does not accept client_options, etc.). # Excluded from coverage because our CI and testing environments always install # a modern version of google-api-core that supports tracing. - for k in [ - "client_options", - "method_name", - "is_streaming", - "kind", - ]: # pragma: NO COVER + for k in ["client_options", "method_name", "is_streaming", "kind"]: # pragma: NO COVER kwargs.pop(k, None) # pragma: NO COVER return gapic_v1.method.wrap_method(func, *args, **kwargs) # pragma: NO COVER @@ -302,14 +285,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -319,81 +302,66 @@ def operations_client(self): raise NotImplementedError() @property - def list_jobs( - self, - ) -> Callable[ - [storage_batch_operations.ListJobsRequest], - Union[ - storage_batch_operations.ListJobsResponse, - Awaitable[storage_batch_operations.ListJobsResponse], - ], - ]: + def list_jobs(self) -> Callable[ + [storage_batch_operations.ListJobsRequest], + Union[ + storage_batch_operations.ListJobsResponse, + Awaitable[storage_batch_operations.ListJobsResponse] + ]]: raise NotImplementedError() @property - def get_job( - self, - ) -> Callable[ - [storage_batch_operations.GetJobRequest], - Union[ - storage_batch_operations_types.Job, - Awaitable[storage_batch_operations_types.Job], - ], - ]: + def get_job(self) -> Callable[ + [storage_batch_operations.GetJobRequest], + Union[ + storage_batch_operations_types.Job, + Awaitable[storage_batch_operations_types.Job] + ]]: raise NotImplementedError() @property - def create_job( - self, - ) -> Callable[ - [storage_batch_operations.CreateJobRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def create_job(self) -> Callable[ + [storage_batch_operations.CreateJobRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def delete_job( - self, - ) -> Callable[ - [storage_batch_operations.DeleteJobRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_job(self) -> Callable[ + [storage_batch_operations.DeleteJobRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def cancel_job( - self, - ) -> Callable[ - [storage_batch_operations.CancelJobRequest], - Union[ - storage_batch_operations.CancelJobResponse, - Awaitable[storage_batch_operations.CancelJobResponse], - ], - ]: + def cancel_job(self) -> Callable[ + [storage_batch_operations.CancelJobRequest], + Union[ + storage_batch_operations.CancelJobResponse, + Awaitable[storage_batch_operations.CancelJobResponse] + ]]: raise NotImplementedError() @property - def list_bucket_operations( - self, - ) -> Callable[ - [storage_batch_operations.ListBucketOperationsRequest], - Union[ - storage_batch_operations.ListBucketOperationsResponse, - Awaitable[storage_batch_operations.ListBucketOperationsResponse], - ], - ]: + def list_bucket_operations(self) -> Callable[ + [storage_batch_operations.ListBucketOperationsRequest], + Union[ + storage_batch_operations.ListBucketOperationsResponse, + Awaitable[storage_batch_operations.ListBucketOperationsResponse] + ]]: raise NotImplementedError() @property - def get_bucket_operation( - self, - ) -> Callable[ - [storage_batch_operations.GetBucketOperationRequest], - Union[ - storage_batch_operations_types.BucketOperation, - Awaitable[storage_batch_operations_types.BucketOperation], - ], - ]: + def get_bucket_operation(self) -> Callable[ + [storage_batch_operations.GetBucketOperationRequest], + Union[ + storage_batch_operations_types.BucketOperation, + Awaitable[storage_batch_operations_types.BucketOperation] + ]]: raise NotImplementedError() @property @@ -401,10 +369,7 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[ - operations_pb2.ListOperationsResponse, - Awaitable[operations_pb2.ListOperationsResponse], - ], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], ]: raise NotImplementedError() @@ -436,8 +401,7 @@ def delete_operation( raise NotImplementedError() @property - def get_location( - self, + def get_location(self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -445,14 +409,10 @@ def get_location( raise NotImplementedError() @property - def list_locations( - self, + def list_locations(self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[ - locations_pb2.ListLocationsResponse, - Awaitable[locations_pb2.ListLocationsResponse], - ], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], ]: raise NotImplementedError() @@ -461,4 +421,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("StorageBatchOperationsTransport",) +__all__ = ( + 'StorageBatchOperationsTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py index 3a6416a2bf31..bfa6dfff4e7f 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/grpc.py @@ -17,19 +17,17 @@ import logging as std_logging import pickle import warnings -from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence, Tuple, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, TYPE_CHECKING import grpc # type: ignore from google.api_core import grpc_helpers if TYPE_CHECKING: # pragma: NO COVER # ClientInterceptor was added in google-api-core 2.36.0+; ignore attribute-defined for older api-core versions during type checking - from google.api_core.grpc_helpers import ( - ClientInterceptor, # type: ignore[attr-defined] - ) + from google.api_core.grpc_helpers import ClientInterceptor # type: ignore[attr-defined] +from google.api_core import operations_v1 from google.api_core import client_options as client_options_lib -from google.api_core import gapic_v1, operations_v1 - +from google.api_core import gapic_v1 # The _observability module was introduced in google-api-core 2.36.0+. # On older versions of google-api-core or when type-checking against them, # mypy may flag attr-defined or assignment errors when fallback to None occurs. @@ -37,25 +35,23 @@ from google.api_core import _observability # type: ignore[attr-defined] except ImportError: # pragma: NO COVER _observability = None # type: ignore[assignment] -import google.auth # type: ignore -import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -import google.protobuf.message -import proto # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.storagebatchoperations_v1.types import ( - storage_batch_operations, - storage_batch_operations_types, -) -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import proto # type: ignore -from .base import DEFAULT_CLIENT_INFO, StorageBatchOperationsTransport +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.storagebatchoperations_v1.types import storage_batch_operations +from google.cloud.storagebatchoperations_v1.types import storage_batch_operations_types +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from .base import StorageBatchOperationsTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -65,9 +61,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -88,7 +82,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -99,11 +93,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -118,7 +108,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": client_call_details.method, "response": grpc_response, @@ -144,35 +134,32 @@ class StorageBatchOperationsGrpcTransport(StorageBatchOperationsTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "storagebatchoperations.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - interceptors: Optional[ - Sequence[ - Union[ - "ClientInterceptor", - Callable[[grpc.Channel], grpc.Channel], + def __init__(self, *, + host: str = 'storagebatchoperations.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + interceptors: Optional[ + Sequence[ + Union[ + "ClientInterceptor", + Callable[[grpc.Channel], grpc.Channel], + ] ] - ] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - ) -> None: + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + ) -> None: """Instantiate the transport. Args: @@ -309,17 +296,9 @@ def __init__( channel_interceptors = list(interceptors) if interceptors else [] if ( _observability is not None - and ( - otel_interceptor := _observability.get_otel_interceptor( - self._client_options - ) - ) - is not None + and (otel_interceptor := _observability.get_otel_interceptor(self._client_options)) is not None and otel_interceptor not in channel_interceptors - and not any( - getattr(i, "_is_otel_interceptor", None) is True - for i in channel_interceptors - ) + and not any(getattr(i, "_is_otel_interceptor", None) is True for i in channel_interceptors) ): channel_interceptors.append(otel_interceptor) @@ -328,28 +307,22 @@ def __init__( "apply_channel_interceptors", lambda channel, interceptors: channel, ) - self._grpc_channel = apply_interceptors( - self._grpc_channel, channel_interceptors - ) + self._grpc_channel = apply_interceptors(self._grpc_channel, channel_interceptors) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "storagebatchoperations.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'storagebatchoperations.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -385,12 +358,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -410,12 +384,9 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def list_jobs( - self, - ) -> Callable[ - [storage_batch_operations.ListJobsRequest], - storage_batch_operations.ListJobsResponse, - ]: + def list_jobs(self) -> Callable[ + [storage_batch_operations.ListJobsRequest], + storage_batch_operations.ListJobsResponse]: r"""Return a callable for the list jobs method over gRPC. Lists Jobs in a given project. @@ -430,20 +401,18 @@ def list_jobs( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_jobs" not in self._stubs: - self._stubs["list_jobs"] = self._logged_channel.unary_unary( - "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/ListJobs", + if 'list_jobs' not in self._stubs: + self._stubs['list_jobs'] = self._logged_channel.unary_unary( + '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/ListJobs', request_serializer=storage_batch_operations.ListJobsRequest.serialize, response_deserializer=storage_batch_operations.ListJobsResponse.deserialize, ) - return self._stubs["list_jobs"] + return self._stubs['list_jobs'] @property - def get_job( - self, - ) -> Callable[ - [storage_batch_operations.GetJobRequest], storage_batch_operations_types.Job - ]: + def get_job(self) -> Callable[ + [storage_batch_operations.GetJobRequest], + storage_batch_operations_types.Job]: r"""Return a callable for the get job method over gRPC. Gets a batch job. @@ -458,20 +427,18 @@ def get_job( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_job" not in self._stubs: - self._stubs["get_job"] = self._logged_channel.unary_unary( - "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/GetJob", + if 'get_job' not in self._stubs: + self._stubs['get_job'] = self._logged_channel.unary_unary( + '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/GetJob', request_serializer=storage_batch_operations.GetJobRequest.serialize, response_deserializer=storage_batch_operations_types.Job.deserialize, ) - return self._stubs["get_job"] + return self._stubs['get_job'] @property - def create_job( - self, - ) -> Callable[ - [storage_batch_operations.CreateJobRequest], operations_pb2.Operation - ]: + def create_job(self) -> Callable[ + [storage_batch_operations.CreateJobRequest], + operations_pb2.Operation]: r"""Return a callable for the create job method over gRPC. Creates a batch job. @@ -486,18 +453,18 @@ def create_job( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_job" not in self._stubs: - self._stubs["create_job"] = self._logged_channel.unary_unary( - "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/CreateJob", + if 'create_job' not in self._stubs: + self._stubs['create_job'] = self._logged_channel.unary_unary( + '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/CreateJob', request_serializer=storage_batch_operations.CreateJobRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["create_job"] + return self._stubs['create_job'] @property - def delete_job( - self, - ) -> Callable[[storage_batch_operations.DeleteJobRequest], empty_pb2.Empty]: + def delete_job(self) -> Callable[ + [storage_batch_operations.DeleteJobRequest], + empty_pb2.Empty]: r"""Return a callable for the delete job method over gRPC. Deletes a batch job. @@ -512,21 +479,18 @@ def delete_job( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_job" not in self._stubs: - self._stubs["delete_job"] = self._logged_channel.unary_unary( - "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/DeleteJob", + if 'delete_job' not in self._stubs: + self._stubs['delete_job'] = self._logged_channel.unary_unary( + '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/DeleteJob', request_serializer=storage_batch_operations.DeleteJobRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_job"] + return self._stubs['delete_job'] @property - def cancel_job( - self, - ) -> Callable[ - [storage_batch_operations.CancelJobRequest], - storage_batch_operations.CancelJobResponse, - ]: + def cancel_job(self) -> Callable[ + [storage_batch_operations.CancelJobRequest], + storage_batch_operations.CancelJobResponse]: r"""Return a callable for the cancel job method over gRPC. Cancels a batch job. @@ -541,21 +505,18 @@ def cancel_job( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "cancel_job" not in self._stubs: - self._stubs["cancel_job"] = self._logged_channel.unary_unary( - "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/CancelJob", + if 'cancel_job' not in self._stubs: + self._stubs['cancel_job'] = self._logged_channel.unary_unary( + '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/CancelJob', request_serializer=storage_batch_operations.CancelJobRequest.serialize, response_deserializer=storage_batch_operations.CancelJobResponse.deserialize, ) - return self._stubs["cancel_job"] + return self._stubs['cancel_job'] @property - def list_bucket_operations( - self, - ) -> Callable[ - [storage_batch_operations.ListBucketOperationsRequest], - storage_batch_operations.ListBucketOperationsResponse, - ]: + def list_bucket_operations(self) -> Callable[ + [storage_batch_operations.ListBucketOperationsRequest], + storage_batch_operations.ListBucketOperationsResponse]: r"""Return a callable for the list bucket operations method over gRPC. Lists BucketOperations in a given project and job. @@ -570,21 +531,18 @@ def list_bucket_operations( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_bucket_operations" not in self._stubs: - self._stubs["list_bucket_operations"] = self._logged_channel.unary_unary( - "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/ListBucketOperations", + if 'list_bucket_operations' not in self._stubs: + self._stubs['list_bucket_operations'] = self._logged_channel.unary_unary( + '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/ListBucketOperations', request_serializer=storage_batch_operations.ListBucketOperationsRequest.serialize, response_deserializer=storage_batch_operations.ListBucketOperationsResponse.deserialize, ) - return self._stubs["list_bucket_operations"] + return self._stubs['list_bucket_operations'] @property - def get_bucket_operation( - self, - ) -> Callable[ - [storage_batch_operations.GetBucketOperationRequest], - storage_batch_operations_types.BucketOperation, - ]: + def get_bucket_operation(self) -> Callable[ + [storage_batch_operations.GetBucketOperationRequest], + storage_batch_operations_types.BucketOperation]: r"""Return a callable for the get bucket operation method over gRPC. Gets a BucketOperation. @@ -599,13 +557,13 @@ def get_bucket_operation( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_bucket_operation" not in self._stubs: - self._stubs["get_bucket_operation"] = self._logged_channel.unary_unary( - "/google.cloud.storagebatchoperations.v1.StorageBatchOperations/GetBucketOperation", + if 'get_bucket_operation' not in self._stubs: + self._stubs['get_bucket_operation'] = self._logged_channel.unary_unary( + '/google.cloud.storagebatchoperations.v1.StorageBatchOperations/GetBucketOperation', request_serializer=storage_batch_operations.GetBucketOperationRequest.serialize, response_deserializer=storage_batch_operations_types.BucketOperation.deserialize, ) - return self._stubs["get_bucket_operation"] + return self._stubs['get_bucket_operation'] def close(self): self._logged_channel.close() @@ -614,7 +572,8 @@ def close(self): def delete_operation( self, ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC.""" + r"""Return a callable for the delete_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -631,7 +590,8 @@ def delete_operation( def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC.""" + r"""Return a callable for the cancel_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -648,7 +608,8 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -664,10 +625,9 @@ def get_operation( @property def list_operations( self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse - ]: - r"""Return a callable for the list_operations method over gRPC.""" + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -683,10 +643,9 @@ def list_operations( @property def list_locations( self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse - ]: - r"""Return a callable for the list locations method over gRPC.""" + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -703,7 +662,8 @@ def list_locations( def get_location( self, ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC.""" + r"""Return a callable for the list locations method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -721,4 +681,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("StorageBatchOperationsGrpcTransport",) +__all__ = ( + 'StorageBatchOperationsGrpcTransport', +) diff --git a/packages/google-cloud-bigquery/google/cloud/bigquery/client.py b/packages/google-cloud-bigquery/google/cloud/bigquery/client.py index 1233a28738c8..e1cb5e1bdcdf 100644 --- a/packages/google-cloud-bigquery/google/cloud/bigquery/client.py +++ b/packages/google-cloud-bigquery/google/cloud/bigquery/client.py @@ -48,9 +48,11 @@ import google.api_core.exceptions as core_exceptions import google.cloud._helpers # type: ignore import requests +from google import resumable_media # type: ignore from google.api_core import page_iterator from google.api_core import retry as retries from google.api_core.iam import Policy +from google.cloud import exceptions # pytype: disable=import-error from google.cloud.client import ( ClientWithProject, # type: ignore # pytype: disable=import-error ) @@ -59,9 +61,6 @@ ResumableUpload, ) -from google import resumable_media # type: ignore -from google.cloud import exceptions # pytype: disable=import-error - try: from google.cloud.bigquery_storage_v1.services.big_query_read.client import ( DEFAULT_CLIENT_INFO as DEFAULT_BQSTORAGE_CLIENT_INFO, @@ -71,7 +70,6 @@ from google.auth.credentials import Credentials - from google.cloud.bigquery import ( _job_helpers, _pandas_helpers, @@ -133,7 +131,9 @@ ) pyarrow = _versions_helpers.PYARROW_VERSIONS.try_import() -pandas = _versions_helpers.PANDAS_VERSIONS.try_import() # mypy check fails because pandas import is outside module, there are type: ignore comments related to this +pandas = ( + _versions_helpers.PANDAS_VERSIONS.try_import() +) # mypy check fails because pandas import is outside module, there are type: ignore comments related to this ResumableTimeoutType = Union[ diff --git a/packages/google-cloud-bigquery/google/cloud/bigquery/table.py b/packages/google-cloud-bigquery/google/cloud/bigquery/table.py index 636378a8d630..c9b79d119062 100644 --- a/packages/google-cloud-bigquery/google/cloud/bigquery/table.py +++ b/packages/google-cloud-bigquery/google/cloud/bigquery/table.py @@ -58,7 +58,6 @@ import google.api_core.exceptions import google.cloud._helpers # type: ignore from google.api_core.page_iterator import HTTPIterator - from google.cloud.bigquery import ( _helpers, _pandas_helpers, @@ -84,7 +83,6 @@ import geopandas # type: ignore import pandas import pyarrow - from google.cloud import bigquery_storage # type: ignore from google.cloud.bigquery.dataset import DatasetReference @@ -573,9 +571,9 @@ def biglake_configuration(self, value): api_repr = value if value is not None: api_repr = value.to_api_repr() - self._properties[self._PROPERTY_TO_API_FIELD["biglake_configuration"]] = ( - api_repr - ) + self._properties[ + self._PROPERTY_TO_API_FIELD["biglake_configuration"] + ] = api_repr @property def require_partition_filter(self): @@ -589,9 +587,9 @@ def require_partition_filter(self): @require_partition_filter.setter def require_partition_filter(self, value): - self._properties[self._PROPERTY_TO_API_FIELD["require_partition_filter"]] = ( - value - ) + self._properties[ + self._PROPERTY_TO_API_FIELD["require_partition_filter"] + ] = value @property def schema(self): @@ -689,9 +687,9 @@ def encryption_configuration(self, value): api_repr = value if value is not None: api_repr = value.to_api_repr() - self._properties[self._PROPERTY_TO_API_FIELD["encryption_configuration"]] = ( - api_repr - ) + self._properties[ + self._PROPERTY_TO_API_FIELD["encryption_configuration"] + ] = api_repr @property def created(self): @@ -830,7 +828,7 @@ def time_partitioning(self, value): api_repr = value.to_api_repr() elif value is not None: raise ValueError( - "value must be google.cloud.bigquery.table.TimePartitioning or None" + "value must be google.cloud.bigquery.table.TimePartitioning " "or None" ) self._properties[self._PROPERTY_TO_API_FIELD["time_partitioning"]] = api_repr @@ -966,9 +964,9 @@ def expires(self, value): if not isinstance(value, datetime.datetime) and value is not None: raise ValueError("Pass a datetime, or None") value_ms = google.cloud._helpers._millis_from_datetime(value) - self._properties[self._PROPERTY_TO_API_FIELD["expires"]] = ( - _helpers._str_or_none(value_ms) - ) + self._properties[ + self._PROPERTY_TO_API_FIELD["expires"] + ] = _helpers._str_or_none(value_ms) @property def friendly_name(self): @@ -1164,9 +1162,9 @@ def external_data_configuration(self, value): api_repr = value if value is not None: api_repr = value.to_api_repr() - self._properties[self._PROPERTY_TO_API_FIELD["external_data_configuration"]] = ( - api_repr - ) + self._properties[ + self._PROPERTY_TO_API_FIELD["external_data_configuration"] + ] = api_repr @property def snapshot_definition(self) -> Optional["SnapshotDefinition"]: @@ -3188,7 +3186,8 @@ def to_geodataframe( ) if not geography_columns: raise TypeError( - "There must be at least one GEOGRAPHY column to create a GeoDataFrame" + "There must be at least one GEOGRAPHY column" + " to create a GeoDataFrame" ) if geography_column: diff --git a/packages/google-cloud-bigquery/noxfile.py b/packages/google-cloud-bigquery/noxfile.py index 5dfe419fedf2..c366a50e293f 100644 --- a/packages/google-cloud-bigquery/noxfile.py +++ b/packages/google-cloud-bigquery/noxfile.py @@ -15,12 +15,12 @@ from __future__ import absolute_import import contextlib +from functools import wraps import os import pathlib import re import shutil import time -from functools import wraps from typing import Generator import nox diff --git a/packages/google-cloud-bigquery/tests/unit/test_client.py b/packages/google-cloud-bigquery/tests/unit/test_client.py index 9bb8b8fc85e5..c48a73cc2ebd 100644 --- a/packages/google-cloud-bigquery/tests/unit/test_client.py +++ b/packages/google-cloud-bigquery/tests/unit/test_client.py @@ -50,16 +50,16 @@ import google.api_core.exceptions import google.cloud._helpers -from google.api_core import client_info -from test_utils.imports import maybe_fail_import - import google.cloud.bigquery.retry import google.cloud.bigquery.table +from google.api_core import client_info from google.cloud import bigquery from google.cloud.bigquery import ParquetOptions, exceptions, version from google.cloud.bigquery.dataset import Dataset, DatasetReference from google.cloud.bigquery.enums import DatasetView, TimestampPrecision, UpdateMode from google.cloud.bigquery.retry import DEFAULT_TIMEOUT +from test_utils.imports import maybe_fail_import + from tests.unit.helpers import make_connection @@ -388,9 +388,8 @@ def test__get_query_results_miss_w_explicit_project_and_timeout(self): ) def test__get_query_results_miss_w_short_timeout(self): - from google.cloud.exceptions import NotFound - import google.cloud.bigquery.client + from google.cloud.exceptions import NotFound creds = _make_credentials() client = self._make_one(self.PROJECT, creds) @@ -414,9 +413,8 @@ def test__get_query_results_miss_w_short_timeout(self): ) def test__get_query_results_miss_w_default_timeout(self): - from google.cloud.exceptions import NotFound - import google.cloud.bigquery.client + from google.cloud.exceptions import NotFound creds = _make_credentials() client = self._make_one(self.PROJECT, creds) @@ -483,9 +481,8 @@ def test__get_query_results_hit(self): self.assertTrue(query_results.complete) def test__list_rows_from_query_results_w_none_timeout(self): - from google.cloud.exceptions import NotFound - from google.cloud.bigquery.schema import SchemaField + from google.cloud.exceptions import NotFound creds = _make_credentials() client = self._make_one(self.PROJECT, creds) @@ -518,10 +515,9 @@ def test__list_rows_from_query_results_w_none_timeout(self): ) def test__list_rows_from_query_results_w_default_timeout(self): - from google.cloud.exceptions import NotFound - import google.cloud.bigquery.client from google.cloud.bigquery.schema import SchemaField + from google.cloud.exceptions import NotFound creds = _make_credentials() client = self._make_one(self.PROJECT, creds) @@ -1837,7 +1833,6 @@ def test_get_table_sets_user_agent(self): def test_get_iam_policy(self): from google.api_core.iam import Policy - from google.cloud.bigquery.iam import ( BIGQUERY_DATA_EDITOR_ROLE, BIGQUERY_DATA_OWNER_ROLE, @@ -1916,7 +1911,6 @@ def test_get_iam_policy_w_invalid_version(self): def test_set_iam_policy(self): from google.api_core.iam import Policy - from google.cloud.bigquery.iam import ( BIGQUERY_DATA_EDITOR_ROLE, BIGQUERY_DATA_OWNER_ROLE, @@ -1973,7 +1967,6 @@ def test_set_iam_policy(self): def test_set_iam_policy_updateMask(self): from google.api_core.iam import Policy - from google.cloud.bigquery.iam import ( BIGQUERY_DATA_EDITOR_ROLE, BIGQUERY_DATA_OWNER_ROLE, @@ -2701,7 +2694,6 @@ def test_update_table_w_query(self): import datetime from google.cloud._helpers import UTC, _millis - from google.cloud.bigquery.schema import SchemaField from google.cloud.bigquery.table import Table @@ -3323,9 +3315,8 @@ def test_create_job_query_config(self): self._create_job_helper(configuration) def test_create_job_query_config_w_rateLimitExceeded_error(self): - from google.cloud.exceptions import Forbidden - from google.cloud.bigquery.retry import DEFAULT_RETRY + from google.cloud.exceptions import Forbidden query = "select count(*) from persons" configuration = { @@ -3406,9 +3397,8 @@ def test_job_from_resource_unknown_type(self): self.assertEqual(got.project, self.PROJECT) def test_get_job_miss_w_explict_project(self): - from google.cloud.exceptions import NotFound - from google.cloud.bigquery.retry import DEFAULT_GET_JOB_TIMEOUT + from google.cloud.exceptions import NotFound OTHER_PROJECT = "OTHER_PROJECT" JOB_ID = "NONESUCH" @@ -3427,9 +3417,8 @@ def test_get_job_miss_w_explict_project(self): ) def test_get_job_miss_w_client_location(self): - from google.cloud.exceptions import NotFound - from google.cloud.bigquery.retry import DEFAULT_GET_JOB_TIMEOUT + from google.cloud.exceptions import NotFound JOB_ID = "NONESUCH" creds = _make_credentials() @@ -5392,7 +5381,6 @@ def test_query_pico_timestamp_insert_error(self): def test_query_job_rpc_fail_w_random_error(self): from google.api_core.exceptions import Unknown - from google.cloud.bigquery.job import QueryJob creds = _make_credentials() @@ -5409,7 +5397,6 @@ def test_query_job_rpc_fail_w_random_error(self): def test_query_job_rpc_fail_w_conflict_job_id_given(self): from google.api_core.exceptions import Conflict - from google.cloud.bigquery.job import QueryJob creds = _make_credentials() @@ -5426,7 +5413,6 @@ def test_query_job_rpc_fail_w_conflict_job_id_given(self): def test_query_job_rpc_fail_w_conflict_random_id_job_fetch_fails(self): from google.api_core.exceptions import Conflict, DataLoss - from google.cloud.bigquery.job import QueryJob creds = _make_credentials() @@ -5450,7 +5436,6 @@ def test_query_job_rpc_fail_w_conflict_random_id_job_fetch_fails(self): def test_query_job_rpc_fail_w_conflict_random_id_job_fetch_fails_no_retries(self): from google.api_core.exceptions import Conflict, DataLoss - from google.cloud.bigquery.job import QueryJob creds = _make_credentials() @@ -5480,7 +5465,6 @@ def test_query_job_rpc_fail_w_conflict_random_id_job_fetch_fails_no_retries(self def test_query_job_rpc_fail_w_conflict_random_id_job_fetch_succeeds(self): from google.api_core.exceptions import Conflict - from google.cloud.bigquery.job import QueryJob creds = _make_credentials() @@ -5824,7 +5808,6 @@ def test_insert_rows_w_schema(self): import datetime from google.cloud._helpers import _RFC3339_MICROS, UTC, _datetime_to_rfc3339 - from google.cloud.bigquery.schema import SchemaField WHEN_TS = 1437767599.006 @@ -5884,7 +5867,6 @@ def test_insert_rows_w_list_of_dictionaries(self): import datetime from google.cloud._helpers import _RFC3339_MICROS, UTC, _datetime_to_rfc3339 - from google.cloud.bigquery.schema import SchemaField from google.cloud.bigquery.table import Table @@ -6072,7 +6054,6 @@ def _row_data(row): def test_insert_rows_w_repeated_fields(self): from google.cloud._helpers import UTC - from google.cloud.bigquery.schema import SchemaField from google.cloud.bigquery.table import Table @@ -6904,7 +6885,6 @@ def test_insert_rows_w_wrong_arg(self): def test_insert_rows_json_w_ssl_error(self): import requests.exceptions - from google.cloud.bigquery.dataset import DatasetReference from google.cloud.bigquery.schema import SchemaField from google.cloud.bigquery.table import Table @@ -6981,7 +6961,6 @@ def test_list_rows(self): import datetime from google.cloud._helpers import UTC - from google.cloud.bigquery.schema import SchemaField from google.cloud.bigquery.table import Row, Table @@ -7823,9 +7802,8 @@ def test_load_table_from_file_with_writable_gzip(self): ) def test_load_table_from_file_failure(self): - from google.resumable_media import InvalidResponse - from google.cloud import exceptions + from google.resumable_media import InvalidResponse client = self._make_client() file_obj = self._make_file_obj() @@ -9682,7 +9660,6 @@ def test_load_table_from_json_wo_schema_wo_autodetect_write_append_w_table(self) # For more details, see https://github.com/googleapis/python-bigquery/issues/1228#issuecomment-1910946297 def test_load_table_from_json_wo_schema_wo_autodetect_write_append_wo_table(self): import google.api_core.exceptions as core_exceptions - from google.cloud.bigquery import job from google.cloud.bigquery.client import _DEFAULT_NUM_RETRIES from google.cloud.bigquery.job import WriteDisposition diff --git a/packages/google-cloud-bigquery/tests/unit/test_table.py b/packages/google-cloud-bigquery/tests/unit/test_table.py index b99ddb0573aa..31556cb2b4fa 100644 --- a/packages/google-cloud-bigquery/tests/unit/test_table.py +++ b/packages/google-cloud-bigquery/tests/unit/test_table.py @@ -25,12 +25,11 @@ import google.api_core.exceptions import pytest -from test_utils.imports import maybe_fail_import - from google.cloud.bigquery import _versions_helpers, exceptions, external_config, schema from google.cloud.bigquery.dataset import DatasetReference from google.cloud.bigquery.enums import DefaultPandasDTypes from google.cloud.bigquery.table import TableReference +from test_utils.imports import maybe_fail_import def _mock_client(): @@ -617,7 +616,6 @@ def test_ctor_tablelistitem(self): import datetime from google.cloud._helpers import UTC, _millis - from google.cloud.bigquery.table import Table, TableListItem self.WHEN_TS = 1437767599.125 @@ -856,7 +854,6 @@ def test_snapshot_definition_not_set(self): def test_snapshot_definition_set(self): from google.cloud._helpers import UTC - from google.cloud.bigquery.table import SnapshotDefinition dataset = DatasetReference(self.PROJECT, self.DS_ID) @@ -891,7 +888,6 @@ def test_clone_definition_not_set(self): def test_clone_definition_set(self): from google.cloud._helpers import UTC - from google.cloud.bigquery.table import CloneDefinition dataset = DatasetReference(self.PROJECT, self.DS_ID) @@ -2236,7 +2232,6 @@ def test_ctor_empty_resource(self): def test_ctor_full_resource(self): from google.cloud._helpers import UTC - from google.cloud.bigquery.table import TableReference resource = { @@ -2368,7 +2363,6 @@ def test_ctor_empty_resource(self): def test_ctor_full_resource(self): from google.cloud._helpers import UTC - from google.cloud.bigquery.table import TableReference resource = { @@ -3065,15 +3059,14 @@ def test_to_arrow_iterable(self): def test_to_arrow_iterable_w_bqstorage(self): pyarrow = pytest.importorskip("pyarrow") pytest.importorskip("google.cloud.bigquery_storage") + from google.cloud import bigquery_storage + from google.cloud.bigquery import schema + from google.cloud.bigquery import table as mut from google.cloud.bigquery_storage_v1 import reader from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( grpc as big_query_read_grpc_transport, ) - from google.cloud import bigquery_storage - from google.cloud.bigquery import schema - from google.cloud.bigquery import table as mut - bqstorage_client = mock.create_autospec(bigquery_storage.BigQueryReadClient) bqstorage_client._transport = mock.create_autospec( big_query_read_grpc_transport.BigQueryReadGrpcTransport @@ -3235,7 +3228,6 @@ def test_to_arrow_w_nulls(self): "pyarrow", minversion=self.PYARROW_MINIMUM_VERSION ) import pyarrow.types - from google.cloud.bigquery.schema import SchemaField schema = [SchemaField("name", "STRING"), SchemaField("age", "INTEGER")] @@ -3441,15 +3433,14 @@ def test_to_arrow_w_bqstorage(self): pytest.importorskip("numpy") pyarrow = pytest.importorskip("pyarrow") pytest.importorskip("google.cloud.bigquery_storage") + from google.cloud import bigquery_storage + from google.cloud.bigquery import schema + from google.cloud.bigquery import table as mut from google.cloud.bigquery_storage_v1 import reader from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( grpc as big_query_read_grpc_transport, ) - from google.cloud import bigquery_storage - from google.cloud.bigquery import schema - from google.cloud.bigquery import table as mut - bqstorage_client = mock.create_autospec(bigquery_storage.BigQueryReadClient) bqstorage_client._transport = mock.create_autospec( big_query_read_grpc_transport.BigQueryReadGrpcTransport @@ -3526,13 +3517,12 @@ def test_to_arrow_w_bqstorage_creates_client(self): pytest.importorskip("numpy") pytest.importorskip("pyarrow") pytest.importorskip("google.cloud.bigquery_storage") - from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( - grpc as big_query_read_grpc_transport, - ) - from google.cloud import bigquery_storage from google.cloud.bigquery import schema from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( + grpc as big_query_read_grpc_transport, + ) mock_client = _mock_client() bqstorage_client = mock.create_autospec(bigquery_storage.BigQueryReadClient) @@ -3562,14 +3552,13 @@ def test_to_arrow_create_read_session_user_agent(self): pytest.importorskip("pyarrow") pytest.importorskip("google.cloud.bigquery_storage") import google.auth.credentials - from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( - grpc as big_query_read_grpc_transport, - ) - from google.cloud import bigquery_storage from google.cloud.bigquery import client as client_module from google.cloud.bigquery import schema, version from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( + grpc as big_query_read_grpc_transport, + ) mock_channel = mock.MagicMock() mock_unary = mock.MagicMock() @@ -3620,14 +3609,13 @@ def test_to_arrow_create_read_session_user_agent_pandas_gbq_not_installed(self): pytest.importorskip("pyarrow") pytest.importorskip("google.cloud.bigquery_storage") import google.auth.credentials - from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( - grpc as big_query_read_grpc_transport, - ) - from google.cloud import bigquery_storage from google.cloud.bigquery import client as client_module from google.cloud.bigquery import schema, version from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( + grpc as big_query_read_grpc_transport, + ) mock_channel = mock.MagicMock() mock_unary = mock.MagicMock() @@ -3883,15 +3871,14 @@ def test_to_dataframe_iterable_w_bqstorage(self): pandas = pytest.importorskip("pandas") pyarrow = pytest.importorskip("pyarrow") pytest.importorskip("google.cloud.bigquery_storage") + from google.cloud import bigquery_storage + from google.cloud.bigquery import schema + from google.cloud.bigquery import table as mut from google.cloud.bigquery_storage_v1 import reader from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( grpc as big_query_read_grpc_transport, ) - from google.cloud import bigquery_storage - from google.cloud.bigquery import schema - from google.cloud.bigquery import table as mut - arrow_fields = [ pyarrow.field("colA", pyarrow.int64()), # Not alphabetical to test column order. @@ -4996,13 +4983,12 @@ def test_to_dataframe_w_bqstorage_creates_client(self): pytest.importorskip("numpy") pytest.importorskip("pandas") pytest.importorskip("google.cloud.bigquery_storage") - from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( - grpc as big_query_read_grpc_transport, - ) - from google.cloud import bigquery_storage from google.cloud.bigquery import schema from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( + grpc as big_query_read_grpc_transport, + ) mock_client = _mock_client() bqstorage_client = mock.create_autospec(bigquery_storage.BigQueryReadClient) @@ -5032,14 +5018,13 @@ def test_to_dataframe_create_read_session_user_agent(self): pytest.importorskip("pandas") pytest.importorskip("google.cloud.bigquery_storage") import google.auth.credentials - from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( - grpc as big_query_read_grpc_transport, - ) - from google.cloud import bigquery_storage from google.cloud.bigquery import client as client_module from google.cloud.bigquery import schema, version from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( + grpc as big_query_read_grpc_transport, + ) mock_channel = mock.MagicMock() mock_unary = mock.MagicMock() @@ -5090,14 +5075,13 @@ def test_to_dataframe_create_read_session_user_agent_pandas_gbq_not_installed(se pytest.importorskip("pandas") pytest.importorskip("google.cloud.bigquery_storage") import google.auth.credentials - from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( - grpc as big_query_read_grpc_transport, - ) - from google.cloud import bigquery_storage from google.cloud.bigquery import client as client_module from google.cloud.bigquery import schema, version from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( + grpc as big_query_read_grpc_transport, + ) mock_channel = mock.MagicMock() mock_unary = mock.MagicMock() @@ -5199,11 +5183,10 @@ def test_to_dataframe_w_bqstorage_empty_streams(self): pytest.importorskip("google.cloud.bigquery_storage") pytest.importorskip("pandas") pyarrow = pytest.importorskip("pyarrow") - from google.cloud.bigquery_storage_v1 import reader - from google.cloud import bigquery_storage from google.cloud.bigquery import schema from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1 import reader arrow_fields = [ pyarrow.field("colA", pyarrow.int64()), @@ -5255,15 +5238,14 @@ def test_to_dataframe_w_bqstorage_nonempty(self): pytest.importorskip("google.cloud.bigquery_storage") pytest.importorskip("pandas") pyarrow = pytest.importorskip("pyarrow") + from google.cloud import bigquery_storage + from google.cloud.bigquery import schema + from google.cloud.bigquery import table as mut from google.cloud.bigquery_storage_v1 import reader from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( grpc as big_query_read_grpc_transport, ) - from google.cloud import bigquery_storage - from google.cloud.bigquery import schema - from google.cloud.bigquery import table as mut - arrow_fields = [ pyarrow.field("colA", pyarrow.int64()), # Not alphabetical to test column order. @@ -5339,10 +5321,9 @@ def test_to_dataframe_w_bqstorage_multiple_streams_return_unique_index(self): bigquery_storage = pytest.importorskip("google.cloud.bigquery_storage") pytest.importorskip("pandas") pyarrow = pytest.importorskip("pyarrow") - from google.cloud.bigquery_storage_v1 import reader - from google.cloud.bigquery import schema from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1 import reader arrow_fields = [pyarrow.field("colA", pyarrow.int64())] arrow_schema = pyarrow.schema(arrow_fields) @@ -5394,10 +5375,9 @@ def test_to_dataframe_w_bqstorage_updates_progress_bar(self): pytest.importorskip("pandas") pyarrow = pytest.importorskip("pyarrow") pytest.importorskip("tqdm") - from google.cloud.bigquery_storage_v1 import reader - from google.cloud.bigquery import schema from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1 import reader # Speed up testing. mut._PROGRESS_INTERVAL = 0.01 @@ -5472,10 +5452,9 @@ def test_to_dataframe_w_bqstorage_exits_on_keyboardinterrupt(self): bigquery_storage = pytest.importorskip("google.cloud.bigquery_storage") pytest.importorskip("pandas") pyarrow = pytest.importorskip("pyarrow") - from google.cloud.bigquery_storage_v1 import reader - from google.cloud.bigquery import schema from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1 import reader # Speed up testing. mut._PROGRESS_INTERVAL = 0.01 @@ -5649,15 +5628,14 @@ def test_to_dataframe_concat_categorical_dtype_w_pyarrow(self): pytest.importorskip("google.cloud.bigquery_storage") pandas = pytest.importorskip("pandas") pyarrow = pytest.importorskip("pyarrow") + from google.cloud import bigquery_storage + from google.cloud.bigquery import schema + from google.cloud.bigquery import table as mut from google.cloud.bigquery_storage_v1 import reader from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( grpc as big_query_read_grpc_transport, ) - from google.cloud import bigquery_storage - from google.cloud.bigquery import schema - from google.cloud.bigquery import table as mut - arrow_fields = [ # Not alphabetical to test column order. pyarrow.field("col_str", pyarrow.utf8()), diff --git a/packages/google-cloud-spanner/.cross_sync/generate.py b/packages/google-cloud-spanner/.cross_sync/generate.py index b5db7c07c521..07a619e1105b 100644 --- a/packages/google-cloud-spanner/.cross_sync/generate.py +++ b/packages/google-cloud-spanner/.cross_sync/generate.py @@ -12,10 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations - -import ast from typing import Sequence - +import ast """ Entrypoint for initiating an async -> sync conversion using CrossSync @@ -37,9 +35,7 @@ def extract_header_comments(file_path) -> str: header.append(line) else: break - header.append( - "\n# This file is automatically generated by CrossSync. Do not edit manually.\n\n" - ) + header.append("\n# This file is automatically generated by CrossSync. Do not edit manually.\n\n") return "".join(header) @@ -80,8 +76,7 @@ def format_with_ruff(source: str, filename: str) -> str: "-", ] passes = [ - base_command - + ["check", "--select", "I,F401", "--fix", "--quiet", *shared_args], + base_command + ["check", "--select", "I,F401", "--fix", "--quiet", *shared_args], base_command + ["format", *shared_args], ] for command in passes: @@ -95,6 +90,7 @@ def format_with_ruff(source: str, filename: str) -> str: class CrossSyncOutputFile: + def __init__(self, output_path: str, ast_tree, header: str | None = None): self.output_path = output_path self.tree = ast_tree @@ -113,7 +109,6 @@ def render(self, with_formatter=True, save_to_disk: bool = True) -> str: full_str = format_with_ruff(full_str, self.output_path) if save_to_disk: import os - os.makedirs(os.path.dirname(self.output_path), exist_ok=True) with open(self.output_path, "w") as f: f.write(full_str) @@ -122,7 +117,6 @@ def render(self, with_formatter=True, save_to_disk: bool = True) -> str: def convert_path(search_path: str) -> set[CrossSyncOutputFile]: import glob - from transformers import CrossSyncFileProcessor if os.path.isfile(search_path): From f7f3febac1a3a7805969a50d5161a28c4c875f5e Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 16 Sep 2026 17:33:17 -0400 Subject: [PATCH 40/43] feat(gapic): wire method_name for mixin methods in base transport Pass canonical method_name to _wrap_method for mixin methods (Operations, IAM, Locations) so that client calls to mixin methods emit OpenTelemetry Tier 3 method spans. --- packages/gapic-generator/gapic/schema/mixins.py | 10 ++++++++++ packages/gapic-generator/gapic/schema/wrappers.py | 2 ++ .../%sub/services/%service/transports/base.py.j2 | 1 + .../asset_v1/services/asset_service/transports/base.py | 1 + .../eventarc_v1/services/eventarc/transports/base.py | 9 +++++++++ .../services/config_service_v2/transports/base.py | 3 +++ .../services/logging_service_v2/transports/base.py | 3 +++ .../services/metrics_service_v2/transports/base.py | 3 +++ .../services/config_service_v2/transports/base.py | 3 +++ .../services/logging_service_v2/transports/base.py | 3 +++ .../services/metrics_service_v2/transports/base.py | 3 +++ .../redis_v1/services/cloud_redis/transports/base.py | 7 +++++++ .../redis_v1/services/cloud_redis/transports/base.py | 7 +++++++ .../storage_batch_operations/transports/base.py | 6 ++++++ packages/gapic-generator/tests/unit/schema/test_api.py | 3 +++ 15 files changed, 64 insertions(+) diff --git a/packages/gapic-generator/gapic/schema/mixins.py b/packages/gapic-generator/gapic/schema/mixins.py index d340ec1189ab..793bb4b3ef99 100644 --- a/packages/gapic-generator/gapic/schema/mixins.py +++ b/packages/gapic-generator/gapic/schema/mixins.py @@ -19,50 +19,60 @@ "DeleteOperation", request_type="operations_pb2.DeleteOperationRequest", response_type="None", + rpc_name="google.longrunning.Operations/DeleteOperation", ), "WaitOperation": wrappers.MixinMethod( "WaitOperation", request_type="operations_pb2.WaitOperationRequest", response_type="operations_pb2.Operation", + rpc_name="google.longrunning.Operations/WaitOperation", ), "ListOperations": wrappers.MixinMethod( "ListOperations", request_type="operations_pb2.ListOperationsRequest", response_type="operations_pb2.ListOperationsResponse", + rpc_name="google.longrunning.Operations/ListOperations", ), "CancelOperation": wrappers.MixinMethod( "CancelOperation", request_type="operations_pb2.CancelOperationRequest", response_type="None", + rpc_name="google.longrunning.Operations/CancelOperation", ), "GetOperation": wrappers.MixinMethod( "GetOperation", request_type="operations_pb2.GetOperationRequest", response_type="operations_pb2.Operation", + rpc_name="google.longrunning.Operations/GetOperation", ), "TestIamPermissions": wrappers.MixinMethod( "TestIamPermissions", request_type="iam_policy_pb2.TestIamPermissionsRequest", response_type="iam_policy_pb2.TestIamPermissionsResponse", + rpc_name="google.iam.v1.IAMPolicy/TestIamPermissions", ), "GetIamPolicy": wrappers.MixinMethod( "GetIamPolicy", request_type="iam_policy_pb2.GetIamPolicyRequest", response_type="policy_pb2.Policy", + rpc_name="google.iam.v1.IAMPolicy/GetIamPolicy", ), "SetIamPolicy": wrappers.MixinMethod( "SetIamPolicy", request_type="iam_policy_pb2.SetIamPolicyRequest", response_type="policy_pb2.Policy", + rpc_name="google.iam.v1.IAMPolicy/SetIamPolicy", ), "ListLocations": wrappers.MixinMethod( "ListLocations", request_type="locations_pb2.ListLocationsRequest", response_type="locations_pb2.ListLocationsResponse", + rpc_name="google.cloud.location.Locations/ListLocations", ), "GetLocation": wrappers.MixinMethod( "GetLocation", request_type="locations_pb2.GetLocationRequest", response_type="locations_pb2.Location", + rpc_name="google.cloud.location.Locations/GetLocation", ), } diff --git a/packages/gapic-generator/gapic/schema/wrappers.py b/packages/gapic-generator/gapic/schema/wrappers.py index 9d17b77257c5..e1acba6b3a8d 100644 --- a/packages/gapic-generator/gapic/schema/wrappers.py +++ b/packages/gapic-generator/gapic/schema/wrappers.py @@ -1463,6 +1463,8 @@ class MixinMethod: name: str request_type: str response_type: str + rpc_name: str = "" + @dataclasses.dataclass(frozen=True) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 index 164e0bb52739..cd4c6b3fa9ad 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 @@ -224,6 +224,7 @@ class {{ service.name }}Transport(abc.ABC): self.{{ method_name|snake_case }}, default_timeout=None, client_info=client_info, + method_name="{{ api.mixin_api_signatures[method_name].rpc_name }}", ), {% endfor %} {# method_name in api.mixin_api_methods.keys() #} } diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py index 644327ceeac1..2ca57c8ab8f7 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py @@ -377,6 +377,7 @@ def _prep_wrapped_messages(self, client_info): self.get_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/GetOperation", ), } diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py index af33d16a7beb..fd3fea7f587d 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py @@ -416,46 +416,55 @@ def _prep_wrapped_messages(self, client_info): self.get_location, default_timeout=None, client_info=client_info, + method_name="google.cloud.location.Locations/GetLocation", ), self.list_locations: self._wrap_method( self.list_locations, default_timeout=None, client_info=client_info, + method_name="google.cloud.location.Locations/ListLocations", ), self.get_iam_policy: self._wrap_method( self.get_iam_policy, default_timeout=None, client_info=client_info, + method_name="google.iam.v1.IAMPolicy/GetIamPolicy", ), self.set_iam_policy: self._wrap_method( self.set_iam_policy, default_timeout=None, client_info=client_info, + method_name="google.iam.v1.IAMPolicy/SetIamPolicy", ), self.test_iam_permissions: self._wrap_method( self.test_iam_permissions, default_timeout=None, client_info=client_info, + method_name="google.iam.v1.IAMPolicy/TestIamPermissions", ), self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/CancelOperation", ), self.delete_operation: self._wrap_method( self.delete_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/DeleteOperation", ), self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/GetOperation", ), self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/ListOperations", ), } diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py index 89638bbf0c72..6b26bfdd24fd 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -442,16 +442,19 @@ def _prep_wrapped_messages(self, client_info): self.cancel_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/CancelOperation", ), self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/GetOperation", ), self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/ListOperations", ), } diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index 5be4cc6ca83e..c0750edf90ae 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -276,16 +276,19 @@ def _prep_wrapped_messages(self, client_info): self.cancel_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/CancelOperation", ), self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/GetOperation", ), self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/ListOperations", ), } diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index 362c7a9f93e5..eae1ca61b467 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -247,16 +247,19 @@ def _prep_wrapped_messages(self, client_info): self.cancel_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/CancelOperation", ), self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/GetOperation", ), self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/ListOperations", ), } diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py index 89638bbf0c72..6b26bfdd24fd 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -442,16 +442,19 @@ def _prep_wrapped_messages(self, client_info): self.cancel_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/CancelOperation", ), self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/GetOperation", ), self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/ListOperations", ), } diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index 5be4cc6ca83e..c0750edf90ae 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -276,16 +276,19 @@ def _prep_wrapped_messages(self, client_info): self.cancel_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/CancelOperation", ), self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/GetOperation", ), self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/ListOperations", ), } diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index 362c7a9f93e5..eae1ca61b467 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -247,16 +247,19 @@ def _prep_wrapped_messages(self, client_info): self.cancel_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/CancelOperation", ), self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/GetOperation", ), self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/ListOperations", ), } diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py index 427dd8e5c7b6..89afff8ed313 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -236,36 +236,43 @@ def _prep_wrapped_messages(self, client_info): self.get_location, default_timeout=None, client_info=client_info, + method_name="google.cloud.location.Locations/GetLocation", ), self.list_locations: self._wrap_method( self.list_locations, default_timeout=None, client_info=client_info, + method_name="google.cloud.location.Locations/ListLocations", ), self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/CancelOperation", ), self.delete_operation: self._wrap_method( self.delete_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/DeleteOperation", ), self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/GetOperation", ), self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/ListOperations", ), self.wait_operation: self._wrap_method( self.wait_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/WaitOperation", ), } diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py index 644738588d8f..0728b3dd001c 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -200,36 +200,43 @@ def _prep_wrapped_messages(self, client_info): self.get_location, default_timeout=None, client_info=client_info, + method_name="google.cloud.location.Locations/GetLocation", ), self.list_locations: self._wrap_method( self.list_locations, default_timeout=None, client_info=client_info, + method_name="google.cloud.location.Locations/ListLocations", ), self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/CancelOperation", ), self.delete_operation: self._wrap_method( self.delete_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/DeleteOperation", ), self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/GetOperation", ), self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/ListOperations", ), self.wait_operation: self._wrap_method( self.wait_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/WaitOperation", ), } diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py index cc97421f7935..cefe275299c3 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py @@ -259,31 +259,37 @@ def _prep_wrapped_messages(self, client_info): self.get_location, default_timeout=None, client_info=client_info, + method_name="google.cloud.location.Locations/GetLocation", ), self.list_locations: self._wrap_method( self.list_locations, default_timeout=None, client_info=client_info, + method_name="google.cloud.location.Locations/ListLocations", ), self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/CancelOperation", ), self.delete_operation: self._wrap_method( self.delete_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/DeleteOperation", ), self.get_operation: self._wrap_method( self.get_operation, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/GetOperation", ), self.list_operations: self._wrap_method( self.list_operations, default_timeout=None, client_info=client_info, + method_name="google.longrunning.Operations/ListOperations", ), } diff --git a/packages/gapic-generator/tests/unit/schema/test_api.py b/packages/gapic-generator/tests/unit/schema/test_api.py index 13ca7a009c86..0bef9ad02560 100644 --- a/packages/gapic-generator/tests/unit/schema/test_api.py +++ b/packages/gapic-generator/tests/unit/schema/test_api.py @@ -2836,6 +2836,9 @@ def test_mixin_api_signatures(): api_schema = api.API.build(fd, "google.example.v1", opts=opts) res = api_schema.mixin_api_signatures assert res == mixins.MIXINS_MAP + assert res["GetOperation"].rpc_name == "google.longrunning.Operations/GetOperation" + assert res["GetIamPolicy"].rpc_name == "google.iam.v1.IAMPolicy/GetIamPolicy" + assert res["GetLocation"].rpc_name == "google.cloud.location.Locations/GetLocation" def test_mixin_http_options(): From 2f522bd228ba661e5efe4f34cb8e4be68d30c686 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Thu, 17 Sep 2026 04:58:25 -0400 Subject: [PATCH 41/43] test(gapic): clarify test handling of abstract base transport NotImplementedError Update test comment in template and goldens to explain testing of NotImplementedError when accessing transport.kind. --- .../tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 | 2 +- .../asset/tests/unit/gapic/asset_v1/test_asset_service.py | 2 +- .../tests/unit/gapic/credentials_v1/test_iam_credentials.py | 2 +- .../eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py | 2 +- .../tests/unit/gapic/logging_v2/test_config_service_v2.py | 2 +- .../tests/unit/gapic/logging_v2/test_logging_service_v2.py | 2 +- .../tests/unit/gapic/logging_v2/test_metrics_service_v2.py | 2 +- .../tests/unit/gapic/logging_v2/test_config_service_v2.py | 2 +- .../tests/unit/gapic/logging_v2/test_logging_service_v2.py | 2 +- .../tests/unit/gapic/logging_v2/test_metrics_service_v2.py | 2 +- .../goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py | 2 +- .../tests/unit/gapic/redis_v1/test_cloud_redis.py | 2 +- .../storagebatchoperations_v1/test_storage_batch_operations.py | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 index f09088ceae26..7cf0ad2e2627 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 @@ -1395,7 +1395,7 @@ def test_{{ service.name|snake_case }}_base_transport_wrap_method(): assert "client_options" not in mock_wrap.call_args.kwargs assert "kind" not in mock_wrap.call_args.kwargs - # Test without kind (e.g. abstract base transport) + # Test for correct handling of abstract base transport NotImplementedError mock_wrap.reset_mock() mock_kind.side_effect = NotImplementedError transport._wrap_with_tracing = True diff --git a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py index 18b00d94d0b6..04819a637fbb 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py @@ -17484,7 +17484,7 @@ def test_asset_service_base_transport_wrap_method(): assert "client_options" not in mock_wrap.call_args.kwargs assert "kind" not in mock_wrap.call_args.kwargs - # Test without kind (e.g. abstract base transport) + # Test for correct handling of abstract base transport NotImplementedError mock_wrap.reset_mock() mock_kind.side_effect = NotImplementedError transport._wrap_with_tracing = True diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py index 43f23fd0a8e3..4cfda9621d70 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py @@ -3898,7 +3898,7 @@ def test_iam_credentials_base_transport_wrap_method(): assert "client_options" not in mock_wrap.call_args.kwargs assert "kind" not in mock_wrap.call_args.kwargs - # Test without kind (e.g. abstract base transport) + # Test for correct handling of abstract base transport NotImplementedError mock_wrap.reset_mock() mock_kind.side_effect = NotImplementedError transport._wrap_with_tracing = True diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py index 8c98fc924a80..665e2e87e0c7 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py @@ -30925,7 +30925,7 @@ def test_eventarc_base_transport_wrap_method(): assert "client_options" not in mock_wrap.call_args.kwargs assert "kind" not in mock_wrap.call_args.kwargs - # Test without kind (e.g. abstract base transport) + # Test for correct handling of abstract base transport NotImplementedError mock_wrap.reset_mock() mock_kind.side_effect = NotImplementedError transport._wrap_with_tracing = True diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py index ede2b0c4869a..15ba0aaa50ae 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -12842,7 +12842,7 @@ def test_config_service_v2_base_transport_wrap_method(): assert "client_options" not in mock_wrap.call_args.kwargs assert "kind" not in mock_wrap.call_args.kwargs - # Test without kind (e.g. abstract base transport) + # Test for correct handling of abstract base transport NotImplementedError mock_wrap.reset_mock() mock_kind.side_effect = NotImplementedError transport._wrap_with_tracing = True diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py index 2d447e1bc2a4..631a8d3d83ae 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -3434,7 +3434,7 @@ def test_logging_service_v2_base_transport_wrap_method(): assert "client_options" not in mock_wrap.call_args.kwargs assert "kind" not in mock_wrap.call_args.kwargs - # Test without kind (e.g. abstract base transport) + # Test for correct handling of abstract base transport NotImplementedError mock_wrap.reset_mock() mock_kind.side_effect = NotImplementedError transport._wrap_with_tracing = True diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index ec5ed23aae67..509491abdfcc 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -3234,7 +3234,7 @@ def test_metrics_service_v2_base_transport_wrap_method(): assert "client_options" not in mock_wrap.call_args.kwargs assert "kind" not in mock_wrap.call_args.kwargs - # Test without kind (e.g. abstract base transport) + # Test for correct handling of abstract base transport NotImplementedError mock_wrap.reset_mock() mock_kind.side_effect = NotImplementedError transport._wrap_with_tracing = True diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py index 138d75fbc96a..887df9002db0 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -12842,7 +12842,7 @@ def test_config_service_v2_base_transport_wrap_method(): assert "client_options" not in mock_wrap.call_args.kwargs assert "kind" not in mock_wrap.call_args.kwargs - # Test without kind (e.g. abstract base transport) + # Test for correct handling of abstract base transport NotImplementedError mock_wrap.reset_mock() mock_kind.side_effect = NotImplementedError transport._wrap_with_tracing = True diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py index 2d447e1bc2a4..631a8d3d83ae 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -3434,7 +3434,7 @@ def test_logging_service_v2_base_transport_wrap_method(): assert "client_options" not in mock_wrap.call_args.kwargs assert "kind" not in mock_wrap.call_args.kwargs - # Test without kind (e.g. abstract base transport) + # Test for correct handling of abstract base transport NotImplementedError mock_wrap.reset_mock() mock_kind.side_effect = NotImplementedError transport._wrap_with_tracing = True diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index 650bf5813089..e39504297fed 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -3234,7 +3234,7 @@ def test_metrics_service_v2_base_transport_wrap_method(): assert "client_options" not in mock_wrap.call_args.kwargs assert "kind" not in mock_wrap.call_args.kwargs - # Test without kind (e.g. abstract base transport) + # Test for correct handling of abstract base transport NotImplementedError mock_wrap.reset_mock() mock_kind.side_effect = NotImplementedError transport._wrap_with_tracing = True diff --git a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py index 22ef991acbe8..315bc7f47fc4 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -11504,7 +11504,7 @@ def test_cloud_redis_base_transport_wrap_method(): assert "client_options" not in mock_wrap.call_args.kwargs assert "kind" not in mock_wrap.call_args.kwargs - # Test without kind (e.g. abstract base transport) + # Test for correct handling of abstract base transport NotImplementedError mock_wrap.reset_mock() mock_kind.side_effect = NotImplementedError transport._wrap_with_tracing = True diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py index c2afe10ec2d1..8641b3453fa9 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -6742,7 +6742,7 @@ def test_cloud_redis_base_transport_wrap_method(): assert "client_options" not in mock_wrap.call_args.kwargs assert "kind" not in mock_wrap.call_args.kwargs - # Test without kind (e.g. abstract base transport) + # Test for correct handling of abstract base transport NotImplementedError mock_wrap.reset_mock() mock_kind.side_effect = NotImplementedError transport._wrap_with_tracing = True diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py index 3699dc2dbf80..4e245aed3eb7 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py @@ -6807,7 +6807,7 @@ def test_storage_batch_operations_base_transport_wrap_method(): assert "client_options" not in mock_wrap.call_args.kwargs assert "kind" not in mock_wrap.call_args.kwargs - # Test without kind (e.g. abstract base transport) + # Test for correct handling of abstract base transport NotImplementedError mock_wrap.reset_mock() mock_kind.side_effect = NotImplementedError transport._wrap_with_tracing = True From ee5f77828a044dfaa8bc78395810ab83e5785345 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Thu, 17 Sep 2026 06:25:58 -0400 Subject: [PATCH 42/43] refactor(testing): tighten fixture usage and standardize span assertions in system tracing tests Leverage otel_echo_client and span_exporter fixtures to eliminate boilerplate and unify span extraction patterns. --- .../tests/system/test_tracing.py | 122 +++++++----------- 1 file changed, 46 insertions(+), 76 deletions(-) diff --git a/packages/gapic-generator/tests/system/test_tracing.py b/packages/gapic-generator/tests/system/test_tracing.py index 9eec44955d6a..23861e51e3d8 100644 --- a/packages/gapic-generator/tests/system/test_tracing.py +++ b/packages/gapic-generator/tests/system/test_tracing.py @@ -84,11 +84,8 @@ def test_sync_unary_tracing(otel_echo_client): """Verifies that a synchronous unary RPC generates trace spans with expected attributes.""" client, exporter = otel_echo_client - with mock.patch.dict( - os.environ, {"GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED": "true"} - ): - response = client.echo(showcase.EchoRequest(content="hello world")) - assert response.content == "hello world" + response = client.echo(showcase.EchoRequest(content="hello world")) + assert response.content == "hello world" spans = exporter.get_finished_spans() # Synchronous unary calls generate both a Tier 2 method span and a Tier 4 wire span @@ -107,56 +104,42 @@ def test_sync_unary_tracing(otel_echo_client): assert wire_spans[0].attributes["url.domain"] == "googleapis.com" -def test_unary_retries_tracing(span_exporter, use_mtls): +def test_unary_retries_tracing(otel_echo_client): """Verifies that each attempt of a retried RPC generates a separate span.""" - exporter, provider = span_exporter - options = ClientOptions( - tracer_provider=provider, - ) - with mock.patch.dict( - os.environ, {"GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED": "true"} - ): - client = construct_client( - EchoClient, - use_mtls, - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) + client, exporter = otel_echo_client - # Configure a custom retry policy with 2 attempts on DeadlineExceeded - custom_retry = retries.Retry( - predicate=retries.if_exception_type(exceptions.DeadlineExceeded), - initial=0.05, - maximum=0.1, - multiplier=1.0, - deadline=0.3, - ) + # Configure a custom retry policy with 2 attempts on DeadlineExceeded + custom_retry = retries.Retry( + predicate=retries.if_exception_type(exceptions.DeadlineExceeded), + initial=0.05, + maximum=0.1, + multiplier=1.0, + deadline=0.3, + ) - with pytest.raises((exceptions.DeadlineExceeded, exceptions.RetryError)): - client.echo( - { - "error": { - "code": code_pb2.Code.Value("DEADLINE_EXCEEDED"), - "message": "Simulated deadline exceeded error for retry testing.", - }, + with pytest.raises((exceptions.DeadlineExceeded, exceptions.RetryError)): + client.echo( + { + "error": { + "code": code_pb2.Code.Value("DEADLINE_EXCEEDED"), + "message": "Simulated deadline exceeded error for retry testing.", }, - retry=custom_retry, - ) + }, + retry=custom_retry, + ) - spans = exporter.get_finished_spans() - # At least two attempts should have been made and recorded - assert len(spans) >= 2 - for span in spans: - assert span.name == "google.showcase.v1beta1.Echo/Echo" - assert span.attributes.get("rpc.system.name") == "grpc" - assert ( - span.attributes.get("rpc.method") == "google.showcase.v1beta1.Echo/Echo" - ) - # Non-successful attempt should not have rpc.response.status_code == "OK" - assert span.attributes.get("rpc.response.status_code") != "OK" + spans = exporter.get_finished_spans() + # At least two attempts should have been made and recorded + assert len(spans) >= 2 + for span in spans: + assert span.name == "google.showcase.v1beta1.Echo/Echo" + assert span.attributes.get("rpc.system.name") == "grpc" + assert span.attributes.get("rpc.method") == "google.showcase.v1beta1.Echo/Echo" + # Non-successful attempt should not have rpc.response.status_code == "OK" + assert span.attributes.get("rpc.response.status_code") != "OK" -def test_tracing_disabled_default(use_mtls): +def test_tracing_disabled_default(span_exporter, use_mtls): """Verifies that default client options emit zero spans (zero overhead guarantee). Ensures that without setting GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED=true, @@ -164,9 +147,7 @@ def test_tracing_disabled_default(use_mtls): tracing overhead is incurred. Also verifies that passing tracer_provider without the environment variable fails fast by raising FeatureGatingError. """ - exporter = InMemorySpanExporter() - provider = TracerProvider() - provider.add_span_processor(SimpleSpanProcessor(exporter)) + exporter, provider = span_exporter # Providing a tracer_provider without enabling the experimental env var fails fast options_with_provider = ClientOptions( @@ -199,7 +180,8 @@ def test_tracing_disabled_default(use_mtls): assert response.content == "no tracing" # Zero spans must be emitted when tracing is disabled - assert len(exporter.get_finished_spans()) == 0 + spans = exporter.get_finished_spans() + assert len(spans) == 0 def test_custom_tracer_provider(use_mtls): @@ -242,8 +224,10 @@ def test_custom_tracer_provider(use_mtls): response = client.echo(showcase.EchoRequest(content="isolated trace")) assert response.content == "isolated trace" - assert len(custom_exporter.get_finished_spans()) == 2 - assert len(global_exporter.get_finished_spans()) == 0 + custom_spans = custom_exporter.get_finished_spans() + assert len(custom_spans) == 2 + global_spans = global_exporter.get_finished_spans() + assert len(global_spans) == 0 finally: trace.set_tracer_provider(original_provider) @@ -289,28 +273,14 @@ def test_direct_client_initialization_tracing(span_exporter): assert span.attributes.get("rpc.system.name") == "grpc" -def test_env_var_opt_in(span_exporter, use_mtls): +def test_env_var_opt_in(otel_echo_client): """Verifies that setting the environment variable enables tracing without tracing_enabled=True.""" - exporter, provider = span_exporter - - options = ClientOptions( - tracer_provider=provider, - ) + client, exporter = otel_echo_client - env_patch = { - "GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED": "true", - } - with mock.patch.dict(os.environ, env_patch): - client = construct_client( - EchoClient, - use_mtls, - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) - response = client.echo(showcase.EchoRequest(content="env opt in")) - assert response.content == "env opt in" + response = client.echo(showcase.EchoRequest(content="env opt in")) + assert response.content == "env opt in" - spans = exporter.get_finished_spans() - assert len(spans) == 2 - for span in spans: - assert span.name == "google.showcase.v1beta1.Echo/Echo" + spans = exporter.get_finished_spans() + assert len(spans) == 2 + for span in spans: + assert span.name == "google.showcase.v1beta1.Echo/Echo" From 89675eae0f620ae8533eefc5f6c8f8e91f315193 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Thu, 17 Sep 2026 07:34:47 -0400 Subject: [PATCH 43/43] feat(observability): populate status.message span attribute for cross-language parity --- .../tests/system/test_tracing.py | 9 +++++ .../google/api_core/gapic_v1/method.py | 9 +++++ .../tests/unit/gapic/test_method.py | 37 ++++++++++++++++++- 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/packages/gapic-generator/tests/system/test_tracing.py b/packages/gapic-generator/tests/system/test_tracing.py index 23861e51e3d8..56f497968bfc 100644 --- a/packages/gapic-generator/tests/system/test_tracing.py +++ b/packages/gapic-generator/tests/system/test_tracing.py @@ -138,6 +138,15 @@ def test_unary_retries_tracing(otel_echo_client): # Non-successful attempt should not have rpc.response.status_code == "OK" assert span.attributes.get("rpc.response.status_code") != "OK" + # Verify that the parent method span captures status.message for cross-language parity + parent_spans = [s for s in spans if s.parent is None] + assert len(parent_spans) == 1 + assert "status.message" in parent_spans[0].attributes + assert ( + "Simulated deadline exceeded error for retry testing." + in parent_spans[0].attributes["status.message"] + ) + def test_tracing_disabled_default(span_exporter, use_mtls): """Verifies that default client options emit zero spans (zero overhead guarantee). diff --git a/packages/google-api-core/google/api_core/gapic_v1/method.py b/packages/google-api-core/google/api_core/gapic_v1/method.py index 2484831ec07a..656b841a2f26 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/method.py +++ b/packages/google-api-core/google/api_core/gapic_v1/method.py @@ -226,6 +226,15 @@ def _extract_error_attributes(exc: Optional[Exception]) -> dict[str, Any]: for k, v in metadata.items(): attrs[f"gcp.errors.metadata.{k}"] = str(v) + # 5. Extract human-readable error description for cross-language PRD parity + message = getattr(target_exc, "message", None) + if not message and hasattr(target_exc, "details") and callable(target_exc.details): + message = target_exc.details() + if not message and isinstance(target_exc, Exception): + message = str(target_exc) + if message: + attrs["status.message"] = str(message) + return attrs diff --git a/packages/google-api-core/tests/unit/gapic/test_method.py b/packages/google-api-core/tests/unit/gapic/test_method.py index 1a265e183077..eed8e9949497 100644 --- a/packages/google-api-core/tests/unit/gapic/test_method.py +++ b/packages/google-api-core/tests/unit/gapic/test_method.py @@ -529,6 +529,9 @@ def test_wrap_method_otel_tracing_enabled_error(mock_otel): "rpc.response.status_code", "RuntimeError" ) mock_otel.span.set_attribute.assert_any_call("error.type", "RuntimeError") + mock_otel.span.set_attribute.assert_any_call( + "status.message", "gRPC connection reset" + ) @pytest.mark.parametrize( @@ -562,6 +565,8 @@ def test_wrap_method_otel_tracing_error_status_code_mapping( "rpc.response.status_code", expected_status ) mock_otel.span.set_attribute.assert_any_call("error.type", expected_status) + expected_msg = exc.cause.message if getattr(exc, "cause", None) else exc.message + mock_otel.span.set_attribute.assert_any_call("status.message", expected_msg) def test_wrap_method_otel_tracing_import_error(monkeypatch): @@ -692,10 +697,10 @@ def test_extract_error_attributes_standard_exception(): """Proves that _extract_error_attributes returns fallback error.type for exceptions without ErrorInfo.""" assert google.api_core.gapic_v1.method._extract_error_attributes( ValueError("fail") - ) == {"error.type": "ValueError"} + ) == {"error.type": "ValueError", "status.message": "fail"} assert google.api_core.gapic_v1.method._extract_error_attributes( exceptions.InvalidArgument("invalid argument") - ) == {"error.type": "INVALID_ARGUMENT"} + ) == {"error.type": "INVALID_ARGUMENT", "status.message": "invalid argument"} assert google.api_core.gapic_v1.method._extract_error_attributes(None) == {} @@ -749,6 +754,7 @@ def test_wrap_method_otel_tracing_records_gcp_error_attributes(mock_otel): mock_otel.span.set_attribute.assert_any_call( "gcp.errors.metadata.quota_limit", "100" ) + mock_otel.span.set_attribute.assert_any_call("status.message", "quota exceeded") def test_extract_status_code_variations(): @@ -873,6 +879,33 @@ def test_extract_error_attributes_variations(): "error.type": "SimpleNamespace" } + # 7. status.message extraction from .message attribute + exc_with_msg = types.SimpleNamespace(message="api call failed") + assert _extract_error_attributes(exc_with_msg) == { + "error.type": "SimpleNamespace", + "status.message": "api call failed", + } + + # 8. status.message extraction from .details() callable (e.g. gRPC RpcError) + exc_with_details = types.SimpleNamespace(details=lambda: "rpc deadline exceeded") + assert _extract_error_attributes(exc_with_details) == { + "error.type": "SimpleNamespace", + "status.message": "rpc deadline exceeded", + } + + # 9. status.message extraction from Exception string representation + exc_standard = ValueError("invalid argument passed") + assert _extract_error_attributes(exc_standard) == { + "error.type": "ValueError", + "status.message": "invalid argument passed", + } + + # 10. Exception with empty message string does not populate status.message + exc_empty_msg = ValueError("") + assert _extract_error_attributes(exc_empty_msg) == { + "error.type": "ValueError", + } + def test_wrap_method_otel_tracing_partial_span_capabilities(mock_otel): """Proves handling when span has or lacks set_attribute."""