From 63b8a43ce25a5305664424fa247ad82595c4342f Mon Sep 17 00:00:00 2001 From: Dan O'Meara Date: Thu, 19 Nov 2020 13:48:06 -0800 Subject: [PATCH] feat!: use microgenerator (#54) --- .coveragerc | 16 +- UPGRADING.md | 152 + docs/UPGRADING.md | 1 + docs/conf.py | 6 +- docs/gapic/v1/api.rst | 6 - docs/gapic/v1/types.rst | 5 - docs/gapic/v1beta1/api.rst | 6 - docs/gapic/v1beta1/types.rst | 5 - docs/index.rst | 19 +- docs/recommender_v1/services.rst | 6 + docs/recommender_v1/types.rst | 6 + docs/recommender_v1beta1/services.rst | 6 + docs/recommender_v1beta1/types.rst | 6 + google/cloud/recommender/__init__.py | 80 + google/cloud/recommender/py.typed | 2 + google/cloud/recommender_v1/__init__.py | 70 +- google/cloud/recommender_v1/gapic/__init__.py | 0 google/cloud/recommender_v1/gapic/enums.py | 134 - .../gapic/recommender_client.py | 970 ----- .../gapic/recommender_client_config.py | 82 - .../gapic/transports/__init__.py | 0 .../transports/recommender_grpc_transport.py | 251 -- google/cloud/recommender_v1/proto/__init__.py | 0 .../cloud/recommender_v1/proto/insight_pb2.py | 666 ---- .../recommender_v1/proto/insight_pb2_grpc.py | 3 - .../proto/recommendation_pb2.py | 1525 -------- .../proto/recommendation_pb2_grpc.py | 3 - .../proto/recommender_service_pb2.py | 1471 -------- .../proto/recommender_service_pb2_grpc.py | 460 --- google/cloud/recommender_v1/py.typed | 2 + .../services/__init__.py} | 19 +- .../services/recommender}/__init__.py | 18 +- .../services/recommender/async_client.py | 957 +++++ .../services/recommender/client.py | 1186 +++++++ .../services/recommender/pagers.py | 282 ++ .../recommender/transports/__init__.py | 36 + .../services/recommender/transports/base.py | 276 ++ .../services/recommender/transports/grpc.py | 508 +++ .../recommender/transports/grpc_asyncio.py | 515 +++ google/cloud/recommender_v1/types.py | 58 - google/cloud/recommender_v1/types/__init__.py | 67 + google/cloud/recommender_v1/types/insight.py | 140 + .../recommender_v1/types/recommendation.py | 353 ++ .../types/recommender_service.py | 278 ++ google/cloud/recommender_v1beta1/__init__.py | 70 +- .../recommender_v1beta1/gapic/__init__.py | 0 .../cloud/recommender_v1beta1/gapic/enums.py | 134 - .../gapic/recommender_client.py | 970 ----- .../gapic/recommender_client_config.py | 82 - .../gapic/transports/__init__.py | 0 .../transports/recommender_grpc_transport.py | 251 -- .../recommender_v1beta1/proto/__init__.py | 0 .../recommender_v1beta1/proto/insight_pb2.py | 666 ---- .../proto/insight_pb2_grpc.py | 3 - .../proto/recommendation.proto | 234 -- .../proto/recommendation_pb2.py | 1525 -------- .../proto/recommendation_pb2_grpc.py | 3 - .../proto/recommender_service.proto | 190 - .../proto/recommender_service_pb2.py | 1471 -------- .../proto/recommender_service_pb2_grpc.py | 460 --- google/cloud/recommender_v1beta1/py.typed | 2 + .../recommender_v1beta1/services/__init__.py | 16 + .../services/recommender}/__init__.py | 18 +- .../services/recommender/async_client.py | 957 +++++ .../services/recommender/client.py | 1186 +++++++ .../services/recommender/pagers.py | 282 ++ .../recommender/transports/__init__.py | 36 + .../services/recommender/transports/base.py | 276 ++ .../services/recommender/transports/grpc.py | 508 +++ .../recommender/transports/grpc_asyncio.py | 515 +++ google/cloud/recommender_v1beta1/types.py | 58 - .../recommender_v1beta1/types/__init__.py | 67 + .../recommender_v1beta1/types/insight.py | 141 + .../types/recommendation.py | 353 ++ .../types/recommender_service.py | 278 ++ mypy.ini | 2 +- noxfile.py | 8 +- samples/AUTHORING_GUIDE.md | 1 + samples/CONTRIBUTING.md | 1 + scripts/fixup_recommender_v1_keywords.py | 186 + scripts/fixup_recommender_v1beta1_keywords.py | 186 + setup.py | 17 +- synth.metadata | 117 +- synth.py | 39 +- tests/unit/gapic/recommender_v1/__init__.py | 1 + .../gapic/recommender_v1/test_recommender.py | 3115 +++++++++++++++++ .../gapic/recommender_v1beta1/__init__.py | 1 + .../recommender_v1beta1/test_recommender.py | 3115 +++++++++++++++++ .../gapic/v1/test_recommender_client_v1.py | 474 --- .../test_recommender_client_v1beta1.py | 474 --- 90 files changed, 16256 insertions(+), 12885 deletions(-) create mode 100644 UPGRADING.md create mode 120000 docs/UPGRADING.md delete mode 100644 docs/gapic/v1/api.rst delete mode 100644 docs/gapic/v1/types.rst delete mode 100644 docs/gapic/v1beta1/api.rst delete mode 100644 docs/gapic/v1beta1/types.rst create mode 100644 docs/recommender_v1/services.rst create mode 100644 docs/recommender_v1/types.rst create mode 100644 docs/recommender_v1beta1/services.rst create mode 100644 docs/recommender_v1beta1/types.rst create mode 100644 google/cloud/recommender/__init__.py create mode 100644 google/cloud/recommender/py.typed delete mode 100644 google/cloud/recommender_v1/gapic/__init__.py delete mode 100644 google/cloud/recommender_v1/gapic/enums.py delete mode 100644 google/cloud/recommender_v1/gapic/recommender_client.py delete mode 100644 google/cloud/recommender_v1/gapic/recommender_client_config.py delete mode 100644 google/cloud/recommender_v1/gapic/transports/__init__.py delete mode 100644 google/cloud/recommender_v1/gapic/transports/recommender_grpc_transport.py delete mode 100644 google/cloud/recommender_v1/proto/__init__.py delete mode 100644 google/cloud/recommender_v1/proto/insight_pb2.py delete mode 100644 google/cloud/recommender_v1/proto/insight_pb2_grpc.py delete mode 100644 google/cloud/recommender_v1/proto/recommendation_pb2.py delete mode 100644 google/cloud/recommender_v1/proto/recommendation_pb2_grpc.py delete mode 100644 google/cloud/recommender_v1/proto/recommender_service_pb2.py delete mode 100644 google/cloud/recommender_v1/proto/recommender_service_pb2_grpc.py create mode 100644 google/cloud/recommender_v1/py.typed rename google/cloud/{recommender.py => recommender_v1/services/__init__.py} (64%) rename google/{ => cloud/recommender_v1/services/recommender}/__init__.py (71%) create mode 100644 google/cloud/recommender_v1/services/recommender/async_client.py create mode 100644 google/cloud/recommender_v1/services/recommender/client.py create mode 100644 google/cloud/recommender_v1/services/recommender/pagers.py create mode 100644 google/cloud/recommender_v1/services/recommender/transports/__init__.py create mode 100644 google/cloud/recommender_v1/services/recommender/transports/base.py create mode 100644 google/cloud/recommender_v1/services/recommender/transports/grpc.py create mode 100644 google/cloud/recommender_v1/services/recommender/transports/grpc_asyncio.py delete mode 100644 google/cloud/recommender_v1/types.py create mode 100644 google/cloud/recommender_v1/types/__init__.py create mode 100644 google/cloud/recommender_v1/types/insight.py create mode 100644 google/cloud/recommender_v1/types/recommendation.py create mode 100644 google/cloud/recommender_v1/types/recommender_service.py delete mode 100644 google/cloud/recommender_v1beta1/gapic/__init__.py delete mode 100644 google/cloud/recommender_v1beta1/gapic/enums.py delete mode 100644 google/cloud/recommender_v1beta1/gapic/recommender_client.py delete mode 100644 google/cloud/recommender_v1beta1/gapic/recommender_client_config.py delete mode 100644 google/cloud/recommender_v1beta1/gapic/transports/__init__.py delete mode 100644 google/cloud/recommender_v1beta1/gapic/transports/recommender_grpc_transport.py delete mode 100644 google/cloud/recommender_v1beta1/proto/__init__.py delete mode 100644 google/cloud/recommender_v1beta1/proto/insight_pb2.py delete mode 100644 google/cloud/recommender_v1beta1/proto/insight_pb2_grpc.py delete mode 100644 google/cloud/recommender_v1beta1/proto/recommendation.proto delete mode 100644 google/cloud/recommender_v1beta1/proto/recommendation_pb2.py delete mode 100644 google/cloud/recommender_v1beta1/proto/recommendation_pb2_grpc.py delete mode 100644 google/cloud/recommender_v1beta1/proto/recommender_service.proto delete mode 100644 google/cloud/recommender_v1beta1/proto/recommender_service_pb2.py delete mode 100644 google/cloud/recommender_v1beta1/proto/recommender_service_pb2_grpc.py create mode 100644 google/cloud/recommender_v1beta1/py.typed create mode 100644 google/cloud/recommender_v1beta1/services/__init__.py rename google/cloud/{ => recommender_v1beta1/services/recommender}/__init__.py (71%) create mode 100644 google/cloud/recommender_v1beta1/services/recommender/async_client.py create mode 100644 google/cloud/recommender_v1beta1/services/recommender/client.py create mode 100644 google/cloud/recommender_v1beta1/services/recommender/pagers.py create mode 100644 google/cloud/recommender_v1beta1/services/recommender/transports/__init__.py create mode 100644 google/cloud/recommender_v1beta1/services/recommender/transports/base.py create mode 100644 google/cloud/recommender_v1beta1/services/recommender/transports/grpc.py create mode 100644 google/cloud/recommender_v1beta1/services/recommender/transports/grpc_asyncio.py delete mode 100644 google/cloud/recommender_v1beta1/types.py create mode 100644 google/cloud/recommender_v1beta1/types/__init__.py create mode 100644 google/cloud/recommender_v1beta1/types/insight.py create mode 100644 google/cloud/recommender_v1beta1/types/recommendation.py create mode 100644 google/cloud/recommender_v1beta1/types/recommender_service.py create mode 100644 samples/AUTHORING_GUIDE.md create mode 100644 samples/CONTRIBUTING.md create mode 100644 scripts/fixup_recommender_v1_keywords.py create mode 100644 scripts/fixup_recommender_v1beta1_keywords.py create mode 100644 tests/unit/gapic/recommender_v1/__init__.py create mode 100644 tests/unit/gapic/recommender_v1/test_recommender.py create mode 100644 tests/unit/gapic/recommender_v1beta1/__init__.py create mode 100644 tests/unit/gapic/recommender_v1beta1/test_recommender.py delete mode 100644 tests/unit/gapic/v1/test_recommender_client_v1.py delete mode 100644 tests/unit/gapic/v1beta1/test_recommender_client_v1beta1.py diff --git a/.coveragerc b/.coveragerc index 0d8e629..e1eed34 100644 --- a/.coveragerc +++ b/.coveragerc @@ -17,22 +17,18 @@ # Generated by synthtool. DO NOT EDIT! [run] branch = True -omit = - google/cloud/__init__.py [report] fail_under = 100 show_missing = True +omit = google/cloud/recommender/__init__.py exclude_lines = # Re-enable the standard pragma pragma: NO COVER # Ignore debug-only repr def __repr__ - # Ignore abstract methods - raise NotImplementedError -omit = - */gapic/*.py - */proto/*.py - */core/*.py - */site-packages/*.py - google/cloud/__init__.py + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/UPGRADING.md b/UPGRADING.md new file mode 100644 index 0000000..63a046d --- /dev/null +++ b/UPGRADING.md @@ -0,0 +1,152 @@ +# 2.0.0 Migration Guide + +The 2.0 release of the `google-cloud-recommender` client is a significant upgrade based on a [next-gen code generator](https://github.com/googleapis/gapic-generator-python), and includes substantial interface changes. Existing code written for earlier versions of this library will likely require updates to use this version. This document describes the changes that have been made, and what you need to do to update your usage. + +If you experience issues or have questions, please file an [issue](https://github.com/googleapis/python-recommender/issues). + +## Supported Python Versions + +> **WARNING**: Breaking change + +The 2.0.0 release requires Python 3.6+. + + +## Method Calls + +> **WARNING**: Breaking change + +Methods expect request objects. We provide a script that will convert most common use cases. + +* Install the library + +```py +python3 -m pip install google-cloud-recommender +``` + +* The script `fixup_recommender_v1_keywords.py` is shipped with the library. It expects +an input directory (with the code to convert) and an empty destination directory. + +```sh +$ fixup_recommender_v1_keywords.py --input-directory .samples/ --output-directory samples/ +``` + +**Before:** +```py +from google.cloud import recommender + +client = recommender.RecommenderClient() +name = client.insight_path('[PROJECT]', '[LOCATION]', '[INSIGHT_TYPE]', '[INSIGHT]') +etag = "my_etag" +response = client.mark_insight_accepted(name=name, etag=etag) +``` + + +**After:** +```py +from google.cloud import recommender + +client = recommender.RecommenderClient() +name = client.insight_path('[PROJECT]', '[LOCATION]', '[INSIGHT_TYPE]', '[INSIGHT]') +etag = "my_etag" +response = client.mark_insight_accepted(request={"name": name, "etag": etag}) +``` + +### More Details + +In `google-cloud-recommender<2.0.0`, parameters required by the API were positional parameters and optional parameters were keyword parameters. + +**Before:** +```py + def mark_insight_accepted( + self, + name, + etag, + state_metadata=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, + metadata=None, + ): +``` + +In the 2.0.0 release, all methods have a single positional parameter `request`. Method docstrings indicate whether a parameter is required or optional. + +Some methods have additional keyword only parameters. The available parameters depend on the [`google.api.method_signature` annotation](https://github.com/googleapis/googleapis/blob/master/google/cloud/recommender/v1/recommender_service.proto#L70) specified by the API producer. + + +**After:** +```py + def mark_insight_accepted( + self, + request: recommender_service.MarkInsightAcceptedRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkInsightAcceptedRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> insight.Insight: +``` + +> **NOTE:** The `request` parameter and flattened keyword parameters for the API are mutually exclusive. +> Passing both will result in an error. + + +Both of these calls are valid: + +```py +response = client.mark_insight_accepted( + request={ + "name": name, + "etag": my_etag + } +) +``` + +```py +response = client.mark_insight_accepted( + name=name, + etag=my_etag +) +``` + +This call is invalid because it mixes `request` with a keyword argument `etag`. Executing this code +will result in an error. + +```py +response = client.mark_insight_accepted( + request={ + "name": name + }, + etag=my_etag +) +``` + + + +## Enums and Types + + +> **WARNING**: Breaking change + +The submodules `enums` and `types` have been removed. + +**Before:** +```py + +from google.cloud import recommender + +insight = recommender.enums.Insight.Category.PERFORMANCE] +cost_projection = recommender.types.CostProjection() +``` + + +**After:** +```py +from google.cloud import recommender + +features = recommender.Insight.Category.PERFORMANCE +cost_projection = recommender.CostProjection() +``` \ No newline at end of file diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md new file mode 120000 index 0000000..01097c8 --- /dev/null +++ b/docs/UPGRADING.md @@ -0,0 +1 @@ +../UPGRADING.md \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py index 3c6f8d0..89c9e29 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -345,10 +345,10 @@ # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), - "grpc": ("https://grpc.io/grpc/python/", None), + "grpc": ("https://grpc.github.io/grpc/python/", None), "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), } diff --git a/docs/gapic/v1/api.rst b/docs/gapic/v1/api.rst deleted file mode 100644 index ad04dd4..0000000 --- a/docs/gapic/v1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Recommender API -========================== - -.. automodule:: google.cloud.recommender_v1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1/types.rst b/docs/gapic/v1/types.rst deleted file mode 100644 index 7ba8521..0000000 --- a/docs/gapic/v1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Recommender API Client -================================ - -.. automodule:: google.cloud.recommender_v1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v1beta1/api.rst b/docs/gapic/v1beta1/api.rst deleted file mode 100644 index d9458d2..0000000 --- a/docs/gapic/v1beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Recommender API -========================== - -.. automodule:: google.cloud.recommender_v1beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1beta1/types.rst b/docs/gapic/v1beta1/types.rst deleted file mode 100644 index 3771da4..0000000 --- a/docs/gapic/v1beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Recommender API Client -================================ - -.. automodule:: google.cloud.recommender_v1beta1.types - :members: \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index 378b403..2a0bac6 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -13,8 +13,8 @@ v1 .. toctree:: :maxdepth: 2 - gapic/v1/api - gapic/v1/types + recommender_v1/services + recommender_v1/types v1beta1 ======= @@ -22,5 +22,16 @@ v1beta1 .. toctree:: :maxdepth: 2 - gapic/v1beta1/api - gapic/v1beta1/types \ No newline at end of file + recommender_v1beta1/services + recommender_v1beta1/types + + +Migration Guide +--------------- + +See the guide below for instructions on migrating to the 2.x release of this library. + +.. toctree:: + :maxdepth: 2 + + UPGRADING \ No newline at end of file diff --git a/docs/recommender_v1/services.rst b/docs/recommender_v1/services.rst new file mode 100644 index 0000000..64345c5 --- /dev/null +++ b/docs/recommender_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Recommender v1 API +============================================ + +.. automodule:: google.cloud.recommender_v1.services.recommender + :members: + :inherited-members: diff --git a/docs/recommender_v1/types.rst b/docs/recommender_v1/types.rst new file mode 100644 index 0000000..99c254c --- /dev/null +++ b/docs/recommender_v1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Recommender v1 API +========================================= + +.. automodule:: google.cloud.recommender_v1.types + :members: + :show-inheritance: diff --git a/docs/recommender_v1beta1/services.rst b/docs/recommender_v1beta1/services.rst new file mode 100644 index 0000000..5b4764d --- /dev/null +++ b/docs/recommender_v1beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Recommender v1beta1 API +================================================= + +.. automodule:: google.cloud.recommender_v1beta1.services.recommender + :members: + :inherited-members: diff --git a/docs/recommender_v1beta1/types.rst b/docs/recommender_v1beta1/types.rst new file mode 100644 index 0000000..c16ac11 --- /dev/null +++ b/docs/recommender_v1beta1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Recommender v1beta1 API +============================================== + +.. automodule:: google.cloud.recommender_v1beta1.types + :members: + :show-inheritance: diff --git a/google/cloud/recommender/__init__.py b/google/cloud/recommender/__init__.py new file mode 100644 index 0000000..f2de80d --- /dev/null +++ b/google/cloud/recommender/__init__.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.recommender_v1.services.recommender.async_client import ( + RecommenderAsyncClient, +) +from google.cloud.recommender_v1.services.recommender.client import RecommenderClient +from google.cloud.recommender_v1.types.insight import Insight +from google.cloud.recommender_v1.types.insight import InsightStateInfo +from google.cloud.recommender_v1.types.recommendation import CostProjection +from google.cloud.recommender_v1.types.recommendation import Impact +from google.cloud.recommender_v1.types.recommendation import Operation +from google.cloud.recommender_v1.types.recommendation import OperationGroup +from google.cloud.recommender_v1.types.recommendation import Recommendation +from google.cloud.recommender_v1.types.recommendation import RecommendationContent +from google.cloud.recommender_v1.types.recommendation import RecommendationStateInfo +from google.cloud.recommender_v1.types.recommendation import ValueMatcher +from google.cloud.recommender_v1.types.recommender_service import GetInsightRequest +from google.cloud.recommender_v1.types.recommender_service import ( + GetRecommendationRequest, +) +from google.cloud.recommender_v1.types.recommender_service import ListInsightsRequest +from google.cloud.recommender_v1.types.recommender_service import ListInsightsResponse +from google.cloud.recommender_v1.types.recommender_service import ( + ListRecommendationsRequest, +) +from google.cloud.recommender_v1.types.recommender_service import ( + ListRecommendationsResponse, +) +from google.cloud.recommender_v1.types.recommender_service import ( + MarkInsightAcceptedRequest, +) +from google.cloud.recommender_v1.types.recommender_service import ( + MarkRecommendationClaimedRequest, +) +from google.cloud.recommender_v1.types.recommender_service import ( + MarkRecommendationFailedRequest, +) +from google.cloud.recommender_v1.types.recommender_service import ( + MarkRecommendationSucceededRequest, +) + +__all__ = ( + "CostProjection", + "GetInsightRequest", + "GetRecommendationRequest", + "Impact", + "Insight", + "InsightStateInfo", + "ListInsightsRequest", + "ListInsightsResponse", + "ListRecommendationsRequest", + "ListRecommendationsResponse", + "MarkInsightAcceptedRequest", + "MarkRecommendationClaimedRequest", + "MarkRecommendationFailedRequest", + "MarkRecommendationSucceededRequest", + "Operation", + "OperationGroup", + "Recommendation", + "RecommendationContent", + "RecommendationStateInfo", + "RecommenderAsyncClient", + "RecommenderClient", + "ValueMatcher", +) diff --git a/google/cloud/recommender/py.typed b/google/cloud/recommender/py.typed new file mode 100644 index 0000000..f9105be --- /dev/null +++ b/google/cloud/recommender/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-recommender package uses inline types. diff --git a/google/cloud/recommender_v1/__init__.py b/google/cloud/recommender_v1/__init__.py index 05e20d3..dbae64e 100644 --- a/google/cloud/recommender_v1/__init__.py +++ b/google/cloud/recommender_v1/__init__.py @@ -1,45 +1,63 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# - -from __future__ import absolute_import -import sys -import warnings - -from google.cloud.recommender_v1 import types -from google.cloud.recommender_v1.gapic import enums -from google.cloud.recommender_v1.gapic import recommender_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class RecommenderClient(recommender_client.RecommenderClient): - __doc__ = recommender_client.RecommenderClient.__doc__ - enums = enums +from .services.recommender import RecommenderClient +from .types.insight import Insight +from .types.insight import InsightStateInfo +from .types.recommendation import CostProjection +from .types.recommendation import Impact +from .types.recommendation import Operation +from .types.recommendation import OperationGroup +from .types.recommendation import Recommendation +from .types.recommendation import RecommendationContent +from .types.recommendation import RecommendationStateInfo +from .types.recommendation import ValueMatcher +from .types.recommender_service import GetInsightRequest +from .types.recommender_service import GetRecommendationRequest +from .types.recommender_service import ListInsightsRequest +from .types.recommender_service import ListInsightsResponse +from .types.recommender_service import ListRecommendationsRequest +from .types.recommender_service import ListRecommendationsResponse +from .types.recommender_service import MarkInsightAcceptedRequest +from .types.recommender_service import MarkRecommendationClaimedRequest +from .types.recommender_service import MarkRecommendationFailedRequest +from .types.recommender_service import MarkRecommendationSucceededRequest __all__ = ( - "enums", - "types", + "CostProjection", + "GetInsightRequest", + "GetRecommendationRequest", + "Impact", + "Insight", + "InsightStateInfo", + "ListInsightsRequest", + "ListInsightsResponse", + "ListRecommendationsRequest", + "ListRecommendationsResponse", + "MarkInsightAcceptedRequest", + "MarkRecommendationClaimedRequest", + "MarkRecommendationFailedRequest", + "MarkRecommendationSucceededRequest", + "Operation", + "OperationGroup", + "Recommendation", + "RecommendationContent", + "RecommendationStateInfo", + "ValueMatcher", "RecommenderClient", ) diff --git a/google/cloud/recommender_v1/gapic/__init__.py b/google/cloud/recommender_v1/gapic/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/recommender_v1/gapic/enums.py b/google/cloud/recommender_v1/gapic/enums.py deleted file mode 100644 index a794132..0000000 --- a/google/cloud/recommender_v1/gapic/enums.py +++ /dev/null @@ -1,134 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class NullValue(enum.IntEnum): - """ - ``NullValue`` is a singleton enumeration to represent the null value - for the ``Value`` type union. - - The JSON representation for ``NullValue`` is JSON ``null``. - - Attributes: - NULL_VALUE (int): Null value. - """ - - NULL_VALUE = 0 - - -class Impact(object): - class Category(enum.IntEnum): - """ - The category of the impact. - - Attributes: - CATEGORY_UNSPECIFIED (int): Default unspecified category. Don't use directly. - COST (int): Indicates a potential increase or decrease in cost. - SECURITY (int): Indicates a potential increase or decrease in security. - PERFORMANCE (int): Indicates a potential increase or decrease in performance. - MANAGEABILITY (int): Indicates a potential increase or decrease in manageability. - """ - - CATEGORY_UNSPECIFIED = 0 - COST = 1 - SECURITY = 2 - PERFORMANCE = 3 - MANAGEABILITY = 4 - - -class Insight(object): - class Category(enum.IntEnum): - """ - Insight category. - - Attributes: - CATEGORY_UNSPECIFIED (int): Unspecified category. - COST (int): The insight is related to cost. - SECURITY (int): The insight is related to security. - PERFORMANCE (int): The insight is related to performance. - MANAGEABILITY (int): This insight is related to manageability. - """ - - CATEGORY_UNSPECIFIED = 0 - COST = 1 - SECURITY = 2 - PERFORMANCE = 3 - MANAGEABILITY = 4 - - -class InsightStateInfo(object): - class State(enum.IntEnum): - """ - Represents insight state. - - Attributes: - STATE_UNSPECIFIED (int): Unspecified state. - ACTIVE (int): Insight is active. Content for ACTIVE insights can be updated by Google. - ACTIVE insights can be marked DISMISSED OR ACCEPTED. - ACCEPTED (int): Some action has been taken based on this insight. Insights become - accepted when a recommendation derived from the insight has been marked - CLAIMED, SUCCEEDED, or FAILED. ACTIVE insights can also be marked - ACCEPTED explicitly. Content for ACCEPTED insights is immutable. ACCEPTED - insights can only be marked ACCEPTED (which may update state metadata). - DISMISSED (int): Insight is dismissed. Content for DISMISSED insights can be updated by - Google. DISMISSED insights can be marked as ACTIVE. - """ - - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - ACCEPTED = 2 - DISMISSED = 3 - - -class RecommendationStateInfo(object): - class State(enum.IntEnum): - """ - Represents Recommendation State. - - Attributes: - STATE_UNSPECIFIED (int): Default state. Don't use directly. - ACTIVE (int): Recommendation is active and can be applied. Recommendations content can - be updated by Google. - - ACTIVE recommendations can be marked as CLAIMED, SUCCEEDED, or FAILED. - CLAIMED (int): Recommendation is in claimed state. Recommendations content is - immutable and cannot be updated by Google. - - CLAIMED recommendations can be marked as CLAIMED, SUCCEEDED, or FAILED. - SUCCEEDED (int): Recommendation is in succeeded state. Recommendations content is - immutable and cannot be updated by Google. - - SUCCEEDED recommendations can be marked as SUCCEEDED, or FAILED. - FAILED (int): Recommendation is in failed state. Recommendations content is immutable - and cannot be updated by Google. - - FAILED recommendations can be marked as SUCCEEDED, or FAILED. - DISMISSED (int): Recommendation is in dismissed state. Recommendation content can be - updated by Google. - - DISMISSED recommendations can be marked as ACTIVE. - """ - - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - CLAIMED = 6 - SUCCEEDED = 3 - FAILED = 4 - DISMISSED = 5 diff --git a/google/cloud/recommender_v1/gapic/recommender_client.py b/google/cloud/recommender_v1/gapic/recommender_client.py deleted file mode 100644 index 26bac72..0000000 --- a/google/cloud/recommender_v1/gapic/recommender_client.py +++ /dev/null @@ -1,970 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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. - -"""Accesses the google.cloud.recommender.v1 Recommender API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.page_iterator -import google.api_core.path_template -import grpc - -from google.cloud.recommender_v1.gapic import enums -from google.cloud.recommender_v1.gapic import recommender_client_config -from google.cloud.recommender_v1.gapic.transports import recommender_grpc_transport -from google.cloud.recommender_v1.proto import insight_pb2 -from google.cloud.recommender_v1.proto import recommendation_pb2 -from google.cloud.recommender_v1.proto import recommender_service_pb2 -from google.cloud.recommender_v1.proto import recommender_service_pb2_grpc - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( - "google-cloud-recommender", -).version - - -class RecommenderClient(object): - """ - Provides insights and recommendations for cloud customers for various - categories like performance optimization, cost savings, reliability, feature - discovery, etc. Insights and recommendations are generated automatically - based on analysis of user resources, configuration and monitoring metrics. - """ - - SERVICE_ADDRESS = "recommender.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.recommender.v1.Recommender" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RecommenderClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def insight_path(cls, project, location, insight_type, insight): - """Return a fully-qualified insight string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/insightTypes/{insight_type}/insights/{insight}", - project=project, - location=location, - insight_type=insight_type, - insight=insight, - ) - - @classmethod - def insight_type_path(cls, project, location, insight_type): - """Return a fully-qualified insight_type string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/insightTypes/{insight_type}", - project=project, - location=location, - insight_type=insight_type, - ) - - @classmethod - def recommendation_path(cls, project, location, recommender, recommendation): - """Return a fully-qualified recommendation string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/recommenders/{recommender}/recommendations/{recommendation}", - project=project, - location=location, - recommender=recommender, - recommendation=recommendation, - ) - - @classmethod - def recommender_path(cls, project, location, recommender): - """Return a fully-qualified recommender string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/recommenders/{recommender}", - project=project, - location=location, - recommender=recommender, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.RecommenderGrpcTransport, - Callable[[~.Credentials, type], ~.RecommenderGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = recommender_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=recommender_grpc_transport.RecommenderGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = recommender_grpc_transport.RecommenderGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def list_insights( - self, - parent, - page_size=None, - filter_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists insights for a Cloud project. Requires the recommender.*.list - IAM permission for the specified insight type. - - Example: - >>> from google.cloud import recommender_v1 - >>> - >>> client = recommender_v1.RecommenderClient() - >>> - >>> parent = client.insight_type_path('[PROJECT]', '[LOCATION]', '[INSIGHT_TYPE]') - >>> - >>> # Iterate over all results - >>> for element in client.list_insights(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_insights(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The container resource on which to execute the request. - Acceptable formats: - - 1. - - "projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]", - - LOCATION here refers to GCP Locations: - https://cloud.google.com/about/locations/ - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - filter_ (str): Optional. Filter expression to restrict the insights returned. - Supported filter fields: state Eg: \`state:"DISMISSED" or state:"ACTIVE" - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.recommender_v1.types.Insight` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_insights" not in self._inner_api_calls: - self._inner_api_calls[ - "list_insights" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_insights, - default_retry=self._method_configs["ListInsights"].retry, - default_timeout=self._method_configs["ListInsights"].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.ListInsightsRequest( - parent=parent, page_size=page_size, filter=filter_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_insights"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="insights", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_insight( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the requested insight. Requires the recommender.*.get IAM - permission for the specified insight type. - - Example: - >>> from google.cloud import recommender_v1 - >>> - >>> client = recommender_v1.RecommenderClient() - >>> - >>> name = client.insight_path('[PROJECT]', '[LOCATION]', '[INSIGHT_TYPE]', '[INSIGHT]') - >>> - >>> response = client.get_insight(name) - - Args: - name (str): Required. Name of the insight. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.recommender_v1.types.Insight` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_insight" not in self._inner_api_calls: - self._inner_api_calls[ - "get_insight" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_insight, - default_retry=self._method_configs["GetInsight"].retry, - default_timeout=self._method_configs["GetInsight"].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.GetInsightRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_insight"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def mark_insight_accepted( - self, - name, - etag, - state_metadata=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Marks the Insight State as Accepted. Users can use this method to - indicate to the Recommender API that they have applied some action based - on the insight. This stops the insight content from being updated. - - MarkInsightAccepted can be applied to insights in ACTIVE state. Requires - the recommender.*.update IAM permission for the specified insight. - - Example: - >>> from google.cloud import recommender_v1 - >>> - >>> client = recommender_v1.RecommenderClient() - >>> - >>> name = client.insight_path('[PROJECT]', '[LOCATION]', '[INSIGHT_TYPE]', '[INSIGHT]') - >>> - >>> # TODO: Initialize `etag`: - >>> etag = '' - >>> - >>> response = client.mark_insight_accepted(name, etag) - - Args: - name (str): Required. Name of the insight. - etag (str): Required. Fingerprint of the Insight. Provides optimistic locking. - state_metadata (dict[str -> str]): Optional. State properties user wish to include with this state. - Full replace of the current state_metadata. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.recommender_v1.types.Insight` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "mark_insight_accepted" not in self._inner_api_calls: - self._inner_api_calls[ - "mark_insight_accepted" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.mark_insight_accepted, - default_retry=self._method_configs["MarkInsightAccepted"].retry, - default_timeout=self._method_configs["MarkInsightAccepted"].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.MarkInsightAcceptedRequest( - name=name, etag=etag, state_metadata=state_metadata, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["mark_insight_accepted"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_recommendations( - self, - parent, - page_size=None, - filter_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists recommendations for a Cloud project. Requires the - recommender.*.list IAM permission for the specified recommender. - - Example: - >>> from google.cloud import recommender_v1 - >>> - >>> client = recommender_v1.RecommenderClient() - >>> - >>> parent = client.recommender_path('[PROJECT]', '[LOCATION]', '[RECOMMENDER]') - >>> - >>> # Iterate over all results - >>> for element in client.list_recommendations(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_recommendations(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The container resource on which to execute the request. - Acceptable formats: - - 1. - - "projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]", - - LOCATION here refers to GCP Locations: - https://cloud.google.com/about/locations/ - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - filter_ (str): Filter expression to restrict the recommendations returned. - Supported filter fields: state_info.state Eg: - \`state_info.state:"DISMISSED" or state_info.state:"FAILED" - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.recommender_v1.types.Recommendation` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_recommendations" not in self._inner_api_calls: - self._inner_api_calls[ - "list_recommendations" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_recommendations, - default_retry=self._method_configs["ListRecommendations"].retry, - default_timeout=self._method_configs["ListRecommendations"].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.ListRecommendationsRequest( - parent=parent, page_size=page_size, filter=filter_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_recommendations"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="recommendations", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_recommendation( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the requested recommendation. Requires the recommender.*.get - IAM permission for the specified recommender. - - Example: - >>> from google.cloud import recommender_v1 - >>> - >>> client = recommender_v1.RecommenderClient() - >>> - >>> name = client.recommendation_path('[PROJECT]', '[LOCATION]', '[RECOMMENDER]', '[RECOMMENDATION]') - >>> - >>> response = client.get_recommendation(name) - - Args: - name (str): Required. Name of the recommendation. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.recommender_v1.types.Recommendation` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_recommendation" not in self._inner_api_calls: - self._inner_api_calls[ - "get_recommendation" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_recommendation, - default_retry=self._method_configs["GetRecommendation"].retry, - default_timeout=self._method_configs["GetRecommendation"].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.GetRecommendationRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_recommendation"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def mark_recommendation_claimed( - self, - name, - etag, - state_metadata=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Marks the Recommendation State as Claimed. Users can use this method - to indicate to the Recommender API that they are starting to apply the - recommendation themselves. This stops the recommendation content from - being updated. Associated insights are frozen and placed in the ACCEPTED - state. - - MarkRecommendationClaimed can be applied to recommendations in CLAIMED, - SUCCEEDED, FAILED, or ACTIVE state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - - Example: - >>> from google.cloud import recommender_v1 - >>> - >>> client = recommender_v1.RecommenderClient() - >>> - >>> name = client.recommendation_path('[PROJECT]', '[LOCATION]', '[RECOMMENDER]', '[RECOMMENDATION]') - >>> - >>> # TODO: Initialize `etag`: - >>> etag = '' - >>> - >>> response = client.mark_recommendation_claimed(name, etag) - - Args: - name (str): Required. Name of the recommendation. - etag (str): Required. Fingerprint of the Recommendation. Provides optimistic locking. - state_metadata (dict[str -> str]): State properties to include with this state. Overwrites any existing - ``state_metadata``. Keys must match the regex - ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match the regex - ``/^[a-zA-Z0-9_./-]{0,255}$/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.recommender_v1.types.Recommendation` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "mark_recommendation_claimed" not in self._inner_api_calls: - self._inner_api_calls[ - "mark_recommendation_claimed" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.mark_recommendation_claimed, - default_retry=self._method_configs["MarkRecommendationClaimed"].retry, - default_timeout=self._method_configs[ - "MarkRecommendationClaimed" - ].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.MarkRecommendationClaimedRequest( - name=name, etag=etag, state_metadata=state_metadata, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["mark_recommendation_claimed"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def mark_recommendation_succeeded( - self, - name, - etag, - state_metadata=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Marks the Recommendation State as Succeeded. Users can use this - method to indicate to the Recommender API that they have applied the - recommendation themselves, and the operation was successful. This stops - the recommendation content from being updated. Associated insights are - frozen and placed in the ACCEPTED state. - - MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, - CLAIMED, SUCCEEDED, or FAILED state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - - Example: - >>> from google.cloud import recommender_v1 - >>> - >>> client = recommender_v1.RecommenderClient() - >>> - >>> name = client.recommendation_path('[PROJECT]', '[LOCATION]', '[RECOMMENDER]', '[RECOMMENDATION]') - >>> - >>> # TODO: Initialize `etag`: - >>> etag = '' - >>> - >>> response = client.mark_recommendation_succeeded(name, etag) - - Args: - name (str): Required. Name of the recommendation. - etag (str): Required. Fingerprint of the Recommendation. Provides optimistic locking. - state_metadata (dict[str -> str]): State properties to include with this state. Overwrites any existing - ``state_metadata``. Keys must match the regex - ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match the regex - ``/^[a-zA-Z0-9_./-]{0,255}$/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.recommender_v1.types.Recommendation` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "mark_recommendation_succeeded" not in self._inner_api_calls: - self._inner_api_calls[ - "mark_recommendation_succeeded" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.mark_recommendation_succeeded, - default_retry=self._method_configs["MarkRecommendationSucceeded"].retry, - default_timeout=self._method_configs[ - "MarkRecommendationSucceeded" - ].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.MarkRecommendationSucceededRequest( - name=name, etag=etag, state_metadata=state_metadata, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["mark_recommendation_succeeded"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def mark_recommendation_failed( - self, - name, - etag, - state_metadata=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Marks the Recommendation State as Failed. Users can use this method - to indicate to the Recommender API that they have applied the - recommendation themselves, and the operation failed. This stops the - recommendation content from being updated. Associated insights are - frozen and placed in the ACCEPTED state. - - MarkRecommendationFailed can be applied to recommendations in ACTIVE, - CLAIMED, SUCCEEDED, or FAILED state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - - Example: - >>> from google.cloud import recommender_v1 - >>> - >>> client = recommender_v1.RecommenderClient() - >>> - >>> name = client.recommendation_path('[PROJECT]', '[LOCATION]', '[RECOMMENDER]', '[RECOMMENDATION]') - >>> - >>> # TODO: Initialize `etag`: - >>> etag = '' - >>> - >>> response = client.mark_recommendation_failed(name, etag) - - Args: - name (str): Required. Name of the recommendation. - etag (str): Required. Fingerprint of the Recommendation. Provides optimistic locking. - state_metadata (dict[str -> str]): State properties to include with this state. Overwrites any existing - ``state_metadata``. Keys must match the regex - ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match the regex - ``/^[a-zA-Z0-9_./-]{0,255}$/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.recommender_v1.types.Recommendation` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "mark_recommendation_failed" not in self._inner_api_calls: - self._inner_api_calls[ - "mark_recommendation_failed" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.mark_recommendation_failed, - default_retry=self._method_configs["MarkRecommendationFailed"].retry, - default_timeout=self._method_configs[ - "MarkRecommendationFailed" - ].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.MarkRecommendationFailedRequest( - name=name, etag=etag, state_metadata=state_metadata, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["mark_recommendation_failed"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/recommender_v1/gapic/recommender_client_config.py b/google/cloud/recommender_v1/gapic/recommender_client_config.py deleted file mode 100644 index a5045fb..0000000 --- a/google/cloud/recommender_v1/gapic/recommender_client_config.py +++ /dev/null @@ -1,82 +0,0 @@ -config = { - "interfaces": { - "google.cloud.recommender.v1.Recommender": { - "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_codes": [], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - }, - "methods": { - "ListInsights": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetInsight": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "MarkInsightAccepted": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "ListRecommendations": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetRecommendation": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "MarkRecommendationClaimed": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "MarkRecommendationSucceeded": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "MarkRecommendationFailed": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - }, - } - } -} diff --git a/google/cloud/recommender_v1/gapic/transports/__init__.py b/google/cloud/recommender_v1/gapic/transports/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/recommender_v1/gapic/transports/recommender_grpc_transport.py b/google/cloud/recommender_v1/gapic/transports/recommender_grpc_transport.py deleted file mode 100644 index 3502d74..0000000 --- a/google/cloud/recommender_v1/gapic/transports/recommender_grpc_transport.py +++ /dev/null @@ -1,251 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 google.api_core.grpc_helpers - -from google.cloud.recommender_v1.proto import recommender_service_pb2_grpc - - -class RecommenderGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.recommender.v1 Recommender API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, channel=None, credentials=None, address="recommender.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "recommender_stub": recommender_service_pb2_grpc.RecommenderStub(channel), - } - - @classmethod - def create_channel( - cls, address="recommender.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def list_insights(self): - """Return the gRPC stub for :meth:`RecommenderClient.list_insights`. - - Lists insights for a Cloud project. Requires the recommender.*.list - IAM permission for the specified insight type. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].ListInsights - - @property - def get_insight(self): - """Return the gRPC stub for :meth:`RecommenderClient.get_insight`. - - Gets the requested insight. Requires the recommender.*.get IAM - permission for the specified insight type. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].GetInsight - - @property - def mark_insight_accepted(self): - """Return the gRPC stub for :meth:`RecommenderClient.mark_insight_accepted`. - - Marks the Insight State as Accepted. Users can use this method to - indicate to the Recommender API that they have applied some action based - on the insight. This stops the insight content from being updated. - - MarkInsightAccepted can be applied to insights in ACTIVE state. Requires - the recommender.*.update IAM permission for the specified insight. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].MarkInsightAccepted - - @property - def list_recommendations(self): - """Return the gRPC stub for :meth:`RecommenderClient.list_recommendations`. - - Lists recommendations for a Cloud project. Requires the - recommender.*.list IAM permission for the specified recommender. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].ListRecommendations - - @property - def get_recommendation(self): - """Return the gRPC stub for :meth:`RecommenderClient.get_recommendation`. - - Gets the requested recommendation. Requires the recommender.*.get - IAM permission for the specified recommender. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].GetRecommendation - - @property - def mark_recommendation_claimed(self): - """Return the gRPC stub for :meth:`RecommenderClient.mark_recommendation_claimed`. - - Marks the Recommendation State as Claimed. Users can use this method - to indicate to the Recommender API that they are starting to apply the - recommendation themselves. This stops the recommendation content from - being updated. Associated insights are frozen and placed in the ACCEPTED - state. - - MarkRecommendationClaimed can be applied to recommendations in CLAIMED, - SUCCEEDED, FAILED, or ACTIVE state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].MarkRecommendationClaimed - - @property - def mark_recommendation_succeeded(self): - """Return the gRPC stub for :meth:`RecommenderClient.mark_recommendation_succeeded`. - - Marks the Recommendation State as Succeeded. Users can use this - method to indicate to the Recommender API that they have applied the - recommendation themselves, and the operation was successful. This stops - the recommendation content from being updated. Associated insights are - frozen and placed in the ACCEPTED state. - - MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, - CLAIMED, SUCCEEDED, or FAILED state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].MarkRecommendationSucceeded - - @property - def mark_recommendation_failed(self): - """Return the gRPC stub for :meth:`RecommenderClient.mark_recommendation_failed`. - - Marks the Recommendation State as Failed. Users can use this method - to indicate to the Recommender API that they have applied the - recommendation themselves, and the operation failed. This stops the - recommendation content from being updated. Associated insights are - frozen and placed in the ACCEPTED state. - - MarkRecommendationFailed can be applied to recommendations in ACTIVE, - CLAIMED, SUCCEEDED, or FAILED state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].MarkRecommendationFailed diff --git a/google/cloud/recommender_v1/proto/__init__.py b/google/cloud/recommender_v1/proto/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/recommender_v1/proto/insight_pb2.py b/google/cloud/recommender_v1/proto/insight_pb2.py deleted file mode 100644 index 53b4905..0000000 --- a/google/cloud/recommender_v1/proto/insight_pb2.py +++ /dev/null @@ -1,666 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/recommender_v1/proto/insight.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/recommender_v1/proto/insight.proto", - package="google.cloud.recommender.v1", - syntax="proto3", - serialized_options=b"\n\037com.google.cloud.recommender.v1B\014InsightProtoP\001ZFgoogle.golang.org/genproto/googleapis/cloud/recommender/v1;recommender\242\002\004CREC\252\002\033Google.Cloud.Recommender.V1\352Am\n&recommender.googleapis.com/InsightType\022Cprojects/{project}/locations/{location}/insightTypes/{insight_type}", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n/google/cloud/recommender_v1/proto/insight.proto\x12\x1bgoogle.cloud.recommender.v1\x1a\x19google/api/resource.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\x81\x06\n\x07Insight\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12\x18\n\x10target_resources\x18\t \x03(\t\x12\x17\n\x0finsight_subtype\x18\n \x01(\t\x12(\n\x07\x63ontent\x18\x03 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\x35\n\x11last_refresh_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x35\n\x12observation_period\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x41\n\nstate_info\x18\x06 \x01(\x0b\x32-.google.cloud.recommender.v1.InsightStateInfo\x12?\n\x08\x63\x61tegory\x18\x07 \x01(\x0e\x32-.google.cloud.recommender.v1.Insight.Category\x12\x0c\n\x04\x65tag\x18\x0b \x01(\t\x12`\n\x1a\x61ssociated_recommendations\x18\x08 \x03(\x0b\x32<.google.cloud.recommender.v1.Insight.RecommendationReference\x1a\x31\n\x17RecommendationReference\x12\x16\n\x0erecommendation\x18\x01 \x01(\t"`\n\x08\x43\x61tegory\x12\x18\n\x14\x43\x41TEGORY_UNSPECIFIED\x10\x00\x12\x08\n\x04\x43OST\x10\x01\x12\x0c\n\x08SECURITY\x10\x02\x12\x0f\n\x0bPERFORMANCE\x10\x03\x12\x11\n\rMANAGEABILITY\x10\x04:\x7f\xea\x41|\n"recommender.googleapis.com/Insight\x12Vprojects/{project}/locations/{location}/insightTypes/{insight_type}/insights/{insight}"\xaf\x02\n\x10InsightStateInfo\x12\x42\n\x05state\x18\x01 \x01(\x0e\x32\x33.google.cloud.recommender.v1.InsightStateInfo.State\x12X\n\x0estate_metadata\x18\x02 \x03(\x0b\x32@.google.cloud.recommender.v1.InsightStateInfo.StateMetadataEntry\x1a\x34\n\x12StateMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"G\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\n\n\x06\x41\x43TIVE\x10\x01\x12\x0c\n\x08\x41\x43\x43\x45PTED\x10\x02\x12\r\n\tDISMISSED\x10\x03\x42\x8e\x02\n\x1f\x63om.google.cloud.recommender.v1B\x0cInsightProtoP\x01ZFgoogle.golang.org/genproto/googleapis/cloud/recommender/v1;recommender\xa2\x02\x04\x43REC\xaa\x02\x1bGoogle.Cloud.Recommender.V1\xea\x41m\n&recommender.googleapis.com/InsightType\x12\x43projects/{project}/locations/{location}/insightTypes/{insight_type}b\x06proto3', - dependencies=[ - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_protobuf_dot_duration__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_INSIGHT_CATEGORY = _descriptor.EnumDescriptor( - name="Category", - full_name="google.cloud.recommender.v1.Insight.Category", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="CATEGORY_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="COST", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SECURITY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PERFORMANCE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MANAGEABILITY", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=747, - serialized_end=843, -) -_sym_db.RegisterEnumDescriptor(_INSIGHT_CATEGORY) - -_INSIGHTSTATEINFO_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.recommender.v1.InsightStateInfo.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ACTIVE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ACCEPTED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DISMISSED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1207, - serialized_end=1278, -) -_sym_db.RegisterEnumDescriptor(_INSIGHTSTATEINFO_STATE) - - -_INSIGHT_RECOMMENDATIONREFERENCE = _descriptor.Descriptor( - name="RecommendationReference", - full_name="google.cloud.recommender.v1.Insight.RecommendationReference", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="recommendation", - full_name="google.cloud.recommender.v1.Insight.RecommendationReference.recommendation", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=696, - serialized_end=745, -) - -_INSIGHT = _descriptor.Descriptor( - name="Insight", - full_name="google.cloud.recommender.v1.Insight", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1.Insight.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.recommender.v1.Insight.description", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="target_resources", - full_name="google.cloud.recommender.v1.Insight.target_resources", - index=2, - number=9, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="insight_subtype", - full_name="google.cloud.recommender.v1.Insight.insight_subtype", - index=3, - number=10, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content", - full_name="google.cloud.recommender.v1.Insight.content", - index=4, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="last_refresh_time", - full_name="google.cloud.recommender.v1.Insight.last_refresh_time", - index=5, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="observation_period", - full_name="google.cloud.recommender.v1.Insight.observation_period", - index=6, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_info", - full_name="google.cloud.recommender.v1.Insight.state_info", - index=7, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="category", - full_name="google.cloud.recommender.v1.Insight.category", - index=8, - number=7, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="etag", - full_name="google.cloud.recommender.v1.Insight.etag", - index=9, - number=11, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="associated_recommendations", - full_name="google.cloud.recommender.v1.Insight.associated_recommendations", - index=10, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_INSIGHT_RECOMMENDATIONREFERENCE,], - enum_types=[_INSIGHT_CATEGORY,], - serialized_options=b'\352A|\n"recommender.googleapis.com/Insight\022Vprojects/{project}/locations/{location}/insightTypes/{insight_type}/insights/{insight}', - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=203, - serialized_end=972, -) - - -_INSIGHTSTATEINFO_STATEMETADATAENTRY = _descriptor.Descriptor( - name="StateMetadataEntry", - full_name="google.cloud.recommender.v1.InsightStateInfo.StateMetadataEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1.InsightStateInfo.StateMetadataEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1.InsightStateInfo.StateMetadataEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1153, - serialized_end=1205, -) - -_INSIGHTSTATEINFO = _descriptor.Descriptor( - name="InsightStateInfo", - full_name="google.cloud.recommender.v1.InsightStateInfo", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.recommender.v1.InsightStateInfo.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_metadata", - full_name="google.cloud.recommender.v1.InsightStateInfo.state_metadata", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_INSIGHTSTATEINFO_STATEMETADATAENTRY,], - enum_types=[_INSIGHTSTATEINFO_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=975, - serialized_end=1278, -) - -_INSIGHT_RECOMMENDATIONREFERENCE.containing_type = _INSIGHT -_INSIGHT.fields_by_name[ - "content" -].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_INSIGHT.fields_by_name[ - "last_refresh_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_INSIGHT.fields_by_name[ - "observation_period" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_INSIGHT.fields_by_name["state_info"].message_type = _INSIGHTSTATEINFO -_INSIGHT.fields_by_name["category"].enum_type = _INSIGHT_CATEGORY -_INSIGHT.fields_by_name[ - "associated_recommendations" -].message_type = _INSIGHT_RECOMMENDATIONREFERENCE -_INSIGHT_CATEGORY.containing_type = _INSIGHT -_INSIGHTSTATEINFO_STATEMETADATAENTRY.containing_type = _INSIGHTSTATEINFO -_INSIGHTSTATEINFO.fields_by_name["state"].enum_type = _INSIGHTSTATEINFO_STATE -_INSIGHTSTATEINFO.fields_by_name[ - "state_metadata" -].message_type = _INSIGHTSTATEINFO_STATEMETADATAENTRY -_INSIGHTSTATEINFO_STATE.containing_type = _INSIGHTSTATEINFO -DESCRIPTOR.message_types_by_name["Insight"] = _INSIGHT -DESCRIPTOR.message_types_by_name["InsightStateInfo"] = _INSIGHTSTATEINFO -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Insight = _reflection.GeneratedProtocolMessageType( - "Insight", - (_message.Message,), - { - "RecommendationReference": _reflection.GeneratedProtocolMessageType( - "RecommendationReference", - (_message.Message,), - { - "DESCRIPTOR": _INSIGHT_RECOMMENDATIONREFERENCE, - "__module__": "google.cloud.recommender_v1.proto.insight_pb2", - "__doc__": """Reference to an associated recommendation. - - Attributes: - recommendation: - Recommendation resource name, e.g. projects/[PROJECT_NUMBER]/l - ocations/[LOCATION]/recommenders/[RECOMMENDER_ID]/recommendati - ons/[RECOMMENDATION_ID] - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.Insight.RecommendationReference) - }, - ), - "DESCRIPTOR": _INSIGHT, - "__module__": "google.cloud.recommender_v1.proto.insight_pb2", - "__doc__": """An insight along with the information used to derive the insight. The - insight may have associated recomendations as well. - - Attributes: - name: - Name of the insight. - description: - Free-form human readable summary in English. The maximum - length is 500 characters. - target_resources: - Fully qualified resource names that this insight is targeting. - insight_subtype: - Insight subtype. Insight content schema will be stable for a - given subtype. - content: - A struct of custom fields to explain the insight. Example: - “grantedPermissionsCount”: “1000” - last_refresh_time: - Timestamp of the latest data used to generate the insight. - observation_period: - Observation period that led to the insight. The source data - used to generate the insight ends at last_refresh_time and - begins at (last_refresh_time - observation_period). - state_info: - Information state and metadata. - category: - Category being targeted by the insight. - etag: - Fingerprint of the Insight. Provides optimistic locking when - updating states. - associated_recommendations: - Recommendations derived from this insight. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.Insight) - }, -) -_sym_db.RegisterMessage(Insight) -_sym_db.RegisterMessage(Insight.RecommendationReference) - -InsightStateInfo = _reflection.GeneratedProtocolMessageType( - "InsightStateInfo", - (_message.Message,), - { - "StateMetadataEntry": _reflection.GeneratedProtocolMessageType( - "StateMetadataEntry", - (_message.Message,), - { - "DESCRIPTOR": _INSIGHTSTATEINFO_STATEMETADATAENTRY, - "__module__": "google.cloud.recommender_v1.proto.insight_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.InsightStateInfo.StateMetadataEntry) - }, - ), - "DESCRIPTOR": _INSIGHTSTATEINFO, - "__module__": "google.cloud.recommender_v1.proto.insight_pb2", - "__doc__": """Information related to insight state. - - Attributes: - state: - Insight state. - state_metadata: - A map of metadata for the state, provided by user or - automations systems. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.InsightStateInfo) - }, -) -_sym_db.RegisterMessage(InsightStateInfo) -_sym_db.RegisterMessage(InsightStateInfo.StateMetadataEntry) - - -DESCRIPTOR._options = None -_INSIGHT._options = None -_INSIGHTSTATEINFO_STATEMETADATAENTRY._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/recommender_v1/proto/insight_pb2_grpc.py b/google/cloud/recommender_v1/proto/insight_pb2_grpc.py deleted file mode 100644 index 8a93939..0000000 --- a/google/cloud/recommender_v1/proto/insight_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/recommender_v1/proto/recommendation_pb2.py b/google/cloud/recommender_v1/proto/recommendation_pb2.py deleted file mode 100644 index 9472a3b..0000000 --- a/google/cloud/recommender_v1/proto/recommendation_pb2.py +++ /dev/null @@ -1,1525 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/recommender_v1/proto/recommendation.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.type import money_pb2 as google_dot_type_dot_money__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/recommender_v1/proto/recommendation.proto", - package="google.cloud.recommender.v1", - syntax="proto3", - serialized_options=b"\n\037com.google.cloud.recommender.v1P\001ZFgoogle.golang.org/genproto/googleapis/cloud/recommender/v1;recommender\242\002\004CREC\252\002\033Google.Cloud.Recommender.V1\352Al\n&recommender.googleapis.com/Recommender\022Bprojects/{project}/locations/{location}/recommenders/{recommender}", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n6google/cloud/recommender_v1/proto/recommendation.proto\x12\x1bgoogle.cloud.recommender.v1\x1a\x19google/api/resource.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/type/money.proto"\xb8\x05\n\x0eRecommendation\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12\x1b\n\x13recommender_subtype\x18\x0c \x01(\t\x12\x35\n\x11last_refresh_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12;\n\x0eprimary_impact\x18\x05 \x01(\x0b\x32#.google.cloud.recommender.v1.Impact\x12>\n\x11\x61\x64\x64itional_impact\x18\x06 \x03(\x0b\x32#.google.cloud.recommender.v1.Impact\x12\x43\n\x07\x63ontent\x18\x07 \x01(\x0b\x32\x32.google.cloud.recommender.v1.RecommendationContent\x12H\n\nstate_info\x18\n \x01(\x0b\x32\x34.google.cloud.recommender.v1.RecommendationStateInfo\x12\x0c\n\x04\x65tag\x18\x0b \x01(\t\x12Y\n\x13\x61ssociated_insights\x18\x0e \x03(\x0b\x32<.google.cloud.recommender.v1.Recommendation.InsightReference\x1a#\n\x10InsightReference\x12\x0f\n\x07insight\x18\x01 \x01(\t:\x94\x01\xea\x41\x90\x01\n)recommender.googleapis.com/Recommendation\x12\x63projects/{project}/locations/{location}/recommenders/{recommender}/recommendations/{recommendation}"^\n\x15RecommendationContent\x12\x45\n\x10operation_groups\x18\x02 \x03(\x0b\x32+.google.cloud.recommender.v1.OperationGroup"L\n\x0eOperationGroup\x12:\n\noperations\x18\x01 \x03(\x0b\x32&.google.cloud.recommender.v1.Operation"\xd7\x04\n\tOperation\x12\x0e\n\x06\x61\x63tion\x18\x01 \x01(\t\x12\x15\n\rresource_type\x18\x02 \x01(\t\x12\x10\n\x08resource\x18\x03 \x01(\t\x12\x0c\n\x04path\x18\x04 \x01(\t\x12\x17\n\x0fsource_resource\x18\x05 \x01(\t\x12\x13\n\x0bsource_path\x18\x06 \x01(\t\x12\'\n\x05value\x18\x07 \x01(\x0b\x32\x16.google.protobuf.ValueH\x00\x12\x42\n\rvalue_matcher\x18\n \x01(\x0b\x32).google.cloud.recommender.v1.ValueMatcherH\x00\x12M\n\x0cpath_filters\x18\x08 \x03(\x0b\x32\x37.google.cloud.recommender.v1.Operation.PathFiltersEntry\x12Z\n\x13path_value_matchers\x18\x0b \x03(\x0b\x32=.google.cloud.recommender.v1.Operation.PathValueMatchersEntry\x1aJ\n\x10PathFiltersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01\x1a\x63\n\x16PathValueMatchersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x38\n\x05value\x18\x02 \x01(\x0b\x32).google.cloud.recommender.v1.ValueMatcher:\x02\x38\x01\x42\x0c\n\npath_value":\n\x0cValueMatcher\x12\x19\n\x0fmatches_pattern\x18\x01 \x01(\tH\x00\x42\x0f\n\rmatch_variant"_\n\x0e\x43ostProjection\x12 \n\x04\x63ost\x18\x01 \x01(\x0b\x32\x12.google.type.Money\x12+\n\x08\x64uration\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"\x80\x02\n\x06Impact\x12>\n\x08\x63\x61tegory\x18\x01 \x01(\x0e\x32,.google.cloud.recommender.v1.Impact.Category\x12\x46\n\x0f\x63ost_projection\x18\x64 \x01(\x0b\x32+.google.cloud.recommender.v1.CostProjectionH\x00"`\n\x08\x43\x61tegory\x12\x18\n\x14\x43\x41TEGORY_UNSPECIFIED\x10\x00\x12\x08\n\x04\x43OST\x10\x01\x12\x0c\n\x08SECURITY\x10\x02\x12\x0f\n\x0bPERFORMANCE\x10\x03\x12\x11\n\rMANAGEABILITY\x10\x04\x42\x0c\n\nprojection"\xde\x02\n\x17RecommendationStateInfo\x12I\n\x05state\x18\x01 \x01(\x0e\x32:.google.cloud.recommender.v1.RecommendationStateInfo.State\x12_\n\x0estate_metadata\x18\x02 \x03(\x0b\x32G.google.cloud.recommender.v1.RecommendationStateInfo.StateMetadataEntry\x1a\x34\n\x12StateMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"a\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\n\n\x06\x41\x43TIVE\x10\x01\x12\x0b\n\x07\x43LAIMED\x10\x06\x12\r\n\tSUCCEEDED\x10\x03\x12\n\n\x06\x46\x41ILED\x10\x04\x12\r\n\tDISMISSED\x10\x05\x42\xff\x01\n\x1f\x63om.google.cloud.recommender.v1P\x01ZFgoogle.golang.org/genproto/googleapis/cloud/recommender/v1;recommender\xa2\x02\x04\x43REC\xaa\x02\x1bGoogle.Cloud.Recommender.V1\xea\x41l\n&recommender.googleapis.com/Recommender\x12\x42projects/{project}/locations/{location}/recommenders/{recommender}b\x06proto3', - dependencies=[ - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_protobuf_dot_duration__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_type_dot_money__pb2.DESCRIPTOR, - ], -) - - -_IMPACT_CATEGORY = _descriptor.EnumDescriptor( - name="Category", - full_name="google.cloud.recommender.v1.Impact.Category", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="CATEGORY_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="COST", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SECURITY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PERFORMANCE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MANAGEABILITY", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=2013, - serialized_end=2109, -) -_sym_db.RegisterEnumDescriptor(_IMPACT_CATEGORY) - -_RECOMMENDATIONSTATEINFO_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.recommender.v1.RecommendationStateInfo.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ACTIVE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CLAIMED", - index=2, - number=6, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SUCCEEDED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FAILED", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DISMISSED", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=2379, - serialized_end=2476, -) -_sym_db.RegisterEnumDescriptor(_RECOMMENDATIONSTATEINFO_STATE) - - -_RECOMMENDATION_INSIGHTREFERENCE = _descriptor.Descriptor( - name="InsightReference", - full_name="google.cloud.recommender.v1.Recommendation.InsightReference", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="insight", - full_name="google.cloud.recommender.v1.Recommendation.InsightReference.insight", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=745, - serialized_end=780, -) - -_RECOMMENDATION = _descriptor.Descriptor( - name="Recommendation", - full_name="google.cloud.recommender.v1.Recommendation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1.Recommendation.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.recommender.v1.Recommendation.description", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="recommender_subtype", - full_name="google.cloud.recommender.v1.Recommendation.recommender_subtype", - index=2, - number=12, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="last_refresh_time", - full_name="google.cloud.recommender.v1.Recommendation.last_refresh_time", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="primary_impact", - full_name="google.cloud.recommender.v1.Recommendation.primary_impact", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="additional_impact", - full_name="google.cloud.recommender.v1.Recommendation.additional_impact", - index=5, - number=6, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content", - full_name="google.cloud.recommender.v1.Recommendation.content", - index=6, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_info", - full_name="google.cloud.recommender.v1.Recommendation.state_info", - index=7, - number=10, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="etag", - full_name="google.cloud.recommender.v1.Recommendation.etag", - index=8, - number=11, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="associated_insights", - full_name="google.cloud.recommender.v1.Recommendation.associated_insights", - index=9, - number=14, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_RECOMMENDATION_INSIGHTREFERENCE,], - enum_types=[], - serialized_options=b"\352A\220\001\n)recommender.googleapis.com/Recommendation\022cprojects/{project}/locations/{location}/recommenders/{recommender}/recommendations/{recommendation}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=235, - serialized_end=931, -) - - -_RECOMMENDATIONCONTENT = _descriptor.Descriptor( - name="RecommendationContent", - full_name="google.cloud.recommender.v1.RecommendationContent", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="operation_groups", - full_name="google.cloud.recommender.v1.RecommendationContent.operation_groups", - index=0, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=933, - serialized_end=1027, -) - - -_OPERATIONGROUP = _descriptor.Descriptor( - name="OperationGroup", - full_name="google.cloud.recommender.v1.OperationGroup", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="operations", - full_name="google.cloud.recommender.v1.OperationGroup.operations", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1029, - serialized_end=1105, -) - - -_OPERATION_PATHFILTERSENTRY = _descriptor.Descriptor( - name="PathFiltersEntry", - full_name="google.cloud.recommender.v1.Operation.PathFiltersEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1.Operation.PathFiltersEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1.Operation.PathFiltersEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1518, - serialized_end=1592, -) - -_OPERATION_PATHVALUEMATCHERSENTRY = _descriptor.Descriptor( - name="PathValueMatchersEntry", - full_name="google.cloud.recommender.v1.Operation.PathValueMatchersEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1.Operation.PathValueMatchersEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1.Operation.PathValueMatchersEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1594, - serialized_end=1693, -) - -_OPERATION = _descriptor.Descriptor( - name="Operation", - full_name="google.cloud.recommender.v1.Operation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="action", - full_name="google.cloud.recommender.v1.Operation.action", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_type", - full_name="google.cloud.recommender.v1.Operation.resource_type", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource", - full_name="google.cloud.recommender.v1.Operation.resource", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="path", - full_name="google.cloud.recommender.v1.Operation.path", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source_resource", - full_name="google.cloud.recommender.v1.Operation.source_resource", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source_path", - full_name="google.cloud.recommender.v1.Operation.source_path", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1.Operation.value", - index=6, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value_matcher", - full_name="google.cloud.recommender.v1.Operation.value_matcher", - index=7, - number=10, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="path_filters", - full_name="google.cloud.recommender.v1.Operation.path_filters", - index=8, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="path_value_matchers", - full_name="google.cloud.recommender.v1.Operation.path_value_matchers", - index=9, - number=11, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_OPERATION_PATHFILTERSENTRY, _OPERATION_PATHVALUEMATCHERSENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="path_value", - full_name="google.cloud.recommender.v1.Operation.path_value", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1108, - serialized_end=1707, -) - - -_VALUEMATCHER = _descriptor.Descriptor( - name="ValueMatcher", - full_name="google.cloud.recommender.v1.ValueMatcher", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="matches_pattern", - full_name="google.cloud.recommender.v1.ValueMatcher.matches_pattern", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="match_variant", - full_name="google.cloud.recommender.v1.ValueMatcher.match_variant", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1709, - serialized_end=1767, -) - - -_COSTPROJECTION = _descriptor.Descriptor( - name="CostProjection", - full_name="google.cloud.recommender.v1.CostProjection", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="cost", - full_name="google.cloud.recommender.v1.CostProjection.cost", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="duration", - full_name="google.cloud.recommender.v1.CostProjection.duration", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1769, - serialized_end=1864, -) - - -_IMPACT = _descriptor.Descriptor( - name="Impact", - full_name="google.cloud.recommender.v1.Impact", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="category", - full_name="google.cloud.recommender.v1.Impact.category", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="cost_projection", - full_name="google.cloud.recommender.v1.Impact.cost_projection", - index=1, - number=100, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_IMPACT_CATEGORY,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="projection", - full_name="google.cloud.recommender.v1.Impact.projection", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1867, - serialized_end=2123, -) - - -_RECOMMENDATIONSTATEINFO_STATEMETADATAENTRY = _descriptor.Descriptor( - name="StateMetadataEntry", - full_name="google.cloud.recommender.v1.RecommendationStateInfo.StateMetadataEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1.RecommendationStateInfo.StateMetadataEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1.RecommendationStateInfo.StateMetadataEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2325, - serialized_end=2377, -) - -_RECOMMENDATIONSTATEINFO = _descriptor.Descriptor( - name="RecommendationStateInfo", - full_name="google.cloud.recommender.v1.RecommendationStateInfo", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.recommender.v1.RecommendationStateInfo.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_metadata", - full_name="google.cloud.recommender.v1.RecommendationStateInfo.state_metadata", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_RECOMMENDATIONSTATEINFO_STATEMETADATAENTRY,], - enum_types=[_RECOMMENDATIONSTATEINFO_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2126, - serialized_end=2476, -) - -_RECOMMENDATION_INSIGHTREFERENCE.containing_type = _RECOMMENDATION -_RECOMMENDATION.fields_by_name[ - "last_refresh_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_RECOMMENDATION.fields_by_name["primary_impact"].message_type = _IMPACT -_RECOMMENDATION.fields_by_name["additional_impact"].message_type = _IMPACT -_RECOMMENDATION.fields_by_name["content"].message_type = _RECOMMENDATIONCONTENT -_RECOMMENDATION.fields_by_name["state_info"].message_type = _RECOMMENDATIONSTATEINFO -_RECOMMENDATION.fields_by_name[ - "associated_insights" -].message_type = _RECOMMENDATION_INSIGHTREFERENCE -_RECOMMENDATIONCONTENT.fields_by_name["operation_groups"].message_type = _OPERATIONGROUP -_OPERATIONGROUP.fields_by_name["operations"].message_type = _OPERATION -_OPERATION_PATHFILTERSENTRY.fields_by_name[ - "value" -].message_type = google_dot_protobuf_dot_struct__pb2._VALUE -_OPERATION_PATHFILTERSENTRY.containing_type = _OPERATION -_OPERATION_PATHVALUEMATCHERSENTRY.fields_by_name["value"].message_type = _VALUEMATCHER -_OPERATION_PATHVALUEMATCHERSENTRY.containing_type = _OPERATION -_OPERATION.fields_by_name[ - "value" -].message_type = google_dot_protobuf_dot_struct__pb2._VALUE -_OPERATION.fields_by_name["value_matcher"].message_type = _VALUEMATCHER -_OPERATION.fields_by_name["path_filters"].message_type = _OPERATION_PATHFILTERSENTRY -_OPERATION.fields_by_name[ - "path_value_matchers" -].message_type = _OPERATION_PATHVALUEMATCHERSENTRY -_OPERATION.oneofs_by_name["path_value"].fields.append( - _OPERATION.fields_by_name["value"] -) -_OPERATION.fields_by_name["value"].containing_oneof = _OPERATION.oneofs_by_name[ - "path_value" -] -_OPERATION.oneofs_by_name["path_value"].fields.append( - _OPERATION.fields_by_name["value_matcher"] -) -_OPERATION.fields_by_name["value_matcher"].containing_oneof = _OPERATION.oneofs_by_name[ - "path_value" -] -_VALUEMATCHER.oneofs_by_name["match_variant"].fields.append( - _VALUEMATCHER.fields_by_name["matches_pattern"] -) -_VALUEMATCHER.fields_by_name[ - "matches_pattern" -].containing_oneof = _VALUEMATCHER.oneofs_by_name["match_variant"] -_COSTPROJECTION.fields_by_name[ - "cost" -].message_type = google_dot_type_dot_money__pb2._MONEY -_COSTPROJECTION.fields_by_name[ - "duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_IMPACT.fields_by_name["category"].enum_type = _IMPACT_CATEGORY -_IMPACT.fields_by_name["cost_projection"].message_type = _COSTPROJECTION -_IMPACT_CATEGORY.containing_type = _IMPACT -_IMPACT.oneofs_by_name["projection"].fields.append( - _IMPACT.fields_by_name["cost_projection"] -) -_IMPACT.fields_by_name["cost_projection"].containing_oneof = _IMPACT.oneofs_by_name[ - "projection" -] -_RECOMMENDATIONSTATEINFO_STATEMETADATAENTRY.containing_type = _RECOMMENDATIONSTATEINFO -_RECOMMENDATIONSTATEINFO.fields_by_name[ - "state" -].enum_type = _RECOMMENDATIONSTATEINFO_STATE -_RECOMMENDATIONSTATEINFO.fields_by_name[ - "state_metadata" -].message_type = _RECOMMENDATIONSTATEINFO_STATEMETADATAENTRY -_RECOMMENDATIONSTATEINFO_STATE.containing_type = _RECOMMENDATIONSTATEINFO -DESCRIPTOR.message_types_by_name["Recommendation"] = _RECOMMENDATION -DESCRIPTOR.message_types_by_name["RecommendationContent"] = _RECOMMENDATIONCONTENT -DESCRIPTOR.message_types_by_name["OperationGroup"] = _OPERATIONGROUP -DESCRIPTOR.message_types_by_name["Operation"] = _OPERATION -DESCRIPTOR.message_types_by_name["ValueMatcher"] = _VALUEMATCHER -DESCRIPTOR.message_types_by_name["CostProjection"] = _COSTPROJECTION -DESCRIPTOR.message_types_by_name["Impact"] = _IMPACT -DESCRIPTOR.message_types_by_name["RecommendationStateInfo"] = _RECOMMENDATIONSTATEINFO -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Recommendation = _reflection.GeneratedProtocolMessageType( - "Recommendation", - (_message.Message,), - { - "InsightReference": _reflection.GeneratedProtocolMessageType( - "InsightReference", - (_message.Message,), - { - "DESCRIPTOR": _RECOMMENDATION_INSIGHTREFERENCE, - "__module__": "google.cloud.recommender_v1.proto.recommendation_pb2", - "__doc__": """Reference to an associated insight. - - Attributes: - insight: - Insight resource name, e.g. ``projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]/insights/[INSIGHT_ID]`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.Recommendation.InsightReference) - }, - ), - "DESCRIPTOR": _RECOMMENDATION, - "__module__": "google.cloud.recommender_v1.proto.recommendation_pb2", - "__doc__": """A recommendation along with a suggested action. E.g., a rightsizing - recommendation for an underutilized VM, IAM role recommendations, etc - - Attributes: - name: - Name of recommendation. - description: - Free-form human readable summary in English. The maximum - length is 500 characters. - recommender_subtype: - Contains an identifier for a subtype of recommendations - produced for the same recommender. Subtype is a function of - content and impact, meaning a new subtype might be added when - significant changes to ``content`` or - ``primary_impact.category`` are introduced. See the - Recommenders section to see a list of subtypes for a given - Recommender. Examples: For recommender = - “google.iam.policy.Recommender”, recommender_subtype can be - one of “REMOVE_ROLE”/“REPLACE_ROLE” - last_refresh_time: - Last time this recommendation was refreshed by the system that - created it in the first place. - primary_impact: - The primary impact that this recommendation can have while - trying to optimize for one category. - additional_impact: - Optional set of additional impact that this recommendation may - have when trying to optimize for the primary category. These - may be positive or negative. - content: - Content of the recommendation describing recommended changes - to resources. - state_info: - Information for state. Contains state and metadata. - etag: - Fingerprint of the Recommendation. Provides optimistic locking - when updating states. - associated_insights: - Insights that led to this recommendation. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.Recommendation) - }, -) -_sym_db.RegisterMessage(Recommendation) -_sym_db.RegisterMessage(Recommendation.InsightReference) - -RecommendationContent = _reflection.GeneratedProtocolMessageType( - "RecommendationContent", - (_message.Message,), - { - "DESCRIPTOR": _RECOMMENDATIONCONTENT, - "__module__": "google.cloud.recommender_v1.proto.recommendation_pb2", - "__doc__": """Contains what resources are changing and how they are changing. - - Attributes: - operation_groups: - Operations to one or more Google Cloud resources grouped in - such a way that, all operations within one group are expected - to be performed atomically and in an order. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.RecommendationContent) - }, -) -_sym_db.RegisterMessage(RecommendationContent) - -OperationGroup = _reflection.GeneratedProtocolMessageType( - "OperationGroup", - (_message.Message,), - { - "DESCRIPTOR": _OPERATIONGROUP, - "__module__": "google.cloud.recommender_v1.proto.recommendation_pb2", - "__doc__": """Group of operations that need to be performed atomically. - - Attributes: - operations: - List of operations across one or more resources that belong to - this group. Loosely based on RFC6902 and should be performed - in the order they appear. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.OperationGroup) - }, -) -_sym_db.RegisterMessage(OperationGroup) - -Operation = _reflection.GeneratedProtocolMessageType( - "Operation", - (_message.Message,), - { - "PathFiltersEntry": _reflection.GeneratedProtocolMessageType( - "PathFiltersEntry", - (_message.Message,), - { - "DESCRIPTOR": _OPERATION_PATHFILTERSENTRY, - "__module__": "google.cloud.recommender_v1.proto.recommendation_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.Operation.PathFiltersEntry) - }, - ), - "PathValueMatchersEntry": _reflection.GeneratedProtocolMessageType( - "PathValueMatchersEntry", - (_message.Message,), - { - "DESCRIPTOR": _OPERATION_PATHVALUEMATCHERSENTRY, - "__module__": "google.cloud.recommender_v1.proto.recommendation_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.Operation.PathValueMatchersEntry) - }, - ), - "DESCRIPTOR": _OPERATION, - "__module__": "google.cloud.recommender_v1.proto.recommendation_pb2", - "__doc__": """Contains an operation for a resource loosely based on the JSON-PATCH - format with support for: - Custom filters for describing partial - array patch. - Extended path values for describing nested arrays. - - Custom fields for describing the resource for which the operation is - being described. - Allows extension to custom operations not natively - supported by RFC6902. See https://tools.ietf.org/html/rfc6902 for - details on the original RFC. - - Attributes: - action: - Type of this operation. Contains one of ‘and’, ‘remove’, - ‘replace’, ‘move’, ‘copy’, ‘test’ and custom operations. This - field is case-insensitive and always populated. - resource_type: - Type of GCP resource being modified/tested. This field is - always populated. Example: - cloudresourcemanager.googleapis.com/Project, - compute.googleapis.com/Instance - resource: - Contains the fully qualified resource name. This field is - always populated. ex: - //cloudresourcemanager.googleapis.com/projects/foo. - path: - Path to the target field being operated on. If the operation - is at the resource level, then path should be “/”. This field - is always populated. - source_resource: - Can be set with action ‘copy’ to copy resource configuration - across different resources of the same type. Example: A - resource clone can be done via action = ‘copy’, path = “/”, - from = “/”, source_resource = and resource_name = . This field - is empty for all other values of ``action``. - source_path: - Can be set with action ‘copy’ or ‘move’ to indicate the source - field within resource or source_resource, ignored if provided - for other operation types. - path_value: - One of the fields in the following block will be set and - intend to describe a value for ‘path’ field. - value: - Value for the ``path`` field. Will be set for - actions:‘add’/‘replace’. Maybe set for action: ‘test’. Either - this or ``value_matcher`` will be set for ‘test’ operation. An - exact match must be performed. - value_matcher: - Can be set for action ‘test’ for advanced matching for the - value of ‘path’ field. Either this or ``value`` will be set - for ‘test’ operation. - path_filters: - Set of filters to apply if ``path`` refers to array elements - or nested array elements in order to narrow down to a single - unique element that is being tested/modified. This is intended - to be an exact match per filter. To perform advanced matching, - use path_value_matchers. - Example: ``{ “/versions/*/name" : - "it-123" "/versions/*/targetSize/percent”: 20 }`` - Example: - { “/bindings/*/role": "roles/admin" "/bindings/*/condition” - : null } - Example: ``{ "/bindings/*/role“:”roles/admin" - “/bindings/*/members/*” : [“x@google.com”, “y@google.com”] - }`` When both path_filters and path_value_matchers are set, - an implicit AND must be performed. - path_value_matchers: - Similar to path_filters, this contains set of filters to apply - if ``path`` field referes to array elements. This is meant to - support value matching beyond exact match. To perform exact - match, use path_filters. When both path_filters and - path_value_matchers are set, an implicit AND must be - performed. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.Operation) - }, -) -_sym_db.RegisterMessage(Operation) -_sym_db.RegisterMessage(Operation.PathFiltersEntry) -_sym_db.RegisterMessage(Operation.PathValueMatchersEntry) - -ValueMatcher = _reflection.GeneratedProtocolMessageType( - "ValueMatcher", - (_message.Message,), - { - "DESCRIPTOR": _VALUEMATCHER, - "__module__": "google.cloud.recommender_v1.proto.recommendation_pb2", - "__doc__": """Contains various matching options for values for a GCP resource field. - - Attributes: - matches_pattern: - To be used for full regex matching. The regular expression is - using the Google RE2 syntax - (https://github.com/google/re2/wiki/Syntax), so to be used - with RE2::FullMatch - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.ValueMatcher) - }, -) -_sym_db.RegisterMessage(ValueMatcher) - -CostProjection = _reflection.GeneratedProtocolMessageType( - "CostProjection", - (_message.Message,), - { - "DESCRIPTOR": _COSTPROJECTION, - "__module__": "google.cloud.recommender_v1.proto.recommendation_pb2", - "__doc__": """Contains metadata about how much money a recommendation can save or - incur. - - Attributes: - cost: - An approximate projection on amount saved or amount incurred. - Negative cost units indicate cost savings and positive cost - units indicate increase. See google.type.Money documentation - for positive/negative units. - duration: - Duration for which this cost applies. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.CostProjection) - }, -) -_sym_db.RegisterMessage(CostProjection) - -Impact = _reflection.GeneratedProtocolMessageType( - "Impact", - (_message.Message,), - { - "DESCRIPTOR": _IMPACT, - "__module__": "google.cloud.recommender_v1.proto.recommendation_pb2", - "__doc__": """Contains the impact a recommendation can have for a given category. - - Attributes: - category: - Category that is being targeted. - projection: - Contains projections (if any) for this category. - cost_projection: - Use with CategoryType.COST - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.Impact) - }, -) -_sym_db.RegisterMessage(Impact) - -RecommendationStateInfo = _reflection.GeneratedProtocolMessageType( - "RecommendationStateInfo", - (_message.Message,), - { - "StateMetadataEntry": _reflection.GeneratedProtocolMessageType( - "StateMetadataEntry", - (_message.Message,), - { - "DESCRIPTOR": _RECOMMENDATIONSTATEINFO_STATEMETADATAENTRY, - "__module__": "google.cloud.recommender_v1.proto.recommendation_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.RecommendationStateInfo.StateMetadataEntry) - }, - ), - "DESCRIPTOR": _RECOMMENDATIONSTATEINFO, - "__module__": "google.cloud.recommender_v1.proto.recommendation_pb2", - "__doc__": """Information for state. Contains state and metadata. - - Attributes: - state: - The state of the recommendation, Eg ACTIVE, SUCCEEDED, FAILED. - state_metadata: - A map of metadata for the state, provided by user or - automations systems. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.RecommendationStateInfo) - }, -) -_sym_db.RegisterMessage(RecommendationStateInfo) -_sym_db.RegisterMessage(RecommendationStateInfo.StateMetadataEntry) - - -DESCRIPTOR._options = None -_RECOMMENDATION._options = None -_OPERATION_PATHFILTERSENTRY._options = None -_OPERATION_PATHVALUEMATCHERSENTRY._options = None -_RECOMMENDATIONSTATEINFO_STATEMETADATAENTRY._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/recommender_v1/proto/recommendation_pb2_grpc.py b/google/cloud/recommender_v1/proto/recommendation_pb2_grpc.py deleted file mode 100644 index 8a93939..0000000 --- a/google/cloud/recommender_v1/proto/recommendation_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/recommender_v1/proto/recommender_service_pb2.py b/google/cloud/recommender_v1/proto/recommender_service_pb2.py deleted file mode 100644 index 77c9c04..0000000 --- a/google/cloud/recommender_v1/proto/recommender_service_pb2.py +++ /dev/null @@ -1,1471 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/recommender_v1/proto/recommender_service.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.recommender_v1.proto import ( - insight_pb2 as google_dot_cloud_dot_recommender__v1_dot_proto_dot_insight__pb2, -) -from google.cloud.recommender_v1.proto import ( - recommendation_pb2 as google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2, -) - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/recommender_v1/proto/recommender_service.proto", - package="google.cloud.recommender.v1", - syntax="proto3", - serialized_options=b"\n\037com.google.cloud.recommender.v1B\020RecommenderProtoP\001ZFgoogle.golang.org/genproto/googleapis/cloud/recommender/v1;recommender\242\002\004CREC\252\002\033Google.Cloud.Recommender.V1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n;google/cloud/recommender_v1/proto/recommender_service.proto\x12\x1bgoogle.cloud.recommender.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a/google/cloud/recommender_v1/proto/insight.proto\x1a\x36google/cloud/recommender_v1/proto/recommendation.proto"\x9b\x01\n\x13ListInsightsRequest\x12>\n\x06parent\x18\x01 \x01(\tB.\xe0\x41\x02\xfa\x41(\n&recommender.googleapis.com/InsightType\x12\x16\n\tpage_size\x18\x02 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x03 \x01(\tB\x03\xe0\x41\x01\x12\x13\n\x06\x66ilter\x18\x04 \x01(\tB\x03\xe0\x41\x01"g\n\x14ListInsightsResponse\x12\x36\n\x08insights\x18\x01 \x03(\x0b\x32$.google.cloud.recommender.v1.Insight\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"M\n\x11GetInsightRequest\x12\x38\n\x04name\x18\x01 \x01(\tB*\xe0\x41\x02\xfa\x41$\n"recommender.googleapis.com/Insight"\x88\x02\n\x1aMarkInsightAcceptedRequest\x12\x38\n\x04name\x18\x01 \x01(\tB*\xe0\x41\x02\xfa\x41$\n"recommender.googleapis.com/Insight\x12g\n\x0estate_metadata\x18\x02 \x03(\x0b\x32J.google.cloud.recommender.v1.MarkInsightAcceptedRequest.StateMetadataEntryB\x03\xe0\x41\x01\x12\x11\n\x04\x65tag\x18\x03 \x01(\tB\x03\xe0\x41\x02\x1a\x34\n\x12StateMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\x9d\x01\n\x1aListRecommendationsRequest\x12>\n\x06parent\x18\x01 \x01(\tB.\xe0\x41\x02\xfa\x41(\n&recommender.googleapis.com/Recommender\x12\x16\n\tpage_size\x18\x02 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x03 \x01(\tB\x03\xe0\x41\x01\x12\x0e\n\x06\x66ilter\x18\x05 \x01(\t"|\n\x1bListRecommendationsResponse\x12\x44\n\x0frecommendations\x18\x01 \x03(\x0b\x32+.google.cloud.recommender.v1.Recommendation\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"[\n\x18GetRecommendationRequest\x12?\n\x04name\x18\x01 \x01(\tB1\xe0\x41\x02\xfa\x41+\n)recommender.googleapis.com/Recommendation"\x96\x02\n MarkRecommendationClaimedRequest\x12?\n\x04name\x18\x01 \x01(\tB1\xe0\x41\x02\xfa\x41+\n)recommender.googleapis.com/Recommendation\x12h\n\x0estate_metadata\x18\x02 \x03(\x0b\x32P.google.cloud.recommender.v1.MarkRecommendationClaimedRequest.StateMetadataEntry\x12\x11\n\x04\x65tag\x18\x03 \x01(\tB\x03\xe0\x41\x02\x1a\x34\n\x12StateMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\x9a\x02\n"MarkRecommendationSucceededRequest\x12?\n\x04name\x18\x01 \x01(\tB1\xe0\x41\x02\xfa\x41+\n)recommender.googleapis.com/Recommendation\x12j\n\x0estate_metadata\x18\x02 \x03(\x0b\x32R.google.cloud.recommender.v1.MarkRecommendationSucceededRequest.StateMetadataEntry\x12\x11\n\x04\x65tag\x18\x03 \x01(\tB\x03\xe0\x41\x02\x1a\x34\n\x12StateMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\x94\x02\n\x1fMarkRecommendationFailedRequest\x12?\n\x04name\x18\x01 \x01(\tB1\xe0\x41\x02\xfa\x41+\n)recommender.googleapis.com/Recommendation\x12g\n\x0estate_metadata\x18\x02 \x03(\x0b\x32O.google.cloud.recommender.v1.MarkRecommendationFailedRequest.StateMetadataEntry\x12\x11\n\x04\x65tag\x18\x03 \x01(\tB\x03\xe0\x41\x02\x1a\x34\n\x12StateMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x32\xf9\x0e\n\x0bRecommender\x12\xc1\x01\n\x0cListInsights\x12\x30.google.cloud.recommender.v1.ListInsightsRequest\x1a\x31.google.cloud.recommender.v1.ListInsightsResponse"L\x82\xd3\xe4\x93\x02=\x12;/v1/{parent=projects/*/locations/*/insightTypes/*}/insights\xda\x41\x06parent\x12\xae\x01\n\nGetInsight\x12..google.cloud.recommender.v1.GetInsightRequest\x1a$.google.cloud.recommender.v1.Insight"J\x82\xd3\xe4\x93\x02=\x12;/v1/{name=projects/*/locations/*/insightTypes/*/insights/*}\xda\x41\x04name\x12\xe4\x01\n\x13MarkInsightAccepted\x12\x37.google.cloud.recommender.v1.MarkInsightAcceptedRequest\x1a$.google.cloud.recommender.v1.Insight"n\x82\xd3\xe4\x93\x02M"H/v1/{name=projects/*/locations/*/insightTypes/*/insights/*}:markAccepted:\x01*\xda\x41\x18name,state_metadata,etag\x12\xed\x01\n\x13ListRecommendations\x12\x37.google.cloud.recommender.v1.ListRecommendationsRequest\x1a\x38.google.cloud.recommender.v1.ListRecommendationsResponse"c\x82\xd3\xe4\x93\x02\x44\x12\x42/v1/{parent=projects/*/locations/*/recommenders/*}/recommendations\xda\x41\x06parent\xda\x41\rparent,filter\x12\xca\x01\n\x11GetRecommendation\x12\x35.google.cloud.recommender.v1.GetRecommendationRequest\x1a+.google.cloud.recommender.v1.Recommendation"Q\x82\xd3\xe4\x93\x02\x44\x12\x42/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}\xda\x41\x04name\x12\xfd\x01\n\x19MarkRecommendationClaimed\x12=.google.cloud.recommender.v1.MarkRecommendationClaimedRequest\x1a+.google.cloud.recommender.v1.Recommendation"t\x82\xd3\xe4\x93\x02S"N/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markClaimed:\x01*\xda\x41\x18name,state_metadata,etag\x12\x83\x02\n\x1bMarkRecommendationSucceeded\x12?.google.cloud.recommender.v1.MarkRecommendationSucceededRequest\x1a+.google.cloud.recommender.v1.Recommendation"v\x82\xd3\xe4\x93\x02U"P/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markSucceeded:\x01*\xda\x41\x18name,state_metadata,etag\x12\xfa\x01\n\x18MarkRecommendationFailed\x12<.google.cloud.recommender.v1.MarkRecommendationFailedRequest\x1a+.google.cloud.recommender.v1.Recommendation"s\x82\xd3\xe4\x93\x02R"M/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markFailed:\x01*\xda\x41\x18name,state_metadata,etag\x1aN\xca\x41\x1arecommender.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\xa2\x01\n\x1f\x63om.google.cloud.recommender.v1B\x10RecommenderProtoP\x01ZFgoogle.golang.org/genproto/googleapis/cloud/recommender/v1;recommender\xa2\x02\x04\x43REC\xaa\x02\x1bGoogle.Cloud.Recommender.V1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_recommender__v1_dot_proto_dot_insight__pb2.DESCRIPTOR, - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2.DESCRIPTOR, - ], -) - - -_LISTINSIGHTSREQUEST = _descriptor.Descriptor( - name="ListInsightsRequest", - full_name="google.cloud.recommender.v1.ListInsightsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.recommender.v1.ListInsightsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A(\n&recommender.googleapis.com/InsightType", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.recommender.v1.ListInsightsRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.recommender.v1.ListInsightsRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.recommender.v1.ListInsightsRequest.filter", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=313, - serialized_end=468, -) - - -_LISTINSIGHTSRESPONSE = _descriptor.Descriptor( - name="ListInsightsResponse", - full_name="google.cloud.recommender.v1.ListInsightsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="insights", - full_name="google.cloud.recommender.v1.ListInsightsResponse.insights", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.recommender.v1.ListInsightsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=470, - serialized_end=573, -) - - -_GETINSIGHTREQUEST = _descriptor.Descriptor( - name="GetInsightRequest", - full_name="google.cloud.recommender.v1.GetInsightRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1.GetInsightRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A$\n"recommender.googleapis.com/Insight', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=575, - serialized_end=652, -) - - -_MARKINSIGHTACCEPTEDREQUEST_STATEMETADATAENTRY = _descriptor.Descriptor( - name="StateMetadataEntry", - full_name="google.cloud.recommender.v1.MarkInsightAcceptedRequest.StateMetadataEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1.MarkInsightAcceptedRequest.StateMetadataEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1.MarkInsightAcceptedRequest.StateMetadataEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=867, - serialized_end=919, -) - -_MARKINSIGHTACCEPTEDREQUEST = _descriptor.Descriptor( - name="MarkInsightAcceptedRequest", - full_name="google.cloud.recommender.v1.MarkInsightAcceptedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1.MarkInsightAcceptedRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A$\n"recommender.googleapis.com/Insight', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_metadata", - full_name="google.cloud.recommender.v1.MarkInsightAcceptedRequest.state_metadata", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="etag", - full_name="google.cloud.recommender.v1.MarkInsightAcceptedRequest.etag", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_MARKINSIGHTACCEPTEDREQUEST_STATEMETADATAENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=655, - serialized_end=919, -) - - -_LISTRECOMMENDATIONSREQUEST = _descriptor.Descriptor( - name="ListRecommendationsRequest", - full_name="google.cloud.recommender.v1.ListRecommendationsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.recommender.v1.ListRecommendationsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A(\n&recommender.googleapis.com/Recommender", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.recommender.v1.ListRecommendationsRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.recommender.v1.ListRecommendationsRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.recommender.v1.ListRecommendationsRequest.filter", - index=3, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=922, - serialized_end=1079, -) - - -_LISTRECOMMENDATIONSRESPONSE = _descriptor.Descriptor( - name="ListRecommendationsResponse", - full_name="google.cloud.recommender.v1.ListRecommendationsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="recommendations", - full_name="google.cloud.recommender.v1.ListRecommendationsResponse.recommendations", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.recommender.v1.ListRecommendationsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1081, - serialized_end=1205, -) - - -_GETRECOMMENDATIONREQUEST = _descriptor.Descriptor( - name="GetRecommendationRequest", - full_name="google.cloud.recommender.v1.GetRecommendationRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1.GetRecommendationRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A+\n)recommender.googleapis.com/Recommendation", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1207, - serialized_end=1298, -) - - -_MARKRECOMMENDATIONCLAIMEDREQUEST_STATEMETADATAENTRY = _descriptor.Descriptor( - name="StateMetadataEntry", - full_name="google.cloud.recommender.v1.MarkRecommendationClaimedRequest.StateMetadataEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1.MarkRecommendationClaimedRequest.StateMetadataEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1.MarkRecommendationClaimedRequest.StateMetadataEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=867, - serialized_end=919, -) - -_MARKRECOMMENDATIONCLAIMEDREQUEST = _descriptor.Descriptor( - name="MarkRecommendationClaimedRequest", - full_name="google.cloud.recommender.v1.MarkRecommendationClaimedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1.MarkRecommendationClaimedRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A+\n)recommender.googleapis.com/Recommendation", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_metadata", - full_name="google.cloud.recommender.v1.MarkRecommendationClaimedRequest.state_metadata", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="etag", - full_name="google.cloud.recommender.v1.MarkRecommendationClaimedRequest.etag", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_MARKRECOMMENDATIONCLAIMEDREQUEST_STATEMETADATAENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1301, - serialized_end=1579, -) - - -_MARKRECOMMENDATIONSUCCEEDEDREQUEST_STATEMETADATAENTRY = _descriptor.Descriptor( - name="StateMetadataEntry", - full_name="google.cloud.recommender.v1.MarkRecommendationSucceededRequest.StateMetadataEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1.MarkRecommendationSucceededRequest.StateMetadataEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1.MarkRecommendationSucceededRequest.StateMetadataEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=867, - serialized_end=919, -) - -_MARKRECOMMENDATIONSUCCEEDEDREQUEST = _descriptor.Descriptor( - name="MarkRecommendationSucceededRequest", - full_name="google.cloud.recommender.v1.MarkRecommendationSucceededRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1.MarkRecommendationSucceededRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A+\n)recommender.googleapis.com/Recommendation", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_metadata", - full_name="google.cloud.recommender.v1.MarkRecommendationSucceededRequest.state_metadata", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="etag", - full_name="google.cloud.recommender.v1.MarkRecommendationSucceededRequest.etag", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_MARKRECOMMENDATIONSUCCEEDEDREQUEST_STATEMETADATAENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1582, - serialized_end=1864, -) - - -_MARKRECOMMENDATIONFAILEDREQUEST_STATEMETADATAENTRY = _descriptor.Descriptor( - name="StateMetadataEntry", - full_name="google.cloud.recommender.v1.MarkRecommendationFailedRequest.StateMetadataEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1.MarkRecommendationFailedRequest.StateMetadataEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1.MarkRecommendationFailedRequest.StateMetadataEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=867, - serialized_end=919, -) - -_MARKRECOMMENDATIONFAILEDREQUEST = _descriptor.Descriptor( - name="MarkRecommendationFailedRequest", - full_name="google.cloud.recommender.v1.MarkRecommendationFailedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1.MarkRecommendationFailedRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A+\n)recommender.googleapis.com/Recommendation", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_metadata", - full_name="google.cloud.recommender.v1.MarkRecommendationFailedRequest.state_metadata", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="etag", - full_name="google.cloud.recommender.v1.MarkRecommendationFailedRequest.etag", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_MARKRECOMMENDATIONFAILEDREQUEST_STATEMETADATAENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1867, - serialized_end=2143, -) - -_LISTINSIGHTSRESPONSE.fields_by_name[ - "insights" -].message_type = ( - google_dot_cloud_dot_recommender__v1_dot_proto_dot_insight__pb2._INSIGHT -) -_MARKINSIGHTACCEPTEDREQUEST_STATEMETADATAENTRY.containing_type = ( - _MARKINSIGHTACCEPTEDREQUEST -) -_MARKINSIGHTACCEPTEDREQUEST.fields_by_name[ - "state_metadata" -].message_type = _MARKINSIGHTACCEPTEDREQUEST_STATEMETADATAENTRY -_LISTRECOMMENDATIONSRESPONSE.fields_by_name[ - "recommendations" -].message_type = ( - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2._RECOMMENDATION -) -_MARKRECOMMENDATIONCLAIMEDREQUEST_STATEMETADATAENTRY.containing_type = ( - _MARKRECOMMENDATIONCLAIMEDREQUEST -) -_MARKRECOMMENDATIONCLAIMEDREQUEST.fields_by_name[ - "state_metadata" -].message_type = _MARKRECOMMENDATIONCLAIMEDREQUEST_STATEMETADATAENTRY -_MARKRECOMMENDATIONSUCCEEDEDREQUEST_STATEMETADATAENTRY.containing_type = ( - _MARKRECOMMENDATIONSUCCEEDEDREQUEST -) -_MARKRECOMMENDATIONSUCCEEDEDREQUEST.fields_by_name[ - "state_metadata" -].message_type = _MARKRECOMMENDATIONSUCCEEDEDREQUEST_STATEMETADATAENTRY -_MARKRECOMMENDATIONFAILEDREQUEST_STATEMETADATAENTRY.containing_type = ( - _MARKRECOMMENDATIONFAILEDREQUEST -) -_MARKRECOMMENDATIONFAILEDREQUEST.fields_by_name[ - "state_metadata" -].message_type = _MARKRECOMMENDATIONFAILEDREQUEST_STATEMETADATAENTRY -DESCRIPTOR.message_types_by_name["ListInsightsRequest"] = _LISTINSIGHTSREQUEST -DESCRIPTOR.message_types_by_name["ListInsightsResponse"] = _LISTINSIGHTSRESPONSE -DESCRIPTOR.message_types_by_name["GetInsightRequest"] = _GETINSIGHTREQUEST -DESCRIPTOR.message_types_by_name[ - "MarkInsightAcceptedRequest" -] = _MARKINSIGHTACCEPTEDREQUEST -DESCRIPTOR.message_types_by_name[ - "ListRecommendationsRequest" -] = _LISTRECOMMENDATIONSREQUEST -DESCRIPTOR.message_types_by_name[ - "ListRecommendationsResponse" -] = _LISTRECOMMENDATIONSRESPONSE -DESCRIPTOR.message_types_by_name["GetRecommendationRequest"] = _GETRECOMMENDATIONREQUEST -DESCRIPTOR.message_types_by_name[ - "MarkRecommendationClaimedRequest" -] = _MARKRECOMMENDATIONCLAIMEDREQUEST -DESCRIPTOR.message_types_by_name[ - "MarkRecommendationSucceededRequest" -] = _MARKRECOMMENDATIONSUCCEEDEDREQUEST -DESCRIPTOR.message_types_by_name[ - "MarkRecommendationFailedRequest" -] = _MARKRECOMMENDATIONFAILEDREQUEST -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -ListInsightsRequest = _reflection.GeneratedProtocolMessageType( - "ListInsightsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTINSIGHTSREQUEST, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2", - "__doc__": """Request for the ``ListInsights`` method. - - Attributes: - parent: - Required. The container resource on which to execute the - request. Acceptable formats: 1. “projects/[PROJECT_NUMBER]/lo - cations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]”, LOCATION - here refers to GCP Locations: - https://cloud.google.com/about/locations/ - page_size: - Optional. The maximum number of results to return from this - request. Non-positive values are ignored. If not specified, - the server will determine the number of results to return. - page_token: - Optional. If present, retrieves the next batch of results from - the preceding call to this method. ``page_token`` must be the - value of ``next_page_token`` from the previous response. The - values of other method parameters must be identical to those - in the previous call. - filter: - Optional. Filter expression to restrict the insights returned. - Supported filter fields: state Eg: \`state:“DISMISSED” or - state:“ACTIVE” - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.ListInsightsRequest) - }, -) -_sym_db.RegisterMessage(ListInsightsRequest) - -ListInsightsResponse = _reflection.GeneratedProtocolMessageType( - "ListInsightsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTINSIGHTSRESPONSE, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2", - "__doc__": """Response to the ``ListInsights`` method. - - Attributes: - insights: - The set of insights for the ``parent`` resource. - next_page_token: - A token that can be used to request the next page of results. - This field is empty if there are no additional results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.ListInsightsResponse) - }, -) -_sym_db.RegisterMessage(ListInsightsResponse) - -GetInsightRequest = _reflection.GeneratedProtocolMessageType( - "GetInsightRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETINSIGHTREQUEST, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2", - "__doc__": """Request to the ``GetInsight`` method. - - Attributes: - name: - Required. Name of the insight. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.GetInsightRequest) - }, -) -_sym_db.RegisterMessage(GetInsightRequest) - -MarkInsightAcceptedRequest = _reflection.GeneratedProtocolMessageType( - "MarkInsightAcceptedRequest", - (_message.Message,), - { - "StateMetadataEntry": _reflection.GeneratedProtocolMessageType( - "StateMetadataEntry", - (_message.Message,), - { - "DESCRIPTOR": _MARKINSIGHTACCEPTEDREQUEST_STATEMETADATAENTRY, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.MarkInsightAcceptedRequest.StateMetadataEntry) - }, - ), - "DESCRIPTOR": _MARKINSIGHTACCEPTEDREQUEST, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2", - "__doc__": """Request for the ``MarkInsightAccepted`` method. - - Attributes: - name: - Required. Name of the insight. - state_metadata: - Optional. State properties user wish to include with this - state. Full replace of the current state_metadata. - etag: - Required. Fingerprint of the Insight. Provides optimistic - locking. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.MarkInsightAcceptedRequest) - }, -) -_sym_db.RegisterMessage(MarkInsightAcceptedRequest) -_sym_db.RegisterMessage(MarkInsightAcceptedRequest.StateMetadataEntry) - -ListRecommendationsRequest = _reflection.GeneratedProtocolMessageType( - "ListRecommendationsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTRECOMMENDATIONSREQUEST, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2", - "__doc__": """Request for the ``ListRecommendations`` method. - - Attributes: - parent: - Required. The container resource on which to execute the - request. Acceptable formats: 1. “projects/[PROJECT_NUMBER]/lo - cations/[LOCATION]/recommenders/[RECOMMENDER_ID]”, LOCATION - here refers to GCP Locations: - https://cloud.google.com/about/locations/ - page_size: - Optional. The maximum number of results to return from this - request. Non-positive values are ignored. If not specified, - the server will determine the number of results to return. - page_token: - Optional. If present, retrieves the next batch of results from - the preceding call to this method. ``page_token`` must be the - value of ``next_page_token`` from the previous response. The - values of other method parameters must be identical to those - in the previous call. - filter: - Filter expression to restrict the recommendations returned. - Supported filter fields: state_info.state Eg: - \`state_info.state:“DISMISSED” or state_info.state:“FAILED” - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.ListRecommendationsRequest) - }, -) -_sym_db.RegisterMessage(ListRecommendationsRequest) - -ListRecommendationsResponse = _reflection.GeneratedProtocolMessageType( - "ListRecommendationsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTRECOMMENDATIONSRESPONSE, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2", - "__doc__": """Response to the ``ListRecommendations`` method. - - Attributes: - recommendations: - The set of recommendations for the ``parent`` resource. - next_page_token: - A token that can be used to request the next page of results. - This field is empty if there are no additional results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.ListRecommendationsResponse) - }, -) -_sym_db.RegisterMessage(ListRecommendationsResponse) - -GetRecommendationRequest = _reflection.GeneratedProtocolMessageType( - "GetRecommendationRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETRECOMMENDATIONREQUEST, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2", - "__doc__": """Request to the ``GetRecommendation`` method. - - Attributes: - name: - Required. Name of the recommendation. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.GetRecommendationRequest) - }, -) -_sym_db.RegisterMessage(GetRecommendationRequest) - -MarkRecommendationClaimedRequest = _reflection.GeneratedProtocolMessageType( - "MarkRecommendationClaimedRequest", - (_message.Message,), - { - "StateMetadataEntry": _reflection.GeneratedProtocolMessageType( - "StateMetadataEntry", - (_message.Message,), - { - "DESCRIPTOR": _MARKRECOMMENDATIONCLAIMEDREQUEST_STATEMETADATAENTRY, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.MarkRecommendationClaimedRequest.StateMetadataEntry) - }, - ), - "DESCRIPTOR": _MARKRECOMMENDATIONCLAIMEDREQUEST, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2", - "__doc__": """Request for the ``MarkRecommendationClaimed`` Method. - - Attributes: - name: - Required. Name of the recommendation. - state_metadata: - State properties to include with this state. Overwrites any - existing ``state_metadata``. Keys must match the regex ``/ - [3]_[a-z0-9_.-]{0,62}/``. Values must match the regex - ``/^[a-zA-Z0-9_./-]{0,255}/``. - etag: - Required. Fingerprint of the Recommendation. Provides - optimistic locking. .. [1] a-z0-9 .. [2] a-z0-9 .. - [3] a-z0-9 - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.MarkRecommendationClaimedRequest) - }, -) -_sym_db.RegisterMessage(MarkRecommendationClaimedRequest) -_sym_db.RegisterMessage(MarkRecommendationClaimedRequest.StateMetadataEntry) - -MarkRecommendationSucceededRequest = _reflection.GeneratedProtocolMessageType( - "MarkRecommendationSucceededRequest", - (_message.Message,), - { - "StateMetadataEntry": _reflection.GeneratedProtocolMessageType( - "StateMetadataEntry", - (_message.Message,), - { - "DESCRIPTOR": _MARKRECOMMENDATIONSUCCEEDEDREQUEST_STATEMETADATAENTRY, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.MarkRecommendationSucceededRequest.StateMetadataEntry) - }, - ), - "DESCRIPTOR": _MARKRECOMMENDATIONSUCCEEDEDREQUEST, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2", - "__doc__": """Request for the ``MarkRecommendationSucceeded`` Method. - - Attributes: - name: - Required. Name of the recommendation. - state_metadata: - State properties to include with this state. Overwrites any - existing ``state_metadata``. Keys must match the regex ``/ - [2]_[a-z0-9_.-]{0,62}/``. Values must match the regex - ``/^[a-zA-Z0-9_./-]{0,255}/``. - etag: - Required. Fingerprint of the Recommendation. Provides - optimistic locking. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.MarkRecommendationSucceededRequest) - }, -) -_sym_db.RegisterMessage(MarkRecommendationSucceededRequest) -_sym_db.RegisterMessage(MarkRecommendationSucceededRequest.StateMetadataEntry) - -MarkRecommendationFailedRequest = _reflection.GeneratedProtocolMessageType( - "MarkRecommendationFailedRequest", - (_message.Message,), - { - "StateMetadataEntry": _reflection.GeneratedProtocolMessageType( - "StateMetadataEntry", - (_message.Message,), - { - "DESCRIPTOR": _MARKRECOMMENDATIONFAILEDREQUEST_STATEMETADATAENTRY, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.MarkRecommendationFailedRequest.StateMetadataEntry) - }, - ), - "DESCRIPTOR": _MARKRECOMMENDATIONFAILEDREQUEST, - "__module__": "google.cloud.recommender_v1.proto.recommender_service_pb2", - "__doc__": """Request for the ``MarkRecommendationFailed`` Method. - - Attributes: - name: - Required. Name of the recommendation. - state_metadata: - State properties to include with this state. Overwrites any - existing ``state_metadata``. Keys must match the regex ``/ - [1]_[a-z0-9_.-]{0,62}/``. Values must match the regex - ``/^[a-zA-Z0-9_./-]{0,255}/``. - etag: - Required. Fingerprint of the Recommendation. Provides - optimistic locking. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.MarkRecommendationFailedRequest) - }, -) -_sym_db.RegisterMessage(MarkRecommendationFailedRequest) -_sym_db.RegisterMessage(MarkRecommendationFailedRequest.StateMetadataEntry) - - -DESCRIPTOR._options = None -_LISTINSIGHTSREQUEST.fields_by_name["parent"]._options = None -_LISTINSIGHTSREQUEST.fields_by_name["page_size"]._options = None -_LISTINSIGHTSREQUEST.fields_by_name["page_token"]._options = None -_LISTINSIGHTSREQUEST.fields_by_name["filter"]._options = None -_GETINSIGHTREQUEST.fields_by_name["name"]._options = None -_MARKINSIGHTACCEPTEDREQUEST_STATEMETADATAENTRY._options = None -_MARKINSIGHTACCEPTEDREQUEST.fields_by_name["name"]._options = None -_MARKINSIGHTACCEPTEDREQUEST.fields_by_name["state_metadata"]._options = None -_MARKINSIGHTACCEPTEDREQUEST.fields_by_name["etag"]._options = None -_LISTRECOMMENDATIONSREQUEST.fields_by_name["parent"]._options = None -_LISTRECOMMENDATIONSREQUEST.fields_by_name["page_size"]._options = None -_LISTRECOMMENDATIONSREQUEST.fields_by_name["page_token"]._options = None -_GETRECOMMENDATIONREQUEST.fields_by_name["name"]._options = None -_MARKRECOMMENDATIONCLAIMEDREQUEST_STATEMETADATAENTRY._options = None -_MARKRECOMMENDATIONCLAIMEDREQUEST.fields_by_name["name"]._options = None -_MARKRECOMMENDATIONCLAIMEDREQUEST.fields_by_name["etag"]._options = None -_MARKRECOMMENDATIONSUCCEEDEDREQUEST_STATEMETADATAENTRY._options = None -_MARKRECOMMENDATIONSUCCEEDEDREQUEST.fields_by_name["name"]._options = None -_MARKRECOMMENDATIONSUCCEEDEDREQUEST.fields_by_name["etag"]._options = None -_MARKRECOMMENDATIONFAILEDREQUEST_STATEMETADATAENTRY._options = None -_MARKRECOMMENDATIONFAILEDREQUEST.fields_by_name["name"]._options = None -_MARKRECOMMENDATIONFAILEDREQUEST.fields_by_name["etag"]._options = None - -_RECOMMENDER = _descriptor.ServiceDescriptor( - name="Recommender", - full_name="google.cloud.recommender.v1.Recommender", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\032recommender.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", - create_key=_descriptor._internal_create_key, - serialized_start=2146, - serialized_end=4059, - methods=[ - _descriptor.MethodDescriptor( - name="ListInsights", - full_name="google.cloud.recommender.v1.Recommender.ListInsights", - index=0, - containing_service=None, - input_type=_LISTINSIGHTSREQUEST, - output_type=_LISTINSIGHTSRESPONSE, - serialized_options=b"\202\323\344\223\002=\022;/v1/{parent=projects/*/locations/*/insightTypes/*}/insights\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetInsight", - full_name="google.cloud.recommender.v1.Recommender.GetInsight", - index=1, - containing_service=None, - input_type=_GETINSIGHTREQUEST, - output_type=google_dot_cloud_dot_recommender__v1_dot_proto_dot_insight__pb2._INSIGHT, - serialized_options=b"\202\323\344\223\002=\022;/v1/{name=projects/*/locations/*/insightTypes/*/insights/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="MarkInsightAccepted", - full_name="google.cloud.recommender.v1.Recommender.MarkInsightAccepted", - index=2, - containing_service=None, - input_type=_MARKINSIGHTACCEPTEDREQUEST, - output_type=google_dot_cloud_dot_recommender__v1_dot_proto_dot_insight__pb2._INSIGHT, - serialized_options=b'\202\323\344\223\002M"H/v1/{name=projects/*/locations/*/insightTypes/*/insights/*}:markAccepted:\001*\332A\030name,state_metadata,etag', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListRecommendations", - full_name="google.cloud.recommender.v1.Recommender.ListRecommendations", - index=3, - containing_service=None, - input_type=_LISTRECOMMENDATIONSREQUEST, - output_type=_LISTRECOMMENDATIONSRESPONSE, - serialized_options=b"\202\323\344\223\002D\022B/v1/{parent=projects/*/locations/*/recommenders/*}/recommendations\332A\006parent\332A\rparent,filter", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetRecommendation", - full_name="google.cloud.recommender.v1.Recommender.GetRecommendation", - index=4, - containing_service=None, - input_type=_GETRECOMMENDATIONREQUEST, - output_type=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2._RECOMMENDATION, - serialized_options=b"\202\323\344\223\002D\022B/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="MarkRecommendationClaimed", - full_name="google.cloud.recommender.v1.Recommender.MarkRecommendationClaimed", - index=5, - containing_service=None, - input_type=_MARKRECOMMENDATIONCLAIMEDREQUEST, - output_type=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2._RECOMMENDATION, - serialized_options=b'\202\323\344\223\002S"N/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markClaimed:\001*\332A\030name,state_metadata,etag', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="MarkRecommendationSucceeded", - full_name="google.cloud.recommender.v1.Recommender.MarkRecommendationSucceeded", - index=6, - containing_service=None, - input_type=_MARKRECOMMENDATIONSUCCEEDEDREQUEST, - output_type=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2._RECOMMENDATION, - serialized_options=b'\202\323\344\223\002U"P/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markSucceeded:\001*\332A\030name,state_metadata,etag', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="MarkRecommendationFailed", - full_name="google.cloud.recommender.v1.Recommender.MarkRecommendationFailed", - index=7, - containing_service=None, - input_type=_MARKRECOMMENDATIONFAILEDREQUEST, - output_type=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2._RECOMMENDATION, - serialized_options=b'\202\323\344\223\002R"M/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markFailed:\001*\332A\030name,state_metadata,etag', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_RECOMMENDER) - -DESCRIPTOR.services_by_name["Recommender"] = _RECOMMENDER - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/recommender_v1/proto/recommender_service_pb2_grpc.py b/google/cloud/recommender_v1/proto/recommender_service_pb2_grpc.py deleted file mode 100644 index 1eced58..0000000 --- a/google/cloud/recommender_v1/proto/recommender_service_pb2_grpc.py +++ /dev/null @@ -1,460 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.recommender_v1.proto import ( - insight_pb2 as google_dot_cloud_dot_recommender__v1_dot_proto_dot_insight__pb2, -) -from google.cloud.recommender_v1.proto import ( - recommendation_pb2 as google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2, -) -from google.cloud.recommender_v1.proto import ( - recommender_service_pb2 as google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2, -) - - -class RecommenderStub(object): - """Provides insights and recommendations for cloud customers for various - categories like performance optimization, cost savings, reliability, feature - discovery, etc. Insights and recommendations are generated automatically - based on analysis of user resources, configuration and monitoring metrics. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.ListInsights = channel.unary_unary( - "/google.cloud.recommender.v1.Recommender/ListInsights", - request_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.ListInsightsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.ListInsightsResponse.FromString, - ) - self.GetInsight = channel.unary_unary( - "/google.cloud.recommender.v1.Recommender/GetInsight", - request_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.GetInsightRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_insight__pb2.Insight.FromString, - ) - self.MarkInsightAccepted = channel.unary_unary( - "/google.cloud.recommender.v1.Recommender/MarkInsightAccepted", - request_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.MarkInsightAcceptedRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_insight__pb2.Insight.FromString, - ) - self.ListRecommendations = channel.unary_unary( - "/google.cloud.recommender.v1.Recommender/ListRecommendations", - request_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.ListRecommendationsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.ListRecommendationsResponse.FromString, - ) - self.GetRecommendation = channel.unary_unary( - "/google.cloud.recommender.v1.Recommender/GetRecommendation", - request_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.GetRecommendationRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - ) - self.MarkRecommendationClaimed = channel.unary_unary( - "/google.cloud.recommender.v1.Recommender/MarkRecommendationClaimed", - request_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.MarkRecommendationClaimedRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - ) - self.MarkRecommendationSucceeded = channel.unary_unary( - "/google.cloud.recommender.v1.Recommender/MarkRecommendationSucceeded", - request_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.MarkRecommendationSucceededRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - ) - self.MarkRecommendationFailed = channel.unary_unary( - "/google.cloud.recommender.v1.Recommender/MarkRecommendationFailed", - request_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.MarkRecommendationFailedRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - ) - - -class RecommenderServicer(object): - """Provides insights and recommendations for cloud customers for various - categories like performance optimization, cost savings, reliability, feature - discovery, etc. Insights and recommendations are generated automatically - based on analysis of user resources, configuration and monitoring metrics. - """ - - def ListInsights(self, request, context): - """Lists insights for a Cloud project. Requires the recommender.*.list IAM - permission for the specified insight type. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetInsight(self, request, context): - """Gets the requested insight. Requires the recommender.*.get IAM permission - for the specified insight type. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def MarkInsightAccepted(self, request, context): - """Marks the Insight State as Accepted. Users can use this method to - indicate to the Recommender API that they have applied some action based - on the insight. This stops the insight content from being updated. - - MarkInsightAccepted can be applied to insights in ACTIVE state. Requires - the recommender.*.update IAM permission for the specified insight. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListRecommendations(self, request, context): - """Lists recommendations for a Cloud project. Requires the recommender.*.list - IAM permission for the specified recommender. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetRecommendation(self, request, context): - """Gets the requested recommendation. Requires the recommender.*.get - IAM permission for the specified recommender. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def MarkRecommendationClaimed(self, request, context): - """Marks the Recommendation State as Claimed. Users can use this method to - indicate to the Recommender API that they are starting to apply the - recommendation themselves. This stops the recommendation content from being - updated. Associated insights are frozen and placed in the ACCEPTED state. - - MarkRecommendationClaimed can be applied to recommendations in CLAIMED, - SUCCEEDED, FAILED, or ACTIVE state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def MarkRecommendationSucceeded(self, request, context): - """Marks the Recommendation State as Succeeded. Users can use this method to - indicate to the Recommender API that they have applied the recommendation - themselves, and the operation was successful. This stops the recommendation - content from being updated. Associated insights are frozen and placed in - the ACCEPTED state. - - MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, - CLAIMED, SUCCEEDED, or FAILED state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def MarkRecommendationFailed(self, request, context): - """Marks the Recommendation State as Failed. Users can use this method to - indicate to the Recommender API that they have applied the recommendation - themselves, and the operation failed. This stops the recommendation content - from being updated. Associated insights are frozen and placed in the - ACCEPTED state. - - MarkRecommendationFailed can be applied to recommendations in ACTIVE, - CLAIMED, SUCCEEDED, or FAILED state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_RecommenderServicer_to_server(servicer, server): - rpc_method_handlers = { - "ListInsights": grpc.unary_unary_rpc_method_handler( - servicer.ListInsights, - request_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.ListInsightsRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.ListInsightsResponse.SerializeToString, - ), - "GetInsight": grpc.unary_unary_rpc_method_handler( - servicer.GetInsight, - request_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.GetInsightRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_insight__pb2.Insight.SerializeToString, - ), - "MarkInsightAccepted": grpc.unary_unary_rpc_method_handler( - servicer.MarkInsightAccepted, - request_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.MarkInsightAcceptedRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_insight__pb2.Insight.SerializeToString, - ), - "ListRecommendations": grpc.unary_unary_rpc_method_handler( - servicer.ListRecommendations, - request_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.ListRecommendationsRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.ListRecommendationsResponse.SerializeToString, - ), - "GetRecommendation": grpc.unary_unary_rpc_method_handler( - servicer.GetRecommendation, - request_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.GetRecommendationRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2.Recommendation.SerializeToString, - ), - "MarkRecommendationClaimed": grpc.unary_unary_rpc_method_handler( - servicer.MarkRecommendationClaimed, - request_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.MarkRecommendationClaimedRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2.Recommendation.SerializeToString, - ), - "MarkRecommendationSucceeded": grpc.unary_unary_rpc_method_handler( - servicer.MarkRecommendationSucceeded, - request_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.MarkRecommendationSucceededRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2.Recommendation.SerializeToString, - ), - "MarkRecommendationFailed": grpc.unary_unary_rpc_method_handler( - servicer.MarkRecommendationFailed, - request_deserializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.MarkRecommendationFailedRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2.Recommendation.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.recommender.v1.Recommender", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class Recommender(object): - """Provides insights and recommendations for cloud customers for various - categories like performance optimization, cost savings, reliability, feature - discovery, etc. Insights and recommendations are generated automatically - based on analysis of user resources, configuration and monitoring metrics. - """ - - @staticmethod - def ListInsights( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1.Recommender/ListInsights", - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.ListInsightsRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.ListInsightsResponse.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetInsight( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1.Recommender/GetInsight", - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.GetInsightRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1_dot_proto_dot_insight__pb2.Insight.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def MarkInsightAccepted( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1.Recommender/MarkInsightAccepted", - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.MarkInsightAcceptedRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1_dot_proto_dot_insight__pb2.Insight.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListRecommendations( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1.Recommender/ListRecommendations", - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.ListRecommendationsRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.ListRecommendationsResponse.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetRecommendation( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1.Recommender/GetRecommendation", - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.GetRecommendationRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def MarkRecommendationClaimed( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1.Recommender/MarkRecommendationClaimed", - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.MarkRecommendationClaimedRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def MarkRecommendationSucceeded( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1.Recommender/MarkRecommendationSucceeded", - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.MarkRecommendationSucceededRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def MarkRecommendationFailed( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1.Recommender/MarkRecommendationFailed", - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommender__service__pb2.MarkRecommendationFailedRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/recommender_v1/py.typed b/google/cloud/recommender_v1/py.typed new file mode 100644 index 0000000..f9105be --- /dev/null +++ b/google/cloud/recommender_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-recommender package uses inline types. diff --git a/google/cloud/recommender.py b/google/cloud/recommender_v1/services/__init__.py similarity index 64% rename from google/cloud/recommender.py rename to google/cloud/recommender_v1/services/__init__.py index 3dd5ddd..42ffdf2 100644 --- a/google/cloud/recommender.py +++ b/google/cloud/recommender_v1/services/__init__.py @@ -1,29 +1,16 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - - -from __future__ import absolute_import - -from google.cloud.recommender_v1 import RecommenderClient -from google.cloud.recommender_v1 import enums -from google.cloud.recommender_v1 import types - - -__all__ = ( - "enums", - "types", - "RecommenderClient", -) +# diff --git a/google/__init__.py b/google/cloud/recommender_v1/services/recommender/__init__.py similarity index 71% rename from google/__init__.py rename to google/cloud/recommender_v1/services/recommender/__init__.py index 9a1b64a..bfe4af8 100644 --- a/google/__init__.py +++ b/google/cloud/recommender_v1/services/recommender/__init__.py @@ -1,24 +1,24 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil +from .client import RecommenderClient +from .async_client import RecommenderAsyncClient - __path__ = pkgutil.extend_path(__path__, __name__) +__all__ = ( + "RecommenderClient", + "RecommenderAsyncClient", +) diff --git a/google/cloud/recommender_v1/services/recommender/async_client.py b/google/cloud/recommender_v1/services/recommender/async_client.py new file mode 100644 index 0000000..bdb77f5 --- /dev/null +++ b/google/cloud/recommender_v1/services/recommender/async_client.py @@ -0,0 +1,957 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.recommender_v1.services.recommender import pagers +from google.cloud.recommender_v1.types import insight +from google.cloud.recommender_v1.types import recommendation +from google.cloud.recommender_v1.types import recommender_service +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import RecommenderTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RecommenderGrpcAsyncIOTransport +from .client import RecommenderClient + + +class RecommenderAsyncClient: + """Provides insights and recommendations for cloud customers for + various categories like performance optimization, cost savings, + reliability, feature discovery, etc. Insights and + recommendations are generated automatically based on analysis of + user resources, configuration and monitoring metrics. + """ + + _client: RecommenderClient + + DEFAULT_ENDPOINT = RecommenderClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RecommenderClient.DEFAULT_MTLS_ENDPOINT + + insight_path = staticmethod(RecommenderClient.insight_path) + parse_insight_path = staticmethod(RecommenderClient.parse_insight_path) + insight_type_path = staticmethod(RecommenderClient.insight_type_path) + parse_insight_type_path = staticmethod(RecommenderClient.parse_insight_type_path) + recommendation_path = staticmethod(RecommenderClient.recommendation_path) + parse_recommendation_path = staticmethod( + RecommenderClient.parse_recommendation_path + ) + recommender_path = staticmethod(RecommenderClient.recommender_path) + parse_recommender_path = staticmethod(RecommenderClient.parse_recommender_path) + + common_billing_account_path = staticmethod( + RecommenderClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + RecommenderClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(RecommenderClient.common_folder_path) + parse_common_folder_path = staticmethod(RecommenderClient.parse_common_folder_path) + + common_organization_path = staticmethod(RecommenderClient.common_organization_path) + parse_common_organization_path = staticmethod( + RecommenderClient.parse_common_organization_path + ) + + common_project_path = staticmethod(RecommenderClient.common_project_path) + parse_common_project_path = staticmethod( + RecommenderClient.parse_common_project_path + ) + + common_location_path = staticmethod(RecommenderClient.common_location_path) + parse_common_location_path = staticmethod( + RecommenderClient.parse_common_location_path + ) + + from_service_account_file = RecommenderClient.from_service_account_file + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RecommenderTransport: + """Return the transport used by the client instance. + + Returns: + RecommenderTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(RecommenderClient).get_transport_class, type(RecommenderClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, RecommenderTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the recommender client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RecommenderTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + 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. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = RecommenderClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_insights( + self, + request: recommender_service.ListInsightsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInsightsAsyncPager: + r"""Lists insights for a Cloud project. Requires the + recommender.*.list IAM permission for the specified insight + type. + + Args: + request (:class:`~.recommender_service.ListInsightsRequest`): + The request object. Request for the `ListInsights` + method. + parent (:class:`str`): + Required. The container resource on which to execute the + request. Acceptable formats: + + 1. + + "projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]", + + LOCATION here refers to GCP Locations: + https://cloud.google.com/about/locations/ + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListInsightsAsyncPager: + Response to the ``ListInsights`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.ListInsightsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_insights, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListInsightsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_insight( + self, + request: recommender_service.GetInsightRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> insight.Insight: + r"""Gets the requested insight. Requires the recommender.*.get IAM + permission for the specified insight type. + + Args: + request (:class:`~.recommender_service.GetInsightRequest`): + The request object. Request to the `GetInsight` method. + name (:class:`str`): + Required. Name of the insight. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.insight.Insight: + An insight along with the information + used to derive the insight. The insight + may have associated recomendations as + well. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.GetInsightRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_insight, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def mark_insight_accepted( + self, + request: recommender_service.MarkInsightAcceptedRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkInsightAcceptedRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> insight.Insight: + r"""Marks the Insight State as Accepted. Users can use this method + to indicate to the Recommender API that they have applied some + action based on the insight. This stops the insight content from + being updated. + + MarkInsightAccepted can be applied to insights in ACTIVE state. + Requires the recommender.*.update IAM permission for the + specified insight. + + Args: + request (:class:`~.recommender_service.MarkInsightAcceptedRequest`): + The request object. Request for the + `MarkInsightAccepted` method. + name (:class:`str`): + Required. Name of the insight. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkInsightAcceptedRequest.StateMetadataEntry]`): + Optional. State properties user wish to include with + this state. Full replace of the current state_metadata. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the Insight. + Provides optimistic locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.insight.Insight: + An insight along with the information + used to derive the insight. The insight + may have associated recomendations as + well. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.MarkInsightAcceptedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.mark_insight_accepted, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_recommendations( + self, + request: recommender_service.ListRecommendationsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListRecommendationsAsyncPager: + r"""Lists recommendations for a Cloud project. Requires the + recommender.*.list IAM permission for the specified recommender. + + Args: + request (:class:`~.recommender_service.ListRecommendationsRequest`): + The request object. Request for the + `ListRecommendations` method. + parent (:class:`str`): + Required. The container resource on which to execute the + request. Acceptable formats: + + 1. + + "projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]", + + LOCATION here refers to GCP Locations: + https://cloud.google.com/about/locations/ + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Filter expression to restrict the recommendations + returned. Supported filter fields: state_info.state Eg: + \`state_info.state:"DISMISSED" or + state_info.state:"FAILED". + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListRecommendationsAsyncPager: + Response to the ``ListRecommendations`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.ListRecommendationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_recommendations, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListRecommendationsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_recommendation( + self, + request: recommender_service.GetRecommendationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Gets the requested recommendation. Requires the + recommender.*.get IAM permission for the specified recommender. + + Args: + request (:class:`~.recommender_service.GetRecommendationRequest`): + The request object. Request to the `GetRecommendation` + method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.GetRecommendationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_recommendation, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def mark_recommendation_claimed( + self, + request: recommender_service.MarkRecommendationClaimedRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkRecommendationClaimedRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Marks the Recommendation State as Claimed. Users can use this + method to indicate to the Recommender API that they are starting + to apply the recommendation themselves. This stops the + recommendation content from being updated. Associated insights + are frozen and placed in the ACCEPTED state. + + MarkRecommendationClaimed can be applied to recommendations in + CLAIMED, SUCCEEDED, FAILED, or ACTIVE state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Args: + request (:class:`~.recommender_service.MarkRecommendationClaimedRequest`): + The request object. Request for the + `MarkRecommendationClaimed` Method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkRecommendationClaimedRequest.StateMetadataEntry]`): + State properties to include with this state. Overwrites + any existing ``state_metadata``. Keys must match the + regex ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match + the regex ``/^[a-zA-Z0-9_./-]{0,255}$/``. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the + Recommendation. Provides optimistic + locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.MarkRecommendationClaimedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.mark_recommendation_claimed, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def mark_recommendation_succeeded( + self, + request: recommender_service.MarkRecommendationSucceededRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkRecommendationSucceededRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Marks the Recommendation State as Succeeded. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation was successful. + This stops the recommendation content from being updated. + Associated insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationSucceeded can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Args: + request (:class:`~.recommender_service.MarkRecommendationSucceededRequest`): + The request object. Request for the + `MarkRecommendationSucceeded` Method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkRecommendationSucceededRequest.StateMetadataEntry]`): + State properties to include with this state. Overwrites + any existing ``state_metadata``. Keys must match the + regex ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match + the regex ``/^[a-zA-Z0-9_./-]{0,255}$/``. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the + Recommendation. Provides optimistic + locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.MarkRecommendationSucceededRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.mark_recommendation_succeeded, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def mark_recommendation_failed( + self, + request: recommender_service.MarkRecommendationFailedRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkRecommendationFailedRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Marks the Recommendation State as Failed. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation failed. This + stops the recommendation content from being updated. Associated + insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationFailed can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Args: + request (:class:`~.recommender_service.MarkRecommendationFailedRequest`): + The request object. Request for the + `MarkRecommendationFailed` Method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkRecommendationFailedRequest.StateMetadataEntry]`): + State properties to include with this state. Overwrites + any existing ``state_metadata``. Keys must match the + regex ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match + the regex ``/^[a-zA-Z0-9_./-]{0,255}$/``. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the + Recommendation. Provides optimistic + locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.MarkRecommendationFailedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.mark_recommendation_failed, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommender", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("RecommenderAsyncClient",) diff --git a/google/cloud/recommender_v1/services/recommender/client.py b/google/cloud/recommender_v1/services/recommender/client.py new file mode 100644 index 0000000..fb75aa8 --- /dev/null +++ b/google/cloud/recommender_v1/services/recommender/client.py @@ -0,0 +1,1186 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import 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 + +from google.cloud.recommender_v1.services.recommender import pagers +from google.cloud.recommender_v1.types import insight +from google.cloud.recommender_v1.types import recommendation +from google.cloud.recommender_v1.types import recommender_service +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import RecommenderTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RecommenderGrpcTransport +from .transports.grpc_asyncio import RecommenderGrpcAsyncIOTransport + + +class RecommenderClientMeta(type): + """Metaclass for the Recommender client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[RecommenderTransport]] + _transport_registry["grpc"] = RecommenderGrpcTransport + _transport_registry["grpc_asyncio"] = RecommenderGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[RecommenderTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RecommenderClient(metaclass=RecommenderClientMeta): + """Provides insights and recommendations for cloud customers for + various categories like performance optimization, cost savings, + reliability, feature discovery, etc. Insights and + recommendations are generated automatically based on analysis of + user resources, configuration and monitoring metrics. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "recommender.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RecommenderTransport: + """Return the transport used by the client instance. + + Returns: + RecommenderTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def insight_path( + project: str, location: str, insight_type: str, insight: str, + ) -> str: + """Return a fully-qualified insight string.""" + return "projects/{project}/locations/{location}/insightTypes/{insight_type}/insights/{insight}".format( + project=project, + location=location, + insight_type=insight_type, + insight=insight, + ) + + @staticmethod + def parse_insight_path(path: str) -> Dict[str, str]: + """Parse a insight path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/insightTypes/(?P.+?)/insights/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def insight_type_path(project: str, location: str, insight_type: str,) -> str: + """Return a fully-qualified insight_type string.""" + return "projects/{project}/locations/{location}/insightTypes/{insight_type}".format( + project=project, location=location, insight_type=insight_type, + ) + + @staticmethod + def parse_insight_type_path(path: str) -> Dict[str, str]: + """Parse a insight_type path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/insightTypes/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def recommendation_path( + project: str, location: str, recommender: str, recommendation: str, + ) -> str: + """Return a fully-qualified recommendation string.""" + return "projects/{project}/locations/{location}/recommenders/{recommender}/recommendations/{recommendation}".format( + project=project, + location=location, + recommender=recommender, + recommendation=recommendation, + ) + + @staticmethod + def parse_recommendation_path(path: str) -> Dict[str, str]: + """Parse a recommendation path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/recommenders/(?P.+?)/recommendations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def recommender_path(project: str, location: str, recommender: str,) -> str: + """Return a fully-qualified recommender string.""" + return "projects/{project}/locations/{location}/recommenders/{recommender}".format( + project=project, location=location, recommender=recommender, + ) + + @staticmethod + def parse_recommender_path(path: str) -> Dict[str, str]: + """Parse a recommender path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/recommenders/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + 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: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + 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: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + 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: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + 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: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + 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 {} + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, RecommenderTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the recommender client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RecommenderTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + 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. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RecommenderTransport): + # transport is a RecommenderTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_insights( + self, + request: recommender_service.ListInsightsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInsightsPager: + r"""Lists insights for a Cloud project. Requires the + recommender.*.list IAM permission for the specified insight + type. + + Args: + request (:class:`~.recommender_service.ListInsightsRequest`): + The request object. Request for the `ListInsights` + method. + parent (:class:`str`): + Required. The container resource on which to execute the + request. Acceptable formats: + + 1. + + "projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]", + + LOCATION here refers to GCP Locations: + https://cloud.google.com/about/locations/ + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListInsightsPager: + Response to the ``ListInsights`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.ListInsightsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommender_service.ListInsightsRequest): + request = recommender_service.ListInsightsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_insights] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListInsightsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_insight( + self, + request: recommender_service.GetInsightRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> insight.Insight: + r"""Gets the requested insight. Requires the recommender.*.get IAM + permission for the specified insight type. + + Args: + request (:class:`~.recommender_service.GetInsightRequest`): + The request object. Request to the `GetInsight` method. + name (:class:`str`): + Required. Name of the insight. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.insight.Insight: + An insight along with the information + used to derive the insight. The insight + may have associated recomendations as + well. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.GetInsightRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommender_service.GetInsightRequest): + request = recommender_service.GetInsightRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_insight] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def mark_insight_accepted( + self, + request: recommender_service.MarkInsightAcceptedRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkInsightAcceptedRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> insight.Insight: + r"""Marks the Insight State as Accepted. Users can use this method + to indicate to the Recommender API that they have applied some + action based on the insight. This stops the insight content from + being updated. + + MarkInsightAccepted can be applied to insights in ACTIVE state. + Requires the recommender.*.update IAM permission for the + specified insight. + + Args: + request (:class:`~.recommender_service.MarkInsightAcceptedRequest`): + The request object. Request for the + `MarkInsightAccepted` method. + name (:class:`str`): + Required. Name of the insight. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkInsightAcceptedRequest.StateMetadataEntry]`): + Optional. State properties user wish to include with + this state. Full replace of the current state_metadata. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the Insight. + Provides optimistic locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.insight.Insight: + An insight along with the information + used to derive the insight. The insight + may have associated recomendations as + well. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.MarkInsightAcceptedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommender_service.MarkInsightAcceptedRequest): + request = recommender_service.MarkInsightAcceptedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.mark_insight_accepted] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_recommendations( + self, + request: recommender_service.ListRecommendationsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListRecommendationsPager: + r"""Lists recommendations for a Cloud project. Requires the + recommender.*.list IAM permission for the specified recommender. + + Args: + request (:class:`~.recommender_service.ListRecommendationsRequest`): + The request object. Request for the + `ListRecommendations` method. + parent (:class:`str`): + Required. The container resource on which to execute the + request. Acceptable formats: + + 1. + + "projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]", + + LOCATION here refers to GCP Locations: + https://cloud.google.com/about/locations/ + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Filter expression to restrict the recommendations + returned. Supported filter fields: state_info.state Eg: + \`state_info.state:"DISMISSED" or + state_info.state:"FAILED". + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListRecommendationsPager: + Response to the ``ListRecommendations`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.ListRecommendationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommender_service.ListRecommendationsRequest): + request = recommender_service.ListRecommendationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_recommendations] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRecommendationsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_recommendation( + self, + request: recommender_service.GetRecommendationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Gets the requested recommendation. Requires the + recommender.*.get IAM permission for the specified recommender. + + Args: + request (:class:`~.recommender_service.GetRecommendationRequest`): + The request object. Request to the `GetRecommendation` + method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.GetRecommendationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommender_service.GetRecommendationRequest): + request = recommender_service.GetRecommendationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_recommendation] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def mark_recommendation_claimed( + self, + request: recommender_service.MarkRecommendationClaimedRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkRecommendationClaimedRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Marks the Recommendation State as Claimed. Users can use this + method to indicate to the Recommender API that they are starting + to apply the recommendation themselves. This stops the + recommendation content from being updated. Associated insights + are frozen and placed in the ACCEPTED state. + + MarkRecommendationClaimed can be applied to recommendations in + CLAIMED, SUCCEEDED, FAILED, or ACTIVE state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Args: + request (:class:`~.recommender_service.MarkRecommendationClaimedRequest`): + The request object. Request for the + `MarkRecommendationClaimed` Method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkRecommendationClaimedRequest.StateMetadataEntry]`): + State properties to include with this state. Overwrites + any existing ``state_metadata``. Keys must match the + regex ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match + the regex ``/^[a-zA-Z0-9_./-]{0,255}$/``. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the + Recommendation. Provides optimistic + locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.MarkRecommendationClaimedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, recommender_service.MarkRecommendationClaimedRequest + ): + request = recommender_service.MarkRecommendationClaimedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.mark_recommendation_claimed + ] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def mark_recommendation_succeeded( + self, + request: recommender_service.MarkRecommendationSucceededRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkRecommendationSucceededRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Marks the Recommendation State as Succeeded. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation was successful. + This stops the recommendation content from being updated. + Associated insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationSucceeded can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Args: + request (:class:`~.recommender_service.MarkRecommendationSucceededRequest`): + The request object. Request for the + `MarkRecommendationSucceeded` Method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkRecommendationSucceededRequest.StateMetadataEntry]`): + State properties to include with this state. Overwrites + any existing ``state_metadata``. Keys must match the + regex ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match + the regex ``/^[a-zA-Z0-9_./-]{0,255}$/``. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the + Recommendation. Provides optimistic + locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.MarkRecommendationSucceededRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, recommender_service.MarkRecommendationSucceededRequest + ): + request = recommender_service.MarkRecommendationSucceededRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.mark_recommendation_succeeded + ] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def mark_recommendation_failed( + self, + request: recommender_service.MarkRecommendationFailedRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkRecommendationFailedRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Marks the Recommendation State as Failed. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation failed. This + stops the recommendation content from being updated. Associated + insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationFailed can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Args: + request (:class:`~.recommender_service.MarkRecommendationFailedRequest`): + The request object. Request for the + `MarkRecommendationFailed` Method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkRecommendationFailedRequest.StateMetadataEntry]`): + State properties to include with this state. Overwrites + any existing ``state_metadata``. Keys must match the + regex ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match + the regex ``/^[a-zA-Z0-9_./-]{0,255}$/``. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the + Recommendation. Provides optimistic + locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.MarkRecommendationFailedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommender_service.MarkRecommendationFailedRequest): + request = recommender_service.MarkRecommendationFailedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.mark_recommendation_failed + ] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommender", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("RecommenderClient",) diff --git a/google/cloud/recommender_v1/services/recommender/pagers.py b/google/cloud/recommender_v1/services/recommender/pagers.py new file mode 100644 index 0000000..86f9944 --- /dev/null +++ b/google/cloud/recommender_v1/services/recommender/pagers.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.recommender_v1.types import insight +from google.cloud.recommender_v1.types import recommendation +from google.cloud.recommender_v1.types import recommender_service + + +class ListInsightsPager: + """A pager for iterating through ``list_insights`` requests. + + This class thinly wraps an initial + :class:`~.recommender_service.ListInsightsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``insights`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInsights`` requests and continue to iterate + through the ``insights`` field on the + corresponding responses. + + All the usual :class:`~.recommender_service.ListInsightsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., recommender_service.ListInsightsResponse], + request: recommender_service.ListInsightsRequest, + response: recommender_service.ListInsightsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.recommender_service.ListInsightsRequest`): + The initial request object. + response (:class:`~.recommender_service.ListInsightsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = recommender_service.ListInsightsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[recommender_service.ListInsightsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[insight.Insight]: + for page in self.pages: + yield from page.insights + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListInsightsAsyncPager: + """A pager for iterating through ``list_insights`` requests. + + This class thinly wraps an initial + :class:`~.recommender_service.ListInsightsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``insights`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInsights`` requests and continue to iterate + through the ``insights`` field on the + corresponding responses. + + All the usual :class:`~.recommender_service.ListInsightsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[recommender_service.ListInsightsResponse]], + request: recommender_service.ListInsightsRequest, + response: recommender_service.ListInsightsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.recommender_service.ListInsightsRequest`): + The initial request object. + response (:class:`~.recommender_service.ListInsightsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = recommender_service.ListInsightsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[recommender_service.ListInsightsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[insight.Insight]: + async def async_generator(): + async for page in self.pages: + for response in page.insights: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRecommendationsPager: + """A pager for iterating through ``list_recommendations`` requests. + + This class thinly wraps an initial + :class:`~.recommender_service.ListRecommendationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``recommendations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRecommendations`` requests and continue to iterate + through the ``recommendations`` field on the + corresponding responses. + + All the usual :class:`~.recommender_service.ListRecommendationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., recommender_service.ListRecommendationsResponse], + request: recommender_service.ListRecommendationsRequest, + response: recommender_service.ListRecommendationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.recommender_service.ListRecommendationsRequest`): + The initial request object. + response (:class:`~.recommender_service.ListRecommendationsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = recommender_service.ListRecommendationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[recommender_service.ListRecommendationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[recommendation.Recommendation]: + for page in self.pages: + yield from page.recommendations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRecommendationsAsyncPager: + """A pager for iterating through ``list_recommendations`` requests. + + This class thinly wraps an initial + :class:`~.recommender_service.ListRecommendationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``recommendations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRecommendations`` requests and continue to iterate + through the ``recommendations`` field on the + corresponding responses. + + All the usual :class:`~.recommender_service.ListRecommendationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[recommender_service.ListRecommendationsResponse] + ], + request: recommender_service.ListRecommendationsRequest, + response: recommender_service.ListRecommendationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.recommender_service.ListRecommendationsRequest`): + The initial request object. + response (:class:`~.recommender_service.ListRecommendationsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = recommender_service.ListRecommendationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[recommender_service.ListRecommendationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[recommendation.Recommendation]: + async def async_generator(): + async for page in self.pages: + for response in page.recommendations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/recommender_v1/services/recommender/transports/__init__.py b/google/cloud/recommender_v1/services/recommender/transports/__init__.py new file mode 100644 index 0000000..d099ae4 --- /dev/null +++ b/google/cloud/recommender_v1/services/recommender/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import RecommenderTransport +from .grpc import RecommenderGrpcTransport +from .grpc_asyncio import RecommenderGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RecommenderTransport]] +_transport_registry["grpc"] = RecommenderGrpcTransport +_transport_registry["grpc_asyncio"] = RecommenderGrpcAsyncIOTransport + + +__all__ = ( + "RecommenderTransport", + "RecommenderGrpcTransport", + "RecommenderGrpcAsyncIOTransport", +) diff --git a/google/cloud/recommender_v1/services/recommender/transports/base.py b/google/cloud/recommender_v1/services/recommender/transports/base.py new file mode 100644 index 0000000..a8a8541 --- /dev/null +++ b/google/cloud/recommender_v1/services/recommender/transports/base.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.recommender_v1.types import insight +from google.cloud.recommender_v1.types import recommendation +from google.cloud.recommender_v1.types import recommender_service + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommender", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class RecommenderTransport(abc.ABC): + """Abstract transport class for Recommender.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "recommender.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_insights: gapic_v1.method.wrap_method( + self.list_insights, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_insight: gapic_v1.method.wrap_method( + self.get_insight, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=client_info, + ), + self.mark_insight_accepted: gapic_v1.method.wrap_method( + self.mark_insight_accepted, + default_timeout=60.0, + client_info=client_info, + ), + self.list_recommendations: gapic_v1.method.wrap_method( + self.list_recommendations, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_recommendation: gapic_v1.method.wrap_method( + self.get_recommendation, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=client_info, + ), + self.mark_recommendation_claimed: gapic_v1.method.wrap_method( + self.mark_recommendation_claimed, + default_timeout=60.0, + client_info=client_info, + ), + self.mark_recommendation_succeeded: gapic_v1.method.wrap_method( + self.mark_recommendation_succeeded, + default_timeout=60.0, + client_info=client_info, + ), + self.mark_recommendation_failed: gapic_v1.method.wrap_method( + self.mark_recommendation_failed, + default_timeout=60.0, + client_info=client_info, + ), + } + + @property + def list_insights( + self, + ) -> typing.Callable[ + [recommender_service.ListInsightsRequest], + typing.Union[ + recommender_service.ListInsightsResponse, + typing.Awaitable[recommender_service.ListInsightsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_insight( + self, + ) -> typing.Callable[ + [recommender_service.GetInsightRequest], + typing.Union[insight.Insight, typing.Awaitable[insight.Insight]], + ]: + raise NotImplementedError() + + @property + def mark_insight_accepted( + self, + ) -> typing.Callable[ + [recommender_service.MarkInsightAcceptedRequest], + typing.Union[insight.Insight, typing.Awaitable[insight.Insight]], + ]: + raise NotImplementedError() + + @property + def list_recommendations( + self, + ) -> typing.Callable[ + [recommender_service.ListRecommendationsRequest], + typing.Union[ + recommender_service.ListRecommendationsResponse, + typing.Awaitable[recommender_service.ListRecommendationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_recommendation( + self, + ) -> typing.Callable[ + [recommender_service.GetRecommendationRequest], + typing.Union[ + recommendation.Recommendation, + typing.Awaitable[recommendation.Recommendation], + ], + ]: + raise NotImplementedError() + + @property + def mark_recommendation_claimed( + self, + ) -> typing.Callable[ + [recommender_service.MarkRecommendationClaimedRequest], + typing.Union[ + recommendation.Recommendation, + typing.Awaitable[recommendation.Recommendation], + ], + ]: + raise NotImplementedError() + + @property + def mark_recommendation_succeeded( + self, + ) -> typing.Callable[ + [recommender_service.MarkRecommendationSucceededRequest], + typing.Union[ + recommendation.Recommendation, + typing.Awaitable[recommendation.Recommendation], + ], + ]: + raise NotImplementedError() + + @property + def mark_recommendation_failed( + self, + ) -> typing.Callable[ + [recommender_service.MarkRecommendationFailedRequest], + typing.Union[ + recommendation.Recommendation, + typing.Awaitable[recommendation.Recommendation], + ], + ]: + raise NotImplementedError() + + +__all__ = ("RecommenderTransport",) diff --git a/google/cloud/recommender_v1/services/recommender/transports/grpc.py b/google/cloud/recommender_v1/services/recommender/transports/grpc.py new file mode 100644 index 0000000..90c97a5 --- /dev/null +++ b/google/cloud/recommender_v1/services/recommender/transports/grpc.py @@ -0,0 +1,508 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.recommender_v1.types import insight +from google.cloud.recommender_v1.types import recommendation +from google.cloud.recommender_v1.types import recommender_service + +from .base import RecommenderTransport, DEFAULT_CLIENT_INFO + + +class RecommenderGrpcTransport(RecommenderTransport): + """gRPC backend transport for Recommender. + + Provides insights and recommendations for cloud customers for + various categories like performance optimization, cost savings, + reliability, feature discovery, etc. Insights and + recommendations are generated automatically based on analysis of + user resources, configuration and monitoring metrics. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + 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 = "recommender.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "recommender.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_insights( + self, + ) -> Callable[ + [recommender_service.ListInsightsRequest], + recommender_service.ListInsightsResponse, + ]: + r"""Return a callable for the list insights method over gRPC. + + Lists insights for a Cloud project. Requires the + recommender.*.list IAM permission for the specified insight + type. + + Returns: + Callable[[~.ListInsightsRequest], + ~.ListInsightsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_insights" not in self._stubs: + self._stubs["list_insights"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/ListInsights", + request_serializer=recommender_service.ListInsightsRequest.serialize, + response_deserializer=recommender_service.ListInsightsResponse.deserialize, + ) + return self._stubs["list_insights"] + + @property + def get_insight( + self, + ) -> Callable[[recommender_service.GetInsightRequest], insight.Insight]: + r"""Return a callable for the get insight method over gRPC. + + Gets the requested insight. Requires the recommender.*.get IAM + permission for the specified insight type. + + Returns: + Callable[[~.GetInsightRequest], + ~.Insight]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_insight" not in self._stubs: + self._stubs["get_insight"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/GetInsight", + request_serializer=recommender_service.GetInsightRequest.serialize, + response_deserializer=insight.Insight.deserialize, + ) + return self._stubs["get_insight"] + + @property + def mark_insight_accepted( + self, + ) -> Callable[[recommender_service.MarkInsightAcceptedRequest], insight.Insight]: + r"""Return a callable for the mark insight accepted method over gRPC. + + Marks the Insight State as Accepted. Users can use this method + to indicate to the Recommender API that they have applied some + action based on the insight. This stops the insight content from + being updated. + + MarkInsightAccepted can be applied to insights in ACTIVE state. + Requires the recommender.*.update IAM permission for the + specified insight. + + Returns: + Callable[[~.MarkInsightAcceptedRequest], + ~.Insight]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_insight_accepted" not in self._stubs: + self._stubs["mark_insight_accepted"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/MarkInsightAccepted", + request_serializer=recommender_service.MarkInsightAcceptedRequest.serialize, + response_deserializer=insight.Insight.deserialize, + ) + return self._stubs["mark_insight_accepted"] + + @property + def list_recommendations( + self, + ) -> Callable[ + [recommender_service.ListRecommendationsRequest], + recommender_service.ListRecommendationsResponse, + ]: + r"""Return a callable for the list recommendations method over gRPC. + + Lists recommendations for a Cloud project. Requires the + recommender.*.list IAM permission for the specified recommender. + + Returns: + Callable[[~.ListRecommendationsRequest], + ~.ListRecommendationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_recommendations" not in self._stubs: + self._stubs["list_recommendations"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/ListRecommendations", + request_serializer=recommender_service.ListRecommendationsRequest.serialize, + response_deserializer=recommender_service.ListRecommendationsResponse.deserialize, + ) + return self._stubs["list_recommendations"] + + @property + def get_recommendation( + self, + ) -> Callable[ + [recommender_service.GetRecommendationRequest], recommendation.Recommendation + ]: + r"""Return a callable for the get recommendation method over gRPC. + + Gets the requested recommendation. Requires the + recommender.*.get IAM permission for the specified recommender. + + Returns: + Callable[[~.GetRecommendationRequest], + ~.Recommendation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_recommendation" not in self._stubs: + self._stubs["get_recommendation"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/GetRecommendation", + request_serializer=recommender_service.GetRecommendationRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["get_recommendation"] + + @property + def mark_recommendation_claimed( + self, + ) -> Callable[ + [recommender_service.MarkRecommendationClaimedRequest], + recommendation.Recommendation, + ]: + r"""Return a callable for the mark recommendation claimed method over gRPC. + + Marks the Recommendation State as Claimed. Users can use this + method to indicate to the Recommender API that they are starting + to apply the recommendation themselves. This stops the + recommendation content from being updated. Associated insights + are frozen and placed in the ACCEPTED state. + + MarkRecommendationClaimed can be applied to recommendations in + CLAIMED, SUCCEEDED, FAILED, or ACTIVE state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Returns: + Callable[[~.MarkRecommendationClaimedRequest], + ~.Recommendation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_recommendation_claimed" not in self._stubs: + self._stubs["mark_recommendation_claimed"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/MarkRecommendationClaimed", + request_serializer=recommender_service.MarkRecommendationClaimedRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["mark_recommendation_claimed"] + + @property + def mark_recommendation_succeeded( + self, + ) -> Callable[ + [recommender_service.MarkRecommendationSucceededRequest], + recommendation.Recommendation, + ]: + r"""Return a callable for the mark recommendation succeeded method over gRPC. + + Marks the Recommendation State as Succeeded. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation was successful. + This stops the recommendation content from being updated. + Associated insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationSucceeded can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Returns: + Callable[[~.MarkRecommendationSucceededRequest], + ~.Recommendation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_recommendation_succeeded" not in self._stubs: + self._stubs[ + "mark_recommendation_succeeded" + ] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/MarkRecommendationSucceeded", + request_serializer=recommender_service.MarkRecommendationSucceededRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["mark_recommendation_succeeded"] + + @property + def mark_recommendation_failed( + self, + ) -> Callable[ + [recommender_service.MarkRecommendationFailedRequest], + recommendation.Recommendation, + ]: + r"""Return a callable for the mark recommendation failed method over gRPC. + + Marks the Recommendation State as Failed. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation failed. This + stops the recommendation content from being updated. Associated + insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationFailed can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Returns: + Callable[[~.MarkRecommendationFailedRequest], + ~.Recommendation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_recommendation_failed" not in self._stubs: + self._stubs["mark_recommendation_failed"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/MarkRecommendationFailed", + request_serializer=recommender_service.MarkRecommendationFailedRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["mark_recommendation_failed"] + + +__all__ = ("RecommenderGrpcTransport",) diff --git a/google/cloud/recommender_v1/services/recommender/transports/grpc_asyncio.py b/google/cloud/recommender_v1/services/recommender/transports/grpc_asyncio.py new file mode 100644 index 0000000..7f2fbff --- /dev/null +++ b/google/cloud/recommender_v1/services/recommender/transports/grpc_asyncio.py @@ -0,0 +1,515 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.recommender_v1.types import insight +from google.cloud.recommender_v1.types import recommendation +from google.cloud.recommender_v1.types import recommender_service + +from .base import RecommenderTransport, DEFAULT_CLIENT_INFO +from .grpc import RecommenderGrpcTransport + + +class RecommenderGrpcAsyncIOTransport(RecommenderTransport): + """gRPC AsyncIO backend transport for Recommender. + + Provides insights and recommendations for cloud customers for + various categories like performance optimization, cost savings, + reliability, feature discovery, etc. Insights and + recommendations are generated automatically based on analysis of + user resources, configuration and monitoring metrics. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "recommender.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "recommender.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_insights( + self, + ) -> Callable[ + [recommender_service.ListInsightsRequest], + Awaitable[recommender_service.ListInsightsResponse], + ]: + r"""Return a callable for the list insights method over gRPC. + + Lists insights for a Cloud project. Requires the + recommender.*.list IAM permission for the specified insight + type. + + Returns: + Callable[[~.ListInsightsRequest], + Awaitable[~.ListInsightsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_insights" not in self._stubs: + self._stubs["list_insights"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/ListInsights", + request_serializer=recommender_service.ListInsightsRequest.serialize, + response_deserializer=recommender_service.ListInsightsResponse.deserialize, + ) + return self._stubs["list_insights"] + + @property + def get_insight( + self, + ) -> Callable[[recommender_service.GetInsightRequest], Awaitable[insight.Insight]]: + r"""Return a callable for the get insight method over gRPC. + + Gets the requested insight. Requires the recommender.*.get IAM + permission for the specified insight type. + + Returns: + Callable[[~.GetInsightRequest], + Awaitable[~.Insight]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_insight" not in self._stubs: + self._stubs["get_insight"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/GetInsight", + request_serializer=recommender_service.GetInsightRequest.serialize, + response_deserializer=insight.Insight.deserialize, + ) + return self._stubs["get_insight"] + + @property + def mark_insight_accepted( + self, + ) -> Callable[ + [recommender_service.MarkInsightAcceptedRequest], Awaitable[insight.Insight] + ]: + r"""Return a callable for the mark insight accepted method over gRPC. + + Marks the Insight State as Accepted. Users can use this method + to indicate to the Recommender API that they have applied some + action based on the insight. This stops the insight content from + being updated. + + MarkInsightAccepted can be applied to insights in ACTIVE state. + Requires the recommender.*.update IAM permission for the + specified insight. + + Returns: + Callable[[~.MarkInsightAcceptedRequest], + Awaitable[~.Insight]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_insight_accepted" not in self._stubs: + self._stubs["mark_insight_accepted"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/MarkInsightAccepted", + request_serializer=recommender_service.MarkInsightAcceptedRequest.serialize, + response_deserializer=insight.Insight.deserialize, + ) + return self._stubs["mark_insight_accepted"] + + @property + def list_recommendations( + self, + ) -> Callable[ + [recommender_service.ListRecommendationsRequest], + Awaitable[recommender_service.ListRecommendationsResponse], + ]: + r"""Return a callable for the list recommendations method over gRPC. + + Lists recommendations for a Cloud project. Requires the + recommender.*.list IAM permission for the specified recommender. + + Returns: + Callable[[~.ListRecommendationsRequest], + Awaitable[~.ListRecommendationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_recommendations" not in self._stubs: + self._stubs["list_recommendations"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/ListRecommendations", + request_serializer=recommender_service.ListRecommendationsRequest.serialize, + response_deserializer=recommender_service.ListRecommendationsResponse.deserialize, + ) + return self._stubs["list_recommendations"] + + @property + def get_recommendation( + self, + ) -> Callable[ + [recommender_service.GetRecommendationRequest], + Awaitable[recommendation.Recommendation], + ]: + r"""Return a callable for the get recommendation method over gRPC. + + Gets the requested recommendation. Requires the + recommender.*.get IAM permission for the specified recommender. + + Returns: + Callable[[~.GetRecommendationRequest], + Awaitable[~.Recommendation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_recommendation" not in self._stubs: + self._stubs["get_recommendation"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/GetRecommendation", + request_serializer=recommender_service.GetRecommendationRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["get_recommendation"] + + @property + def mark_recommendation_claimed( + self, + ) -> Callable[ + [recommender_service.MarkRecommendationClaimedRequest], + Awaitable[recommendation.Recommendation], + ]: + r"""Return a callable for the mark recommendation claimed method over gRPC. + + Marks the Recommendation State as Claimed. Users can use this + method to indicate to the Recommender API that they are starting + to apply the recommendation themselves. This stops the + recommendation content from being updated. Associated insights + are frozen and placed in the ACCEPTED state. + + MarkRecommendationClaimed can be applied to recommendations in + CLAIMED, SUCCEEDED, FAILED, or ACTIVE state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Returns: + Callable[[~.MarkRecommendationClaimedRequest], + Awaitable[~.Recommendation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_recommendation_claimed" not in self._stubs: + self._stubs["mark_recommendation_claimed"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/MarkRecommendationClaimed", + request_serializer=recommender_service.MarkRecommendationClaimedRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["mark_recommendation_claimed"] + + @property + def mark_recommendation_succeeded( + self, + ) -> Callable[ + [recommender_service.MarkRecommendationSucceededRequest], + Awaitable[recommendation.Recommendation], + ]: + r"""Return a callable for the mark recommendation succeeded method over gRPC. + + Marks the Recommendation State as Succeeded. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation was successful. + This stops the recommendation content from being updated. + Associated insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationSucceeded can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Returns: + Callable[[~.MarkRecommendationSucceededRequest], + Awaitable[~.Recommendation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_recommendation_succeeded" not in self._stubs: + self._stubs[ + "mark_recommendation_succeeded" + ] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/MarkRecommendationSucceeded", + request_serializer=recommender_service.MarkRecommendationSucceededRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["mark_recommendation_succeeded"] + + @property + def mark_recommendation_failed( + self, + ) -> Callable[ + [recommender_service.MarkRecommendationFailedRequest], + Awaitable[recommendation.Recommendation], + ]: + r"""Return a callable for the mark recommendation failed method over gRPC. + + Marks the Recommendation State as Failed. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation failed. This + stops the recommendation content from being updated. Associated + insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationFailed can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Returns: + Callable[[~.MarkRecommendationFailedRequest], + Awaitable[~.Recommendation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_recommendation_failed" not in self._stubs: + self._stubs["mark_recommendation_failed"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1.Recommender/MarkRecommendationFailed", + request_serializer=recommender_service.MarkRecommendationFailedRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["mark_recommendation_failed"] + + +__all__ = ("RecommenderGrpcAsyncIOTransport",) diff --git a/google/cloud/recommender_v1/types.py b/google/cloud/recommender_v1/types.py deleted file mode 100644 index a65fb5c..0000000 --- a/google/cloud/recommender_v1/types.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.recommender_v1.proto import insight_pb2 -from google.cloud.recommender_v1.proto import recommendation_pb2 -from google.cloud.recommender_v1.proto import recommender_service_pb2 -from google.protobuf import duration_pb2 -from google.protobuf import struct_pb2 -from google.protobuf import timestamp_pb2 -from google.type import money_pb2 - - -_shared_modules = [ - duration_pb2, - struct_pb2, - timestamp_pb2, - money_pb2, -] - -_local_modules = [ - insight_pb2, - recommendation_pb2, - recommender_service_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.recommender_v1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/recommender_v1/types/__init__.py b/google/cloud/recommender_v1/types/__init__.py new file mode 100644 index 0000000..04032ec --- /dev/null +++ b/google/cloud/recommender_v1/types/__init__.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .insight import ( + Insight, + InsightStateInfo, +) +from .recommendation import ( + Recommendation, + RecommendationContent, + OperationGroup, + Operation, + ValueMatcher, + CostProjection, + Impact, + RecommendationStateInfo, +) +from .recommender_service import ( + ListInsightsRequest, + ListInsightsResponse, + GetInsightRequest, + MarkInsightAcceptedRequest, + ListRecommendationsRequest, + ListRecommendationsResponse, + GetRecommendationRequest, + MarkRecommendationClaimedRequest, + MarkRecommendationSucceededRequest, + MarkRecommendationFailedRequest, +) + + +__all__ = ( + "Insight", + "InsightStateInfo", + "Recommendation", + "RecommendationContent", + "OperationGroup", + "Operation", + "ValueMatcher", + "CostProjection", + "Impact", + "RecommendationStateInfo", + "ListInsightsRequest", + "ListInsightsResponse", + "GetInsightRequest", + "MarkInsightAcceptedRequest", + "ListRecommendationsRequest", + "ListRecommendationsResponse", + "GetRecommendationRequest", + "MarkRecommendationClaimedRequest", + "MarkRecommendationSucceededRequest", + "MarkRecommendationFailedRequest", +) diff --git a/google/cloud/recommender_v1/types/insight.py b/google/cloud/recommender_v1/types/insight.py new file mode 100644 index 0000000..fb351cd --- /dev/null +++ b/google/cloud/recommender_v1/types/insight.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.recommender.v1", manifest={"Insight", "InsightStateInfo",}, +) + + +class Insight(proto.Message): + r"""An insight along with the information used to derive the + insight. The insight may have associated recomendations as well. + + Attributes: + name (str): + Name of the insight. + description (str): + Free-form human readable summary in English. + The maximum length is 500 characters. + target_resources (Sequence[str]): + Fully qualified resource names that this + insight is targeting. + insight_subtype (str): + Insight subtype. Insight content schema will + be stable for a given subtype. + content (~.struct.Struct): + A struct of custom fields to explain the + insight. Example: "grantedPermissionsCount": + "1000". + last_refresh_time (~.timestamp.Timestamp): + Timestamp of the latest data used to generate + the insight. + observation_period (~.duration.Duration): + Observation period that led to the insight. The source data + used to generate the insight ends at last_refresh_time and + begins at (last_refresh_time - observation_period). + state_info (~.insight.InsightStateInfo): + Information state and metadata. + category (~.insight.Insight.Category): + Category being targeted by the insight. + etag (str): + Fingerprint of the Insight. Provides + optimistic locking when updating states. + associated_recommendations (Sequence[~.insight.Insight.RecommendationReference]): + Recommendations derived from this insight. + """ + + class Category(proto.Enum): + r"""Insight category.""" + CATEGORY_UNSPECIFIED = 0 + COST = 1 + SECURITY = 2 + PERFORMANCE = 3 + MANAGEABILITY = 4 + + class RecommendationReference(proto.Message): + r"""Reference to an associated recommendation. + + Attributes: + recommendation (str): + Recommendation resource name, e.g. + projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/recommendations/[RECOMMENDATION_ID] + """ + + recommendation = proto.Field(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=1) + + description = proto.Field(proto.STRING, number=2) + + target_resources = proto.RepeatedField(proto.STRING, number=9) + + insight_subtype = proto.Field(proto.STRING, number=10) + + content = proto.Field(proto.MESSAGE, number=3, message=struct.Struct,) + + last_refresh_time = proto.Field( + proto.MESSAGE, number=4, message=timestamp.Timestamp, + ) + + observation_period = proto.Field( + proto.MESSAGE, number=5, message=duration.Duration, + ) + + state_info = proto.Field(proto.MESSAGE, number=6, message="InsightStateInfo",) + + category = proto.Field(proto.ENUM, number=7, enum=Category,) + + etag = proto.Field(proto.STRING, number=11) + + associated_recommendations = proto.RepeatedField( + proto.MESSAGE, number=8, message=RecommendationReference, + ) + + +class InsightStateInfo(proto.Message): + r"""Information related to insight state. + + Attributes: + state (~.insight.InsightStateInfo.State): + Insight state. + state_metadata (Sequence[~.insight.InsightStateInfo.StateMetadataEntry]): + A map of metadata for the state, provided by + user or automations systems. + """ + + class State(proto.Enum): + r"""Represents insight state.""" + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + ACCEPTED = 2 + DISMISSED = 3 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + state_metadata = proto.MapField(proto.STRING, proto.STRING, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/recommender_v1/types/recommendation.py b/google/cloud/recommender_v1/types/recommendation.py new file mode 100644 index 0000000..7becf01 --- /dev/null +++ b/google/cloud/recommender_v1/types/recommendation.py @@ -0,0 +1,353 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import duration_pb2 as gp_duration # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.type import money_pb2 as money # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.recommender.v1", + manifest={ + "Recommendation", + "RecommendationContent", + "OperationGroup", + "Operation", + "ValueMatcher", + "CostProjection", + "Impact", + "RecommendationStateInfo", + }, +) + + +class Recommendation(proto.Message): + r"""A recommendation along with a suggested action. E.g., a + rightsizing recommendation for an underutilized VM, IAM role + recommendations, etc + + Attributes: + name (str): + Name of recommendation. + description (str): + Free-form human readable summary in English. + The maximum length is 500 characters. + recommender_subtype (str): + Contains an identifier for a subtype of recommendations + produced for the same recommender. Subtype is a function of + content and impact, meaning a new subtype might be added + when significant changes to ``content`` or + ``primary_impact.category`` are introduced. See the + Recommenders section to see a list of subtypes for a given + Recommender. + + Examples: For recommender = "google.iam.policy.Recommender", + recommender_subtype can be one of + "REMOVE_ROLE"/"REPLACE_ROLE". + last_refresh_time (~.timestamp.Timestamp): + Last time this recommendation was refreshed + by the system that created it in the first + place. + primary_impact (~.recommendation.Impact): + The primary impact that this recommendation + can have while trying to optimize for one + category. + additional_impact (Sequence[~.recommendation.Impact]): + Optional set of additional impact that this + recommendation may have when trying to optimize + for the primary category. These may be positive + or negative. + content (~.recommendation.RecommendationContent): + Content of the recommendation describing + recommended changes to resources. + state_info (~.recommendation.RecommendationStateInfo): + Information for state. Contains state and + metadata. + etag (str): + Fingerprint of the Recommendation. Provides + optimistic locking when updating states. + associated_insights (Sequence[~.recommendation.Recommendation.InsightReference]): + Insights that led to this recommendation. + """ + + class InsightReference(proto.Message): + r"""Reference to an associated insight. + + Attributes: + insight (str): + Insight resource name, e.g. + projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]/insights/[INSIGHT_ID] + """ + + insight = proto.Field(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=1) + + description = proto.Field(proto.STRING, number=2) + + recommender_subtype = proto.Field(proto.STRING, number=12) + + last_refresh_time = proto.Field( + proto.MESSAGE, number=4, message=timestamp.Timestamp, + ) + + primary_impact = proto.Field(proto.MESSAGE, number=5, message="Impact",) + + additional_impact = proto.RepeatedField(proto.MESSAGE, number=6, message="Impact",) + + content = proto.Field(proto.MESSAGE, number=7, message="RecommendationContent",) + + state_info = proto.Field( + proto.MESSAGE, number=10, message="RecommendationStateInfo", + ) + + etag = proto.Field(proto.STRING, number=11) + + associated_insights = proto.RepeatedField( + proto.MESSAGE, number=14, message=InsightReference, + ) + + +class RecommendationContent(proto.Message): + r"""Contains what resources are changing and how they are + changing. + + Attributes: + operation_groups (Sequence[~.recommendation.OperationGroup]): + Operations to one or more Google Cloud + resources grouped in such a way that, all + operations within one group are expected to be + performed atomically and in an order. + """ + + operation_groups = proto.RepeatedField( + proto.MESSAGE, number=2, message="OperationGroup", + ) + + +class OperationGroup(proto.Message): + r"""Group of operations that need to be performed atomically. + + Attributes: + operations (Sequence[~.recommendation.Operation]): + List of operations across one or more + resources that belong to this group. Loosely + based on RFC6902 and should be performed in the + order they appear. + """ + + operations = proto.RepeatedField(proto.MESSAGE, number=1, message="Operation",) + + +class Operation(proto.Message): + r"""Contains an operation for a resource loosely based on the JSON-PATCH + format with support for: + + - Custom filters for describing partial array patch. + - Extended path values for describing nested arrays. + - Custom fields for describing the resource for which the operation + is being described. + - Allows extension to custom operations not natively supported by + RFC6902. See https://tools.ietf.org/html/rfc6902 for details on + the original RFC. + + Attributes: + action (str): + Type of this operation. Contains one of + 'and', 'remove', 'replace', 'move', 'copy', + 'test' and custom operations. This field is + case-insensitive and always populated. + resource_type (str): + Type of GCP resource being modified/tested. + This field is always populated. Example: + cloudresourcemanager.googleapis.com/Project, + compute.googleapis.com/Instance + resource (str): + Contains the fully qualified resource name. + This field is always populated. ex: + //cloudresourcemanager.googleapis.com/projects/foo. + path (str): + Path to the target field being operated on. + If the operation is at the resource level, then + path should be "/". This field is always + populated. + source_resource (str): + Can be set with action 'copy' to copy resource configuration + across different resources of the same type. Example: A + resource clone can be done via action = 'copy', path = "/", + from = "/", source_resource = and resource_name = . This + field is empty for all other values of ``action``. + source_path (str): + Can be set with action 'copy' or 'move' to indicate the + source field within resource or source_resource, ignored if + provided for other operation types. + value (~.struct.Value): + Value for the ``path`` field. Will be set for + actions:'add'/'replace'. Maybe set for action: 'test'. + Either this or ``value_matcher`` will be set for 'test' + operation. An exact match must be performed. + value_matcher (~.recommendation.ValueMatcher): + Can be set for action 'test' for advanced matching for the + value of 'path' field. Either this or ``value`` will be set + for 'test' operation. + path_filters (Sequence[~.recommendation.Operation.PathFiltersEntry]): + Set of filters to apply if ``path`` refers to array elements + or nested array elements in order to narrow down to a single + unique element that is being tested/modified. This is + intended to be an exact match per filter. To perform + advanced matching, use path_value_matchers. + + - Example: ``{ "/versions/*/name" : "it-123" + "/versions/*/targetSize/percent": 20 }`` + - Example: ``{ "/bindings/*/role": "roles/admin" + "/bindings/*/condition" : null }`` + - Example: ``{ "/bindings/*/role": "roles/admin" + "/bindings/*/members/*" : ["x@google.com", + "y@google.com"] }`` When both path_filters and + path_value_matchers are set, an implicit AND must be + performed. + path_value_matchers (Sequence[~.recommendation.Operation.PathValueMatchersEntry]): + Similar to path_filters, this contains set of filters to + apply if ``path`` field referes to array elements. This is + meant to support value matching beyond exact match. To + perform exact match, use path_filters. When both + path_filters and path_value_matchers are set, an implicit + AND must be performed. + """ + + action = proto.Field(proto.STRING, number=1) + + resource_type = proto.Field(proto.STRING, number=2) + + resource = proto.Field(proto.STRING, number=3) + + path = proto.Field(proto.STRING, number=4) + + source_resource = proto.Field(proto.STRING, number=5) + + source_path = proto.Field(proto.STRING, number=6) + + value = proto.Field( + proto.MESSAGE, number=7, oneof="path_value", message=struct.Value, + ) + + value_matcher = proto.Field( + proto.MESSAGE, number=10, oneof="path_value", message="ValueMatcher", + ) + + path_filters = proto.MapField( + proto.STRING, proto.MESSAGE, number=8, message=struct.Value, + ) + + path_value_matchers = proto.MapField( + proto.STRING, proto.MESSAGE, number=11, message="ValueMatcher", + ) + + +class ValueMatcher(proto.Message): + r"""Contains various matching options for values for a GCP + resource field. + + Attributes: + matches_pattern (str): + To be used for full regex matching. The + regular expression is using the Google RE2 + syntax + (https://github.com/google/re2/wiki/Syntax), so + to be used with RE2::FullMatch + """ + + matches_pattern = proto.Field(proto.STRING, number=1, oneof="match_variant") + + +class CostProjection(proto.Message): + r"""Contains metadata about how much money a recommendation can + save or incur. + + Attributes: + cost (~.money.Money): + An approximate projection on amount saved or + amount incurred. Negative cost units indicate + cost savings and positive cost units indicate + increase. See google.type.Money documentation + for positive/negative units. + duration (~.gp_duration.Duration): + Duration for which this cost applies. + """ + + cost = proto.Field(proto.MESSAGE, number=1, message=money.Money,) + + duration = proto.Field(proto.MESSAGE, number=2, message=gp_duration.Duration,) + + +class Impact(proto.Message): + r"""Contains the impact a recommendation can have for a given + category. + + Attributes: + category (~.recommendation.Impact.Category): + Category that is being targeted. + cost_projection (~.recommendation.CostProjection): + Use with CategoryType.COST + """ + + class Category(proto.Enum): + r"""The category of the impact.""" + CATEGORY_UNSPECIFIED = 0 + COST = 1 + SECURITY = 2 + PERFORMANCE = 3 + MANAGEABILITY = 4 + + category = proto.Field(proto.ENUM, number=1, enum=Category,) + + cost_projection = proto.Field( + proto.MESSAGE, number=100, oneof="projection", message="CostProjection", + ) + + +class RecommendationStateInfo(proto.Message): + r"""Information for state. Contains state and metadata. + + Attributes: + state (~.recommendation.RecommendationStateInfo.State): + The state of the recommendation, Eg ACTIVE, + SUCCEEDED, FAILED. + state_metadata (Sequence[~.recommendation.RecommendationStateInfo.StateMetadataEntry]): + A map of metadata for the state, provided by + user or automations systems. + """ + + class State(proto.Enum): + r"""Represents Recommendation State.""" + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + CLAIMED = 6 + SUCCEEDED = 3 + FAILED = 4 + DISMISSED = 5 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + state_metadata = proto.MapField(proto.STRING, proto.STRING, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/recommender_v1/types/recommender_service.py b/google/cloud/recommender_v1/types/recommender_service.py new file mode 100644 index 0000000..eaf488e --- /dev/null +++ b/google/cloud/recommender_v1/types/recommender_service.py @@ -0,0 +1,278 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.recommender_v1.types import insight +from google.cloud.recommender_v1.types import recommendation + + +__protobuf__ = proto.module( + package="google.cloud.recommender.v1", + manifest={ + "ListInsightsRequest", + "ListInsightsResponse", + "GetInsightRequest", + "MarkInsightAcceptedRequest", + "ListRecommendationsRequest", + "ListRecommendationsResponse", + "GetRecommendationRequest", + "MarkRecommendationClaimedRequest", + "MarkRecommendationSucceededRequest", + "MarkRecommendationFailedRequest", + }, +) + + +class ListInsightsRequest(proto.Message): + r"""Request for the ``ListInsights`` method. + + Attributes: + parent (str): + Required. The container resource on which to execute the + request. Acceptable formats: + + 1. + + "projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]", + + LOCATION here refers to GCP Locations: + https://cloud.google.com/about/locations/ + page_size (int): + Optional. The maximum number of results to + return from this request. Non-positive values + are ignored. If not specified, the server will + determine the number of results to return. + page_token (str): + Optional. If present, retrieves the next batch of results + from the preceding call to this method. ``page_token`` must + be the value of ``next_page_token`` from the previous + response. The values of other method parameters must be + identical to those in the previous call. + filter (str): + Optional. Filter expression to restrict the insights + returned. Supported filter fields: state Eg: + \`state:"DISMISSED" or state:"ACTIVE". + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + filter = proto.Field(proto.STRING, number=4) + + +class ListInsightsResponse(proto.Message): + r"""Response to the ``ListInsights`` method. + + Attributes: + insights (Sequence[~.insight.Insight]): + The set of insights for the ``parent`` resource. + next_page_token (str): + A token that can be used to request the next + page of results. This field is empty if there + are no additional results. + """ + + @property + def raw_page(self): + return self + + insights = proto.RepeatedField(proto.MESSAGE, number=1, message=insight.Insight,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetInsightRequest(proto.Message): + r"""Request to the ``GetInsight`` method. + + Attributes: + name (str): + Required. Name of the insight. + """ + + name = proto.Field(proto.STRING, number=1) + + +class MarkInsightAcceptedRequest(proto.Message): + r"""Request for the ``MarkInsightAccepted`` method. + + Attributes: + name (str): + Required. Name of the insight. + state_metadata (Sequence[~.recommender_service.MarkInsightAcceptedRequest.StateMetadataEntry]): + Optional. State properties user wish to include with this + state. Full replace of the current state_metadata. + etag (str): + Required. Fingerprint of the Insight. + Provides optimistic locking. + """ + + name = proto.Field(proto.STRING, number=1) + + state_metadata = proto.MapField(proto.STRING, proto.STRING, number=2) + + etag = proto.Field(proto.STRING, number=3) + + +class ListRecommendationsRequest(proto.Message): + r"""Request for the ``ListRecommendations`` method. + + Attributes: + parent (str): + Required. The container resource on which to execute the + request. Acceptable formats: + + 1. + + "projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]", + + LOCATION here refers to GCP Locations: + https://cloud.google.com/about/locations/ + page_size (int): + Optional. The maximum number of results to + return from this request. Non-positive values + are ignored. If not specified, the server will + determine the number of results to return. + page_token (str): + Optional. If present, retrieves the next batch of results + from the preceding call to this method. ``page_token`` must + be the value of ``next_page_token`` from the previous + response. The values of other method parameters must be + identical to those in the previous call. + filter (str): + Filter expression to restrict the recommendations returned. + Supported filter fields: state_info.state Eg: + \`state_info.state:"DISMISSED" or state_info.state:"FAILED". + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + filter = proto.Field(proto.STRING, number=5) + + +class ListRecommendationsResponse(proto.Message): + r"""Response to the ``ListRecommendations`` method. + + Attributes: + recommendations (Sequence[~.recommendation.Recommendation]): + The set of recommendations for the ``parent`` resource. + next_page_token (str): + A token that can be used to request the next + page of results. This field is empty if there + are no additional results. + """ + + @property + def raw_page(self): + return self + + recommendations = proto.RepeatedField( + proto.MESSAGE, number=1, message=recommendation.Recommendation, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetRecommendationRequest(proto.Message): + r"""Request to the ``GetRecommendation`` method. + + Attributes: + name (str): + Required. Name of the recommendation. + """ + + name = proto.Field(proto.STRING, number=1) + + +class MarkRecommendationClaimedRequest(proto.Message): + r"""Request for the ``MarkRecommendationClaimed`` Method. + + Attributes: + name (str): + Required. Name of the recommendation. + state_metadata (Sequence[~.recommender_service.MarkRecommendationClaimedRequest.StateMetadataEntry]): + State properties to include with this state. Overwrites any + existing ``state_metadata``. Keys must match the regex + ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match the regex + ``/^[a-zA-Z0-9_./-]{0,255}$/``. + etag (str): + Required. Fingerprint of the Recommendation. + Provides optimistic locking. + """ + + name = proto.Field(proto.STRING, number=1) + + state_metadata = proto.MapField(proto.STRING, proto.STRING, number=2) + + etag = proto.Field(proto.STRING, number=3) + + +class MarkRecommendationSucceededRequest(proto.Message): + r"""Request for the ``MarkRecommendationSucceeded`` Method. + + Attributes: + name (str): + Required. Name of the recommendation. + state_metadata (Sequence[~.recommender_service.MarkRecommendationSucceededRequest.StateMetadataEntry]): + State properties to include with this state. Overwrites any + existing ``state_metadata``. Keys must match the regex + ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match the regex + ``/^[a-zA-Z0-9_./-]{0,255}$/``. + etag (str): + Required. Fingerprint of the Recommendation. + Provides optimistic locking. + """ + + name = proto.Field(proto.STRING, number=1) + + state_metadata = proto.MapField(proto.STRING, proto.STRING, number=2) + + etag = proto.Field(proto.STRING, number=3) + + +class MarkRecommendationFailedRequest(proto.Message): + r"""Request for the ``MarkRecommendationFailed`` Method. + + Attributes: + name (str): + Required. Name of the recommendation. + state_metadata (Sequence[~.recommender_service.MarkRecommendationFailedRequest.StateMetadataEntry]): + State properties to include with this state. Overwrites any + existing ``state_metadata``. Keys must match the regex + ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match the regex + ``/^[a-zA-Z0-9_./-]{0,255}$/``. + etag (str): + Required. Fingerprint of the Recommendation. + Provides optimistic locking. + """ + + name = proto.Field(proto.STRING, number=1) + + state_metadata = proto.MapField(proto.STRING, proto.STRING, number=2) + + etag = proto.Field(proto.STRING, number=3) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/recommender_v1beta1/__init__.py b/google/cloud/recommender_v1beta1/__init__.py index 82250ea..dbae64e 100644 --- a/google/cloud/recommender_v1beta1/__init__.py +++ b/google/cloud/recommender_v1beta1/__init__.py @@ -1,45 +1,63 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# - -from __future__ import absolute_import -import sys -import warnings - -from google.cloud.recommender_v1beta1 import types -from google.cloud.recommender_v1beta1.gapic import enums -from google.cloud.recommender_v1beta1.gapic import recommender_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class RecommenderClient(recommender_client.RecommenderClient): - __doc__ = recommender_client.RecommenderClient.__doc__ - enums = enums +from .services.recommender import RecommenderClient +from .types.insight import Insight +from .types.insight import InsightStateInfo +from .types.recommendation import CostProjection +from .types.recommendation import Impact +from .types.recommendation import Operation +from .types.recommendation import OperationGroup +from .types.recommendation import Recommendation +from .types.recommendation import RecommendationContent +from .types.recommendation import RecommendationStateInfo +from .types.recommendation import ValueMatcher +from .types.recommender_service import GetInsightRequest +from .types.recommender_service import GetRecommendationRequest +from .types.recommender_service import ListInsightsRequest +from .types.recommender_service import ListInsightsResponse +from .types.recommender_service import ListRecommendationsRequest +from .types.recommender_service import ListRecommendationsResponse +from .types.recommender_service import MarkInsightAcceptedRequest +from .types.recommender_service import MarkRecommendationClaimedRequest +from .types.recommender_service import MarkRecommendationFailedRequest +from .types.recommender_service import MarkRecommendationSucceededRequest __all__ = ( - "enums", - "types", + "CostProjection", + "GetInsightRequest", + "GetRecommendationRequest", + "Impact", + "Insight", + "InsightStateInfo", + "ListInsightsRequest", + "ListInsightsResponse", + "ListRecommendationsRequest", + "ListRecommendationsResponse", + "MarkInsightAcceptedRequest", + "MarkRecommendationClaimedRequest", + "MarkRecommendationFailedRequest", + "MarkRecommendationSucceededRequest", + "Operation", + "OperationGroup", + "Recommendation", + "RecommendationContent", + "RecommendationStateInfo", + "ValueMatcher", "RecommenderClient", ) diff --git a/google/cloud/recommender_v1beta1/gapic/__init__.py b/google/cloud/recommender_v1beta1/gapic/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/recommender_v1beta1/gapic/enums.py b/google/cloud/recommender_v1beta1/gapic/enums.py deleted file mode 100644 index a794132..0000000 --- a/google/cloud/recommender_v1beta1/gapic/enums.py +++ /dev/null @@ -1,134 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class NullValue(enum.IntEnum): - """ - ``NullValue`` is a singleton enumeration to represent the null value - for the ``Value`` type union. - - The JSON representation for ``NullValue`` is JSON ``null``. - - Attributes: - NULL_VALUE (int): Null value. - """ - - NULL_VALUE = 0 - - -class Impact(object): - class Category(enum.IntEnum): - """ - The category of the impact. - - Attributes: - CATEGORY_UNSPECIFIED (int): Default unspecified category. Don't use directly. - COST (int): Indicates a potential increase or decrease in cost. - SECURITY (int): Indicates a potential increase or decrease in security. - PERFORMANCE (int): Indicates a potential increase or decrease in performance. - MANAGEABILITY (int): Indicates a potential increase or decrease in manageability. - """ - - CATEGORY_UNSPECIFIED = 0 - COST = 1 - SECURITY = 2 - PERFORMANCE = 3 - MANAGEABILITY = 4 - - -class Insight(object): - class Category(enum.IntEnum): - """ - Insight category. - - Attributes: - CATEGORY_UNSPECIFIED (int): Unspecified category. - COST (int): The insight is related to cost. - SECURITY (int): The insight is related to security. - PERFORMANCE (int): The insight is related to performance. - MANAGEABILITY (int): This insight is related to manageability. - """ - - CATEGORY_UNSPECIFIED = 0 - COST = 1 - SECURITY = 2 - PERFORMANCE = 3 - MANAGEABILITY = 4 - - -class InsightStateInfo(object): - class State(enum.IntEnum): - """ - Represents insight state. - - Attributes: - STATE_UNSPECIFIED (int): Unspecified state. - ACTIVE (int): Insight is active. Content for ACTIVE insights can be updated by Google. - ACTIVE insights can be marked DISMISSED OR ACCEPTED. - ACCEPTED (int): Some action has been taken based on this insight. Insights become - accepted when a recommendation derived from the insight has been marked - CLAIMED, SUCCEEDED, or FAILED. ACTIVE insights can also be marked - ACCEPTED explicitly. Content for ACCEPTED insights is immutable. ACCEPTED - insights can only be marked ACCEPTED (which may update state metadata). - DISMISSED (int): Insight is dismissed. Content for DISMISSED insights can be updated by - Google. DISMISSED insights can be marked as ACTIVE. - """ - - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - ACCEPTED = 2 - DISMISSED = 3 - - -class RecommendationStateInfo(object): - class State(enum.IntEnum): - """ - Represents Recommendation State. - - Attributes: - STATE_UNSPECIFIED (int): Default state. Don't use directly. - ACTIVE (int): Recommendation is active and can be applied. Recommendations content can - be updated by Google. - - ACTIVE recommendations can be marked as CLAIMED, SUCCEEDED, or FAILED. - CLAIMED (int): Recommendation is in claimed state. Recommendations content is - immutable and cannot be updated by Google. - - CLAIMED recommendations can be marked as CLAIMED, SUCCEEDED, or FAILED. - SUCCEEDED (int): Recommendation is in succeeded state. Recommendations content is - immutable and cannot be updated by Google. - - SUCCEEDED recommendations can be marked as SUCCEEDED, or FAILED. - FAILED (int): Recommendation is in failed state. Recommendations content is immutable - and cannot be updated by Google. - - FAILED recommendations can be marked as SUCCEEDED, or FAILED. - DISMISSED (int): Recommendation is in dismissed state. Recommendation content can be - updated by Google. - - DISMISSED recommendations can be marked as ACTIVE. - """ - - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - CLAIMED = 6 - SUCCEEDED = 3 - FAILED = 4 - DISMISSED = 5 diff --git a/google/cloud/recommender_v1beta1/gapic/recommender_client.py b/google/cloud/recommender_v1beta1/gapic/recommender_client.py deleted file mode 100644 index 4087ac4..0000000 --- a/google/cloud/recommender_v1beta1/gapic/recommender_client.py +++ /dev/null @@ -1,970 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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. - -"""Accesses the google.cloud.recommender.v1beta1 Recommender API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.page_iterator -import google.api_core.path_template -import grpc - -from google.cloud.recommender_v1beta1.gapic import enums -from google.cloud.recommender_v1beta1.gapic import recommender_client_config -from google.cloud.recommender_v1beta1.gapic.transports import recommender_grpc_transport -from google.cloud.recommender_v1beta1.proto import insight_pb2 -from google.cloud.recommender_v1beta1.proto import recommendation_pb2 -from google.cloud.recommender_v1beta1.proto import recommender_service_pb2 -from google.cloud.recommender_v1beta1.proto import recommender_service_pb2_grpc - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( - "google-cloud-recommender", -).version - - -class RecommenderClient(object): - """ - Provides insights and recommendations for cloud customers for various - categories like performance optimization, cost savings, reliability, feature - discovery, etc. Insights and recommendations are generated automatically - based on analysis of user resources, configuration and monitoring metrics. - """ - - SERVICE_ADDRESS = "recommender.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.recommender.v1beta1.Recommender" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RecommenderClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def insight_path(cls, project, location, insight_type, insight): - """Return a fully-qualified insight string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/insightTypes/{insight_type}/insights/{insight}", - project=project, - location=location, - insight_type=insight_type, - insight=insight, - ) - - @classmethod - def insight_type_path(cls, project, location, insight_type): - """Return a fully-qualified insight_type string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/insightTypes/{insight_type}", - project=project, - location=location, - insight_type=insight_type, - ) - - @classmethod - def recommendation_path(cls, project, location, recommender, recommendation): - """Return a fully-qualified recommendation string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/recommenders/{recommender}/recommendations/{recommendation}", - project=project, - location=location, - recommender=recommender, - recommendation=recommendation, - ) - - @classmethod - def recommender_path(cls, project, location, recommender): - """Return a fully-qualified recommender string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/recommenders/{recommender}", - project=project, - location=location, - recommender=recommender, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.RecommenderGrpcTransport, - Callable[[~.Credentials, type], ~.RecommenderGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = recommender_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=recommender_grpc_transport.RecommenderGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = recommender_grpc_transport.RecommenderGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def list_insights( - self, - parent, - page_size=None, - filter_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists insights for a Cloud project. Requires the recommender.*.list - IAM permission for the specified insight type. - - Example: - >>> from google.cloud import recommender_v1beta1 - >>> - >>> client = recommender_v1beta1.RecommenderClient() - >>> - >>> parent = client.insight_type_path('[PROJECT]', '[LOCATION]', '[INSIGHT_TYPE]') - >>> - >>> # Iterate over all results - >>> for element in client.list_insights(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_insights(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The container resource on which to execute the request. - Acceptable formats: - - 1. - - "projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]", - - LOCATION here refers to GCP Locations: - https://cloud.google.com/about/locations/ - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - filter_ (str): Optional. Filter expression to restrict the insights returned. - Supported filter fields: state Eg: \`state:"DISMISSED" or state:"ACTIVE" - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.recommender_v1beta1.types.Insight` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_insights" not in self._inner_api_calls: - self._inner_api_calls[ - "list_insights" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_insights, - default_retry=self._method_configs["ListInsights"].retry, - default_timeout=self._method_configs["ListInsights"].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.ListInsightsRequest( - parent=parent, page_size=page_size, filter=filter_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_insights"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="insights", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_insight( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the requested insight. Requires the recommender.*.get IAM - permission for the specified insight type. - - Example: - >>> from google.cloud import recommender_v1beta1 - >>> - >>> client = recommender_v1beta1.RecommenderClient() - >>> - >>> name = client.insight_path('[PROJECT]', '[LOCATION]', '[INSIGHT_TYPE]', '[INSIGHT]') - >>> - >>> response = client.get_insight(name) - - Args: - name (str): Required. Name of the insight. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.recommender_v1beta1.types.Insight` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_insight" not in self._inner_api_calls: - self._inner_api_calls[ - "get_insight" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_insight, - default_retry=self._method_configs["GetInsight"].retry, - default_timeout=self._method_configs["GetInsight"].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.GetInsightRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_insight"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def mark_insight_accepted( - self, - name, - etag, - state_metadata=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Marks the Insight State as Accepted. Users can use this method to - indicate to the Recommender API that they have applied some action based - on the insight. This stops the insight content from being updated. - - MarkInsightAccepted can be applied to insights in ACTIVE state. Requires - the recommender.*.update IAM permission for the specified insight. - - Example: - >>> from google.cloud import recommender_v1beta1 - >>> - >>> client = recommender_v1beta1.RecommenderClient() - >>> - >>> name = client.insight_path('[PROJECT]', '[LOCATION]', '[INSIGHT_TYPE]', '[INSIGHT]') - >>> - >>> # TODO: Initialize `etag`: - >>> etag = '' - >>> - >>> response = client.mark_insight_accepted(name, etag) - - Args: - name (str): Required. Name of the insight. - etag (str): Required. Fingerprint of the Insight. Provides optimistic locking. - state_metadata (dict[str -> str]): Optional. State properties user wish to include with this state. - Full replace of the current state_metadata. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.recommender_v1beta1.types.Insight` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "mark_insight_accepted" not in self._inner_api_calls: - self._inner_api_calls[ - "mark_insight_accepted" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.mark_insight_accepted, - default_retry=self._method_configs["MarkInsightAccepted"].retry, - default_timeout=self._method_configs["MarkInsightAccepted"].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.MarkInsightAcceptedRequest( - name=name, etag=etag, state_metadata=state_metadata, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["mark_insight_accepted"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_recommendations( - self, - parent, - page_size=None, - filter_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists recommendations for a Cloud project. Requires the - recommender.*.list IAM permission for the specified recommender. - - Example: - >>> from google.cloud import recommender_v1beta1 - >>> - >>> client = recommender_v1beta1.RecommenderClient() - >>> - >>> parent = client.recommender_path('[PROJECT]', '[LOCATION]', '[RECOMMENDER]') - >>> - >>> # Iterate over all results - >>> for element in client.list_recommendations(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_recommendations(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The container resource on which to execute the request. - Acceptable formats: - - 1. - - "projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]", - - LOCATION here refers to GCP Locations: - https://cloud.google.com/about/locations/ - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - filter_ (str): Filter expression to restrict the recommendations returned. - Supported filter fields: state_info.state Eg: - \`state_info.state:"DISMISSED" or state_info.state:"FAILED" - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.recommender_v1beta1.types.Recommendation` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_recommendations" not in self._inner_api_calls: - self._inner_api_calls[ - "list_recommendations" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_recommendations, - default_retry=self._method_configs["ListRecommendations"].retry, - default_timeout=self._method_configs["ListRecommendations"].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.ListRecommendationsRequest( - parent=parent, page_size=page_size, filter=filter_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_recommendations"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="recommendations", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_recommendation( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the requested recommendation. Requires the recommender.*.get - IAM permission for the specified recommender. - - Example: - >>> from google.cloud import recommender_v1beta1 - >>> - >>> client = recommender_v1beta1.RecommenderClient() - >>> - >>> name = client.recommendation_path('[PROJECT]', '[LOCATION]', '[RECOMMENDER]', '[RECOMMENDATION]') - >>> - >>> response = client.get_recommendation(name) - - Args: - name (str): Required. Name of the recommendation. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.recommender_v1beta1.types.Recommendation` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_recommendation" not in self._inner_api_calls: - self._inner_api_calls[ - "get_recommendation" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_recommendation, - default_retry=self._method_configs["GetRecommendation"].retry, - default_timeout=self._method_configs["GetRecommendation"].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.GetRecommendationRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_recommendation"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def mark_recommendation_claimed( - self, - name, - etag, - state_metadata=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Marks the Recommendation State as Claimed. Users can use this method - to indicate to the Recommender API that they are starting to apply the - recommendation themselves. This stops the recommendation content from - being updated. Associated insights are frozen and placed in the ACCEPTED - state. - - MarkRecommendationClaimed can be applied to recommendations in CLAIMED - or ACTIVE state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - - Example: - >>> from google.cloud import recommender_v1beta1 - >>> - >>> client = recommender_v1beta1.RecommenderClient() - >>> - >>> name = client.recommendation_path('[PROJECT]', '[LOCATION]', '[RECOMMENDER]', '[RECOMMENDATION]') - >>> - >>> # TODO: Initialize `etag`: - >>> etag = '' - >>> - >>> response = client.mark_recommendation_claimed(name, etag) - - Args: - name (str): Required. Name of the recommendation. - etag (str): Required. Fingerprint of the Recommendation. Provides optimistic locking. - state_metadata (dict[str -> str]): State properties to include with this state. Overwrites any existing - ``state_metadata``. Keys must match the regex - ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match the regex - ``/^[a-zA-Z0-9_./-]{0,255}$/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.recommender_v1beta1.types.Recommendation` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "mark_recommendation_claimed" not in self._inner_api_calls: - self._inner_api_calls[ - "mark_recommendation_claimed" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.mark_recommendation_claimed, - default_retry=self._method_configs["MarkRecommendationClaimed"].retry, - default_timeout=self._method_configs[ - "MarkRecommendationClaimed" - ].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.MarkRecommendationClaimedRequest( - name=name, etag=etag, state_metadata=state_metadata, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["mark_recommendation_claimed"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def mark_recommendation_succeeded( - self, - name, - etag, - state_metadata=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Marks the Recommendation State as Succeeded. Users can use this - method to indicate to the Recommender API that they have applied the - recommendation themselves, and the operation was successful. This stops - the recommendation content from being updated. Associated insights are - frozen and placed in the ACCEPTED state. - - MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, - CLAIMED, SUCCEEDED, or FAILED state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - - Example: - >>> from google.cloud import recommender_v1beta1 - >>> - >>> client = recommender_v1beta1.RecommenderClient() - >>> - >>> name = client.recommendation_path('[PROJECT]', '[LOCATION]', '[RECOMMENDER]', '[RECOMMENDATION]') - >>> - >>> # TODO: Initialize `etag`: - >>> etag = '' - >>> - >>> response = client.mark_recommendation_succeeded(name, etag) - - Args: - name (str): Required. Name of the recommendation. - etag (str): Required. Fingerprint of the Recommendation. Provides optimistic locking. - state_metadata (dict[str -> str]): State properties to include with this state. Overwrites any existing - ``state_metadata``. Keys must match the regex - ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match the regex - ``/^[a-zA-Z0-9_./-]{0,255}$/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.recommender_v1beta1.types.Recommendation` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "mark_recommendation_succeeded" not in self._inner_api_calls: - self._inner_api_calls[ - "mark_recommendation_succeeded" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.mark_recommendation_succeeded, - default_retry=self._method_configs["MarkRecommendationSucceeded"].retry, - default_timeout=self._method_configs[ - "MarkRecommendationSucceeded" - ].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.MarkRecommendationSucceededRequest( - name=name, etag=etag, state_metadata=state_metadata, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["mark_recommendation_succeeded"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def mark_recommendation_failed( - self, - name, - etag, - state_metadata=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Marks the Recommendation State as Failed. Users can use this method - to indicate to the Recommender API that they have applied the - recommendation themselves, and the operation failed. This stops the - recommendation content from being updated. Associated insights are - frozen and placed in the ACCEPTED state. - - MarkRecommendationFailed can be applied to recommendations in ACTIVE, - CLAIMED, SUCCEEDED, or FAILED state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - - Example: - >>> from google.cloud import recommender_v1beta1 - >>> - >>> client = recommender_v1beta1.RecommenderClient() - >>> - >>> name = client.recommendation_path('[PROJECT]', '[LOCATION]', '[RECOMMENDER]', '[RECOMMENDATION]') - >>> - >>> # TODO: Initialize `etag`: - >>> etag = '' - >>> - >>> response = client.mark_recommendation_failed(name, etag) - - Args: - name (str): Required. Name of the recommendation. - etag (str): Required. Fingerprint of the Recommendation. Provides optimistic locking. - state_metadata (dict[str -> str]): State properties to include with this state. Overwrites any existing - ``state_metadata``. Keys must match the regex - ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match the regex - ``/^[a-zA-Z0-9_./-]{0,255}$/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.recommender_v1beta1.types.Recommendation` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "mark_recommendation_failed" not in self._inner_api_calls: - self._inner_api_calls[ - "mark_recommendation_failed" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.mark_recommendation_failed, - default_retry=self._method_configs["MarkRecommendationFailed"].retry, - default_timeout=self._method_configs[ - "MarkRecommendationFailed" - ].timeout, - client_info=self._client_info, - ) - - request = recommender_service_pb2.MarkRecommendationFailedRequest( - name=name, etag=etag, state_metadata=state_metadata, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["mark_recommendation_failed"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/recommender_v1beta1/gapic/recommender_client_config.py b/google/cloud/recommender_v1beta1/gapic/recommender_client_config.py deleted file mode 100644 index fa55959..0000000 --- a/google/cloud/recommender_v1beta1/gapic/recommender_client_config.py +++ /dev/null @@ -1,82 +0,0 @@ -config = { - "interfaces": { - "google.cloud.recommender.v1beta1.Recommender": { - "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_codes": [], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - }, - "methods": { - "ListInsights": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetInsight": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "MarkInsightAccepted": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "ListRecommendations": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetRecommendation": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "MarkRecommendationClaimed": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "MarkRecommendationSucceeded": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "MarkRecommendationFailed": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - }, - } - } -} diff --git a/google/cloud/recommender_v1beta1/gapic/transports/__init__.py b/google/cloud/recommender_v1beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/recommender_v1beta1/gapic/transports/recommender_grpc_transport.py b/google/cloud/recommender_v1beta1/gapic/transports/recommender_grpc_transport.py deleted file mode 100644 index 0e7176a..0000000 --- a/google/cloud/recommender_v1beta1/gapic/transports/recommender_grpc_transport.py +++ /dev/null @@ -1,251 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 google.api_core.grpc_helpers - -from google.cloud.recommender_v1beta1.proto import recommender_service_pb2_grpc - - -class RecommenderGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.recommender.v1beta1 Recommender API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, channel=None, credentials=None, address="recommender.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "recommender_stub": recommender_service_pb2_grpc.RecommenderStub(channel), - } - - @classmethod - def create_channel( - cls, address="recommender.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def list_insights(self): - """Return the gRPC stub for :meth:`RecommenderClient.list_insights`. - - Lists insights for a Cloud project. Requires the recommender.*.list - IAM permission for the specified insight type. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].ListInsights - - @property - def get_insight(self): - """Return the gRPC stub for :meth:`RecommenderClient.get_insight`. - - Gets the requested insight. Requires the recommender.*.get IAM - permission for the specified insight type. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].GetInsight - - @property - def mark_insight_accepted(self): - """Return the gRPC stub for :meth:`RecommenderClient.mark_insight_accepted`. - - Marks the Insight State as Accepted. Users can use this method to - indicate to the Recommender API that they have applied some action based - on the insight. This stops the insight content from being updated. - - MarkInsightAccepted can be applied to insights in ACTIVE state. Requires - the recommender.*.update IAM permission for the specified insight. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].MarkInsightAccepted - - @property - def list_recommendations(self): - """Return the gRPC stub for :meth:`RecommenderClient.list_recommendations`. - - Lists recommendations for a Cloud project. Requires the - recommender.*.list IAM permission for the specified recommender. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].ListRecommendations - - @property - def get_recommendation(self): - """Return the gRPC stub for :meth:`RecommenderClient.get_recommendation`. - - Gets the requested recommendation. Requires the recommender.*.get - IAM permission for the specified recommender. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].GetRecommendation - - @property - def mark_recommendation_claimed(self): - """Return the gRPC stub for :meth:`RecommenderClient.mark_recommendation_claimed`. - - Marks the Recommendation State as Claimed. Users can use this method - to indicate to the Recommender API that they are starting to apply the - recommendation themselves. This stops the recommendation content from - being updated. Associated insights are frozen and placed in the ACCEPTED - state. - - MarkRecommendationClaimed can be applied to recommendations in CLAIMED - or ACTIVE state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].MarkRecommendationClaimed - - @property - def mark_recommendation_succeeded(self): - """Return the gRPC stub for :meth:`RecommenderClient.mark_recommendation_succeeded`. - - Marks the Recommendation State as Succeeded. Users can use this - method to indicate to the Recommender API that they have applied the - recommendation themselves, and the operation was successful. This stops - the recommendation content from being updated. Associated insights are - frozen and placed in the ACCEPTED state. - - MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, - CLAIMED, SUCCEEDED, or FAILED state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].MarkRecommendationSucceeded - - @property - def mark_recommendation_failed(self): - """Return the gRPC stub for :meth:`RecommenderClient.mark_recommendation_failed`. - - Marks the Recommendation State as Failed. Users can use this method - to indicate to the Recommender API that they have applied the - recommendation themselves, and the operation failed. This stops the - recommendation content from being updated. Associated insights are - frozen and placed in the ACCEPTED state. - - MarkRecommendationFailed can be applied to recommendations in ACTIVE, - CLAIMED, SUCCEEDED, or FAILED state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["recommender_stub"].MarkRecommendationFailed diff --git a/google/cloud/recommender_v1beta1/proto/__init__.py b/google/cloud/recommender_v1beta1/proto/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/google/cloud/recommender_v1beta1/proto/insight_pb2.py b/google/cloud/recommender_v1beta1/proto/insight_pb2.py deleted file mode 100644 index 72ab4e5..0000000 --- a/google/cloud/recommender_v1beta1/proto/insight_pb2.py +++ /dev/null @@ -1,666 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/recommender_v1beta1/proto/insight.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/recommender_v1beta1/proto/insight.proto", - package="google.cloud.recommender.v1beta1", - syntax="proto3", - serialized_options=b"\n$com.google.cloud.recommender.v1beta1P\001ZKgoogle.golang.org/genproto/googleapis/cloud/recommender/v1beta1;recommender\242\002\004CREC\252\002 Google.Cloud.Recommender.V1Beta1\352Am\n&recommender.googleapis.com/InsightType\022Cprojects/{project}/locations/{location}/insightTypes/{insight_type}", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n4google/cloud/recommender_v1beta1/proto/insight.proto\x12 google.cloud.recommender.v1beta1\x1a\x19google/api/resource.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\x90\x06\n\x07Insight\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12\x18\n\x10target_resources\x18\t \x03(\t\x12\x17\n\x0finsight_subtype\x18\n \x01(\t\x12(\n\x07\x63ontent\x18\x03 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\x35\n\x11last_refresh_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x35\n\x12observation_period\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x46\n\nstate_info\x18\x06 \x01(\x0b\x32\x32.google.cloud.recommender.v1beta1.InsightStateInfo\x12\x44\n\x08\x63\x61tegory\x18\x07 \x01(\x0e\x32\x32.google.cloud.recommender.v1beta1.Insight.Category\x12\x0c\n\x04\x65tag\x18\x0b \x01(\t\x12\x65\n\x1a\x61ssociated_recommendations\x18\x08 \x03(\x0b\x32\x41.google.cloud.recommender.v1beta1.Insight.RecommendationReference\x1a\x31\n\x17RecommendationReference\x12\x16\n\x0erecommendation\x18\x01 \x01(\t"`\n\x08\x43\x61tegory\x12\x18\n\x14\x43\x41TEGORY_UNSPECIFIED\x10\x00\x12\x08\n\x04\x43OST\x10\x01\x12\x0c\n\x08SECURITY\x10\x02\x12\x0f\n\x0bPERFORMANCE\x10\x03\x12\x11\n\rMANAGEABILITY\x10\x04:\x7f\xea\x41|\n"recommender.googleapis.com/Insight\x12Vprojects/{project}/locations/{location}/insightTypes/{insight_type}/insights/{insight}"\xb9\x02\n\x10InsightStateInfo\x12G\n\x05state\x18\x01 \x01(\x0e\x32\x38.google.cloud.recommender.v1beta1.InsightStateInfo.State\x12]\n\x0estate_metadata\x18\x02 \x03(\x0b\x32\x45.google.cloud.recommender.v1beta1.InsightStateInfo.StateMetadataEntry\x1a\x34\n\x12StateMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"G\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\n\n\x06\x41\x43TIVE\x10\x01\x12\x0c\n\x08\x41\x43\x43\x45PTED\x10\x02\x12\r\n\tDISMISSED\x10\x03\x42\x8f\x02\n$com.google.cloud.recommender.v1beta1P\x01ZKgoogle.golang.org/genproto/googleapis/cloud/recommender/v1beta1;recommender\xa2\x02\x04\x43REC\xaa\x02 Google.Cloud.Recommender.V1Beta1\xea\x41m\n&recommender.googleapis.com/InsightType\x12\x43projects/{project}/locations/{location}/insightTypes/{insight_type}b\x06proto3', - dependencies=[ - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_protobuf_dot_duration__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_INSIGHT_CATEGORY = _descriptor.EnumDescriptor( - name="Category", - full_name="google.cloud.recommender.v1beta1.Insight.Category", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="CATEGORY_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="COST", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SECURITY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PERFORMANCE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MANAGEABILITY", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=772, - serialized_end=868, -) -_sym_db.RegisterEnumDescriptor(_INSIGHT_CATEGORY) - -_INSIGHTSTATEINFO_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.recommender.v1beta1.InsightStateInfo.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ACTIVE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ACCEPTED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DISMISSED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1242, - serialized_end=1313, -) -_sym_db.RegisterEnumDescriptor(_INSIGHTSTATEINFO_STATE) - - -_INSIGHT_RECOMMENDATIONREFERENCE = _descriptor.Descriptor( - name="RecommendationReference", - full_name="google.cloud.recommender.v1beta1.Insight.RecommendationReference", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="recommendation", - full_name="google.cloud.recommender.v1beta1.Insight.RecommendationReference.recommendation", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=721, - serialized_end=770, -) - -_INSIGHT = _descriptor.Descriptor( - name="Insight", - full_name="google.cloud.recommender.v1beta1.Insight", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1beta1.Insight.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.recommender.v1beta1.Insight.description", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="target_resources", - full_name="google.cloud.recommender.v1beta1.Insight.target_resources", - index=2, - number=9, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="insight_subtype", - full_name="google.cloud.recommender.v1beta1.Insight.insight_subtype", - index=3, - number=10, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content", - full_name="google.cloud.recommender.v1beta1.Insight.content", - index=4, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="last_refresh_time", - full_name="google.cloud.recommender.v1beta1.Insight.last_refresh_time", - index=5, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="observation_period", - full_name="google.cloud.recommender.v1beta1.Insight.observation_period", - index=6, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_info", - full_name="google.cloud.recommender.v1beta1.Insight.state_info", - index=7, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="category", - full_name="google.cloud.recommender.v1beta1.Insight.category", - index=8, - number=7, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="etag", - full_name="google.cloud.recommender.v1beta1.Insight.etag", - index=9, - number=11, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="associated_recommendations", - full_name="google.cloud.recommender.v1beta1.Insight.associated_recommendations", - index=10, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_INSIGHT_RECOMMENDATIONREFERENCE,], - enum_types=[_INSIGHT_CATEGORY,], - serialized_options=b'\352A|\n"recommender.googleapis.com/Insight\022Vprojects/{project}/locations/{location}/insightTypes/{insight_type}/insights/{insight}', - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=213, - serialized_end=997, -) - - -_INSIGHTSTATEINFO_STATEMETADATAENTRY = _descriptor.Descriptor( - name="StateMetadataEntry", - full_name="google.cloud.recommender.v1beta1.InsightStateInfo.StateMetadataEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1beta1.InsightStateInfo.StateMetadataEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1beta1.InsightStateInfo.StateMetadataEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1188, - serialized_end=1240, -) - -_INSIGHTSTATEINFO = _descriptor.Descriptor( - name="InsightStateInfo", - full_name="google.cloud.recommender.v1beta1.InsightStateInfo", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.recommender.v1beta1.InsightStateInfo.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_metadata", - full_name="google.cloud.recommender.v1beta1.InsightStateInfo.state_metadata", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_INSIGHTSTATEINFO_STATEMETADATAENTRY,], - enum_types=[_INSIGHTSTATEINFO_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1000, - serialized_end=1313, -) - -_INSIGHT_RECOMMENDATIONREFERENCE.containing_type = _INSIGHT -_INSIGHT.fields_by_name[ - "content" -].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_INSIGHT.fields_by_name[ - "last_refresh_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_INSIGHT.fields_by_name[ - "observation_period" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_INSIGHT.fields_by_name["state_info"].message_type = _INSIGHTSTATEINFO -_INSIGHT.fields_by_name["category"].enum_type = _INSIGHT_CATEGORY -_INSIGHT.fields_by_name[ - "associated_recommendations" -].message_type = _INSIGHT_RECOMMENDATIONREFERENCE -_INSIGHT_CATEGORY.containing_type = _INSIGHT -_INSIGHTSTATEINFO_STATEMETADATAENTRY.containing_type = _INSIGHTSTATEINFO -_INSIGHTSTATEINFO.fields_by_name["state"].enum_type = _INSIGHTSTATEINFO_STATE -_INSIGHTSTATEINFO.fields_by_name[ - "state_metadata" -].message_type = _INSIGHTSTATEINFO_STATEMETADATAENTRY -_INSIGHTSTATEINFO_STATE.containing_type = _INSIGHTSTATEINFO -DESCRIPTOR.message_types_by_name["Insight"] = _INSIGHT -DESCRIPTOR.message_types_by_name["InsightStateInfo"] = _INSIGHTSTATEINFO -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Insight = _reflection.GeneratedProtocolMessageType( - "Insight", - (_message.Message,), - { - "RecommendationReference": _reflection.GeneratedProtocolMessageType( - "RecommendationReference", - (_message.Message,), - { - "DESCRIPTOR": _INSIGHT_RECOMMENDATIONREFERENCE, - "__module__": "google.cloud.recommender_v1beta1.proto.insight_pb2", - "__doc__": """Reference to an associated recommendation. - - Attributes: - recommendation: - Recommendation resource name, e.g. projects/[PROJECT_NUMBER]/l - ocations/[LOCATION]/recommenders/[RECOMMENDER_ID]/recommendati - ons/[RECOMMENDATION_ID] - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.Insight.RecommendationReference) - }, - ), - "DESCRIPTOR": _INSIGHT, - "__module__": "google.cloud.recommender_v1beta1.proto.insight_pb2", - "__doc__": """An insight along with the information used to derive the insight. The - insight may have associated recomendations as well. - - Attributes: - name: - Name of the insight. - description: - Free-form human readable summary in English. The maximum - length is 500 characters. - target_resources: - Fully qualified resource names that this insight is targeting. - insight_subtype: - Insight subtype. Insight content schema will be stable for a - given subtype. - content: - A struct of custom fields to explain the insight. Example: - “grantedPermissionsCount”: “1000” - last_refresh_time: - Timestamp of the latest data used to generate the insight. - observation_period: - Observation period that led to the insight. The source data - used to generate the insight ends at last_refresh_time and - begins at (last_refresh_time - observation_period). - state_info: - Information state and metadata. - category: - Category being targeted by the insight. - etag: - Fingerprint of the Insight. Provides optimistic locking when - updating states. - associated_recommendations: - Recommendations derived from this insight. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.Insight) - }, -) -_sym_db.RegisterMessage(Insight) -_sym_db.RegisterMessage(Insight.RecommendationReference) - -InsightStateInfo = _reflection.GeneratedProtocolMessageType( - "InsightStateInfo", - (_message.Message,), - { - "StateMetadataEntry": _reflection.GeneratedProtocolMessageType( - "StateMetadataEntry", - (_message.Message,), - { - "DESCRIPTOR": _INSIGHTSTATEINFO_STATEMETADATAENTRY, - "__module__": "google.cloud.recommender_v1beta1.proto.insight_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.InsightStateInfo.StateMetadataEntry) - }, - ), - "DESCRIPTOR": _INSIGHTSTATEINFO, - "__module__": "google.cloud.recommender_v1beta1.proto.insight_pb2", - "__doc__": """Information related to insight state. - - Attributes: - state: - Insight state. - state_metadata: - A map of metadata for the state, provided by user or - automations systems. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.InsightStateInfo) - }, -) -_sym_db.RegisterMessage(InsightStateInfo) -_sym_db.RegisterMessage(InsightStateInfo.StateMetadataEntry) - - -DESCRIPTOR._options = None -_INSIGHT._options = None -_INSIGHTSTATEINFO_STATEMETADATAENTRY._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/recommender_v1beta1/proto/insight_pb2_grpc.py b/google/cloud/recommender_v1beta1/proto/insight_pb2_grpc.py deleted file mode 100644 index 8a93939..0000000 --- a/google/cloud/recommender_v1beta1/proto/insight_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/recommender_v1beta1/proto/recommendation.proto b/google/cloud/recommender_v1beta1/proto/recommendation.proto deleted file mode 100644 index 8980de0..0000000 --- a/google/cloud/recommender_v1beta1/proto/recommendation.proto +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -syntax = "proto3"; - -package google.cloud.recommender.v1beta1; - -import "google/protobuf/duration.proto"; -import "google/protobuf/struct.proto"; -import "google/protobuf/timestamp.proto"; -import "google/type/money.proto"; - -option csharp_namespace = "Google.Cloud.Recommender.V1Beta1"; -option go_package = "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1;recommender"; -option java_multiple_files = true; -option java_package = "com.google.cloud.recommender.v1beta1"; -option objc_class_prefix = "CREC"; - -// A recommendation along with a suggested action. E.g., a rightsizing -// recommendation for an underutilized VM, IAM role recommendations, etc -message Recommendation { - // Name of recommendation. - // - // A project recommendation is represented as - // projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/recommendations/[RECOMMENDATION_ID] - string name = 1; - - // Free-form human readable summary in English. The maximum length is 500 - // characters. - string description = 2; - - // Contains an identifier for a subtype of recommendations produced for the - // same recommender. Subtype is a function of content and impact, meaning a - // new subtype will be added when either content or primary impact category - // changes. - // - // Examples: - // For recommender = "google.iam.policy.RoleRecommender", - // recommender_subtype can be one of "REMOVE_ROLE"/"REPLACE_ROLE" - string recommender_subtype = 12; - - // Last time this recommendation was refreshed by the system that created it - // in the first place. - google.protobuf.Timestamp last_refresh_time = 4; - - // The primary impact that this recommendation can have while trying to - // optimize for one category. - Impact primary_impact = 5; - - // Optional set of additional impact that this recommendation may have when - // trying to optimize for the primary category. These may be positive - // or negative. - repeated Impact additional_impact = 6; - - // Content of the recommendation describing recommended changes to resources. - RecommendationContent content = 7; - - // Information for state. Contains state and metadata. - RecommendationStateInfo state_info = 10; - - // Fingerprint of the Recommendation. Provides optimistic locking when - // updating states. - string etag = 11; -} - -// Contains what resources are changing and how they are changing. -message RecommendationContent { - // Operations to one or more Google Cloud resources grouped in such a way - // that, all operations within one group are expected to be performed - // atomically and in an order. - repeated OperationGroup operation_groups = 2; -} - -// Group of operations that need to be performed atomically. -message OperationGroup { - // List of operations across one or more resources that belong to this group. - // Loosely based on RFC6902 and should be performed in the order they appear. - repeated Operation operations = 1; -} - -// Contains an operation for a resource inspired by the JSON-PATCH format with -// support for: -// * Custom filters for describing partial array patch. -// * Extended path values for describing nested arrays. -// * Custom fields for describing the resource for which the operation is being -// described. -// * Allows extension to custom operations not natively supported by RFC6902. -// See https://tools.ietf.org/html/rfc6902 for details on the original RFC. -message Operation { - // Type of this operation. Contains one of 'and', 'remove', 'replace', 'move', - // 'copy', 'test' and custom operations. This field is case-insensitive and - // always populated. - string action = 1; - - // Type of GCP resource being modified/tested. This field is always populated. - // Example: cloudresourcemanager.googleapis.com/Project, - // compute.googleapis.com/Instance - string resource_type = 2; - - // Contains the fully qualified resource name. This field is always populated. - // ex: //cloudresourcemanager.googleapis.com/projects/foo. - string resource = 3; - - // Path to the target field being operated on. If the operation is at the - // resource level, then path should be "/". This field is always populated. - string path = 4; - - // Can be set with action 'copy' to copy resource configuration across - // different resources of the same type. Example: A resource clone can be - // done via action = 'copy', path = "/", from = "/", - // source_resource = and resource_name = . - // This field is empty for all other values of `action`. - string source_resource = 5; - - // Can be set with action 'copy' or 'move' to indicate the source field within - // resource or source_resource, ignored if provided for other operation types. - string source_path = 6; - - // Value for the `path` field. Set if action is 'add'/'replace'/'test'. - google.protobuf.Value value = 7; - - // Set of filters to apply if `path` refers to array elements or nested array - // elements in order to narrow down to a single unique element that is being - // tested/modified. - // Note that this is intended to be an exact match per filter. - // Example: { - // "/versions/*/name" : "it-123" - // "/versions/*/targetSize/percent": 20 - // } - // Example: { - // "/bindings/*/role": "roles/admin" - // "/bindings/*/condition" : null - // } - // Example: { - // "/bindings/*/role": "roles/admin" - // "/bindings/*/members/*" : ["x@google.com", "y@google.com"] - // } - map path_filters = 8; -} - -// Contains metadata about how much money a recommendation can save or incur. -message CostProjection { - // An approximate projection on amount saved or amount incurred. Negative cost - // units indicate cost savings and positive cost units indicate increase. - // See google.type.Money documentation for positive/negative units. - google.type.Money cost = 1; - - // Duration for which this cost applies. - google.protobuf.Duration duration = 2; -} - -// Contains the impact a recommendation can have for a given category. -message Impact { - // The category of the impact. - enum Category { - // Default unspecified category. Don't use directly. - CATEGORY_UNSPECIFIED = 0; - - // Indicates a potential increase or decrease in cost. - COST = 1; - - // Indicates a potential increase or decrease in security. - SECURITY = 2; - - // Indicates a potential increase or decrease in performance. - PERFORMANCE = 3; - } - - // Category that is being targeted. - Category category = 1; - - // Contains projections (if any) for this category. - oneof projection { - // Use with CategoryType.COST - CostProjection cost_projection = 100; - } -} - -// Information for state. Contains state and metadata. -message RecommendationStateInfo { - // Represents Recommendation State - enum State { - // Default state. Don't use directly. - STATE_UNSPECIFIED = 0; - - // Recommendation is active and can be applied. Recommendations content can - // be updated by Google. - // - // ACTIVE recommendations can be marked as CLAIMED, SUCCEEDED, or FAILED. - ACTIVE = 1; - - // Recommendation is in claimed state. Recommendations content is - // immutable and cannot be updated by Google. - // - // CLAIMED recommendations can be marked as CLAIMED, SUCCEEDED, or FAILED. - CLAIMED = 6; - - // Recommendation is in succeeded state. Recommendations content is - // immutable and cannot be updated by Google. - // - // SUCCEEDED recommendations can be marked as SUCCEEDED, or FAILED. - SUCCEEDED = 3; - - // Recommendation is in failed state. Recommendations content is immutable - // and cannot be updated by Google. - // - // FAILED recommendations can be marked as SUCCEEDED, or FAILED. - FAILED = 4; - - // Recommendation is in dismissed state. Recommendation content can be - // updated by Google. - // - // DISMISSED recommendations can be marked as ACTIVE. - DISMISSED = 5; - } - - // The state of the recommendation, Eg ACTIVE, SUCCEEDED, FAILED. - State state = 1; - - // A map of metadata for the state, provided by user or automations systems. - map state_metadata = 2; -} diff --git a/google/cloud/recommender_v1beta1/proto/recommendation_pb2.py b/google/cloud/recommender_v1beta1/proto/recommendation_pb2.py deleted file mode 100644 index 1aa6e14..0000000 --- a/google/cloud/recommender_v1beta1/proto/recommendation_pb2.py +++ /dev/null @@ -1,1525 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/recommender_v1beta1/proto/recommendation.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.type import money_pb2 as google_dot_type_dot_money__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/recommender_v1beta1/proto/recommendation.proto", - package="google.cloud.recommender.v1beta1", - syntax="proto3", - serialized_options=b"\n$com.google.cloud.recommender.v1beta1P\001ZKgoogle.golang.org/genproto/googleapis/cloud/recommender/v1beta1;recommender\242\002\004CREC\252\002 Google.Cloud.Recommender.V1Beta1\352Al\n&recommender.googleapis.com/Recommender\022Bprojects/{project}/locations/{location}/recommenders/{recommender}", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n;google/cloud/recommender_v1beta1/proto/recommendation.proto\x12 google.cloud.recommender.v1beta1\x1a\x19google/api/resource.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/type/money.proto"\xd1\x05\n\x0eRecommendation\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12\x1b\n\x13recommender_subtype\x18\x0c \x01(\t\x12\x35\n\x11last_refresh_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12@\n\x0eprimary_impact\x18\x05 \x01(\x0b\x32(.google.cloud.recommender.v1beta1.Impact\x12\x43\n\x11\x61\x64\x64itional_impact\x18\x06 \x03(\x0b\x32(.google.cloud.recommender.v1beta1.Impact\x12H\n\x07\x63ontent\x18\x07 \x01(\x0b\x32\x37.google.cloud.recommender.v1beta1.RecommendationContent\x12M\n\nstate_info\x18\n \x01(\x0b\x32\x39.google.cloud.recommender.v1beta1.RecommendationStateInfo\x12\x0c\n\x04\x65tag\x18\x0b \x01(\t\x12^\n\x13\x61ssociated_insights\x18\x0e \x03(\x0b\x32\x41.google.cloud.recommender.v1beta1.Recommendation.InsightReference\x1a#\n\x10InsightReference\x12\x0f\n\x07insight\x18\x01 \x01(\t:\x94\x01\xea\x41\x90\x01\n)recommender.googleapis.com/Recommendation\x12\x63projects/{project}/locations/{location}/recommenders/{recommender}/recommendations/{recommendation}"c\n\x15RecommendationContent\x12J\n\x10operation_groups\x18\x02 \x03(\x0b\x32\x30.google.cloud.recommender.v1beta1.OperationGroup"Q\n\x0eOperationGroup\x12?\n\noperations\x18\x01 \x03(\x0b\x32+.google.cloud.recommender.v1beta1.Operation"\xeb\x04\n\tOperation\x12\x0e\n\x06\x61\x63tion\x18\x01 \x01(\t\x12\x15\n\rresource_type\x18\x02 \x01(\t\x12\x10\n\x08resource\x18\x03 \x01(\t\x12\x0c\n\x04path\x18\x04 \x01(\t\x12\x17\n\x0fsource_resource\x18\x05 \x01(\t\x12\x13\n\x0bsource_path\x18\x06 \x01(\t\x12\'\n\x05value\x18\x07 \x01(\x0b\x32\x16.google.protobuf.ValueH\x00\x12G\n\rvalue_matcher\x18\n \x01(\x0b\x32..google.cloud.recommender.v1beta1.ValueMatcherH\x00\x12R\n\x0cpath_filters\x18\x08 \x03(\x0b\x32<.google.cloud.recommender.v1beta1.Operation.PathFiltersEntry\x12_\n\x13path_value_matchers\x18\x0b \x03(\x0b\x32\x42.google.cloud.recommender.v1beta1.Operation.PathValueMatchersEntry\x1aJ\n\x10PathFiltersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01\x1ah\n\x16PathValueMatchersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12=\n\x05value\x18\x02 \x01(\x0b\x32..google.cloud.recommender.v1beta1.ValueMatcher:\x02\x38\x01\x42\x0c\n\npath_value":\n\x0cValueMatcher\x12\x19\n\x0fmatches_pattern\x18\x01 \x01(\tH\x00\x42\x0f\n\rmatch_variant"_\n\x0e\x43ostProjection\x12 \n\x04\x63ost\x18\x01 \x01(\x0b\x32\x12.google.type.Money\x12+\n\x08\x64uration\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"\x8a\x02\n\x06Impact\x12\x43\n\x08\x63\x61tegory\x18\x01 \x01(\x0e\x32\x31.google.cloud.recommender.v1beta1.Impact.Category\x12K\n\x0f\x63ost_projection\x18\x64 \x01(\x0b\x32\x30.google.cloud.recommender.v1beta1.CostProjectionH\x00"`\n\x08\x43\x61tegory\x12\x18\n\x14\x43\x41TEGORY_UNSPECIFIED\x10\x00\x12\x08\n\x04\x43OST\x10\x01\x12\x0c\n\x08SECURITY\x10\x02\x12\x0f\n\x0bPERFORMANCE\x10\x03\x12\x11\n\rMANAGEABILITY\x10\x04\x42\x0c\n\nprojection"\xe8\x02\n\x17RecommendationStateInfo\x12N\n\x05state\x18\x01 \x01(\x0e\x32?.google.cloud.recommender.v1beta1.RecommendationStateInfo.State\x12\x64\n\x0estate_metadata\x18\x02 \x03(\x0b\x32L.google.cloud.recommender.v1beta1.RecommendationStateInfo.StateMetadataEntry\x1a\x34\n\x12StateMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"a\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\n\n\x06\x41\x43TIVE\x10\x01\x12\x0b\n\x07\x43LAIMED\x10\x06\x12\r\n\tSUCCEEDED\x10\x03\x12\n\n\x06\x46\x41ILED\x10\x04\x12\r\n\tDISMISSED\x10\x05\x42\x8e\x02\n$com.google.cloud.recommender.v1beta1P\x01ZKgoogle.golang.org/genproto/googleapis/cloud/recommender/v1beta1;recommender\xa2\x02\x04\x43REC\xaa\x02 Google.Cloud.Recommender.V1Beta1\xea\x41l\n&recommender.googleapis.com/Recommender\x12\x42projects/{project}/locations/{location}/recommenders/{recommender}b\x06proto3', - dependencies=[ - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_protobuf_dot_duration__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_type_dot_money__pb2.DESCRIPTOR, - ], -) - - -_IMPACT_CATEGORY = _descriptor.EnumDescriptor( - name="Category", - full_name="google.cloud.recommender.v1beta1.Impact.Category", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="CATEGORY_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="COST", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SECURITY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PERFORMANCE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MANAGEABILITY", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=2088, - serialized_end=2184, -) -_sym_db.RegisterEnumDescriptor(_IMPACT_CATEGORY) - -_RECOMMENDATIONSTATEINFO_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.recommender.v1beta1.RecommendationStateInfo.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ACTIVE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CLAIMED", - index=2, - number=6, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SUCCEEDED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FAILED", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DISMISSED", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=2464, - serialized_end=2561, -) -_sym_db.RegisterEnumDescriptor(_RECOMMENDATIONSTATEINFO_STATE) - - -_RECOMMENDATION_INSIGHTREFERENCE = _descriptor.Descriptor( - name="InsightReference", - full_name="google.cloud.recommender.v1beta1.Recommendation.InsightReference", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="insight", - full_name="google.cloud.recommender.v1beta1.Recommendation.InsightReference.insight", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=780, - serialized_end=815, -) - -_RECOMMENDATION = _descriptor.Descriptor( - name="Recommendation", - full_name="google.cloud.recommender.v1beta1.Recommendation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1beta1.Recommendation.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.recommender.v1beta1.Recommendation.description", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="recommender_subtype", - full_name="google.cloud.recommender.v1beta1.Recommendation.recommender_subtype", - index=2, - number=12, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="last_refresh_time", - full_name="google.cloud.recommender.v1beta1.Recommendation.last_refresh_time", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="primary_impact", - full_name="google.cloud.recommender.v1beta1.Recommendation.primary_impact", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="additional_impact", - full_name="google.cloud.recommender.v1beta1.Recommendation.additional_impact", - index=5, - number=6, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content", - full_name="google.cloud.recommender.v1beta1.Recommendation.content", - index=6, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_info", - full_name="google.cloud.recommender.v1beta1.Recommendation.state_info", - index=7, - number=10, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="etag", - full_name="google.cloud.recommender.v1beta1.Recommendation.etag", - index=8, - number=11, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="associated_insights", - full_name="google.cloud.recommender.v1beta1.Recommendation.associated_insights", - index=9, - number=14, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_RECOMMENDATION_INSIGHTREFERENCE,], - enum_types=[], - serialized_options=b"\352A\220\001\n)recommender.googleapis.com/Recommendation\022cprojects/{project}/locations/{location}/recommenders/{recommender}/recommendations/{recommendation}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=245, - serialized_end=966, -) - - -_RECOMMENDATIONCONTENT = _descriptor.Descriptor( - name="RecommendationContent", - full_name="google.cloud.recommender.v1beta1.RecommendationContent", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="operation_groups", - full_name="google.cloud.recommender.v1beta1.RecommendationContent.operation_groups", - index=0, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=968, - serialized_end=1067, -) - - -_OPERATIONGROUP = _descriptor.Descriptor( - name="OperationGroup", - full_name="google.cloud.recommender.v1beta1.OperationGroup", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="operations", - full_name="google.cloud.recommender.v1beta1.OperationGroup.operations", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1069, - serialized_end=1150, -) - - -_OPERATION_PATHFILTERSENTRY = _descriptor.Descriptor( - name="PathFiltersEntry", - full_name="google.cloud.recommender.v1beta1.Operation.PathFiltersEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1beta1.Operation.PathFiltersEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1beta1.Operation.PathFiltersEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1578, - serialized_end=1652, -) - -_OPERATION_PATHVALUEMATCHERSENTRY = _descriptor.Descriptor( - name="PathValueMatchersEntry", - full_name="google.cloud.recommender.v1beta1.Operation.PathValueMatchersEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1beta1.Operation.PathValueMatchersEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1beta1.Operation.PathValueMatchersEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1654, - serialized_end=1758, -) - -_OPERATION = _descriptor.Descriptor( - name="Operation", - full_name="google.cloud.recommender.v1beta1.Operation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="action", - full_name="google.cloud.recommender.v1beta1.Operation.action", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_type", - full_name="google.cloud.recommender.v1beta1.Operation.resource_type", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource", - full_name="google.cloud.recommender.v1beta1.Operation.resource", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="path", - full_name="google.cloud.recommender.v1beta1.Operation.path", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source_resource", - full_name="google.cloud.recommender.v1beta1.Operation.source_resource", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source_path", - full_name="google.cloud.recommender.v1beta1.Operation.source_path", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1beta1.Operation.value", - index=6, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value_matcher", - full_name="google.cloud.recommender.v1beta1.Operation.value_matcher", - index=7, - number=10, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="path_filters", - full_name="google.cloud.recommender.v1beta1.Operation.path_filters", - index=8, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="path_value_matchers", - full_name="google.cloud.recommender.v1beta1.Operation.path_value_matchers", - index=9, - number=11, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_OPERATION_PATHFILTERSENTRY, _OPERATION_PATHVALUEMATCHERSENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="path_value", - full_name="google.cloud.recommender.v1beta1.Operation.path_value", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1153, - serialized_end=1772, -) - - -_VALUEMATCHER = _descriptor.Descriptor( - name="ValueMatcher", - full_name="google.cloud.recommender.v1beta1.ValueMatcher", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="matches_pattern", - full_name="google.cloud.recommender.v1beta1.ValueMatcher.matches_pattern", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="match_variant", - full_name="google.cloud.recommender.v1beta1.ValueMatcher.match_variant", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1774, - serialized_end=1832, -) - - -_COSTPROJECTION = _descriptor.Descriptor( - name="CostProjection", - full_name="google.cloud.recommender.v1beta1.CostProjection", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="cost", - full_name="google.cloud.recommender.v1beta1.CostProjection.cost", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="duration", - full_name="google.cloud.recommender.v1beta1.CostProjection.duration", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1834, - serialized_end=1929, -) - - -_IMPACT = _descriptor.Descriptor( - name="Impact", - full_name="google.cloud.recommender.v1beta1.Impact", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="category", - full_name="google.cloud.recommender.v1beta1.Impact.category", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="cost_projection", - full_name="google.cloud.recommender.v1beta1.Impact.cost_projection", - index=1, - number=100, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_IMPACT_CATEGORY,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="projection", - full_name="google.cloud.recommender.v1beta1.Impact.projection", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1932, - serialized_end=2198, -) - - -_RECOMMENDATIONSTATEINFO_STATEMETADATAENTRY = _descriptor.Descriptor( - name="StateMetadataEntry", - full_name="google.cloud.recommender.v1beta1.RecommendationStateInfo.StateMetadataEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1beta1.RecommendationStateInfo.StateMetadataEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1beta1.RecommendationStateInfo.StateMetadataEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2410, - serialized_end=2462, -) - -_RECOMMENDATIONSTATEINFO = _descriptor.Descriptor( - name="RecommendationStateInfo", - full_name="google.cloud.recommender.v1beta1.RecommendationStateInfo", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.recommender.v1beta1.RecommendationStateInfo.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_metadata", - full_name="google.cloud.recommender.v1beta1.RecommendationStateInfo.state_metadata", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_RECOMMENDATIONSTATEINFO_STATEMETADATAENTRY,], - enum_types=[_RECOMMENDATIONSTATEINFO_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2201, - serialized_end=2561, -) - -_RECOMMENDATION_INSIGHTREFERENCE.containing_type = _RECOMMENDATION -_RECOMMENDATION.fields_by_name[ - "last_refresh_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_RECOMMENDATION.fields_by_name["primary_impact"].message_type = _IMPACT -_RECOMMENDATION.fields_by_name["additional_impact"].message_type = _IMPACT -_RECOMMENDATION.fields_by_name["content"].message_type = _RECOMMENDATIONCONTENT -_RECOMMENDATION.fields_by_name["state_info"].message_type = _RECOMMENDATIONSTATEINFO -_RECOMMENDATION.fields_by_name[ - "associated_insights" -].message_type = _RECOMMENDATION_INSIGHTREFERENCE -_RECOMMENDATIONCONTENT.fields_by_name["operation_groups"].message_type = _OPERATIONGROUP -_OPERATIONGROUP.fields_by_name["operations"].message_type = _OPERATION -_OPERATION_PATHFILTERSENTRY.fields_by_name[ - "value" -].message_type = google_dot_protobuf_dot_struct__pb2._VALUE -_OPERATION_PATHFILTERSENTRY.containing_type = _OPERATION -_OPERATION_PATHVALUEMATCHERSENTRY.fields_by_name["value"].message_type = _VALUEMATCHER -_OPERATION_PATHVALUEMATCHERSENTRY.containing_type = _OPERATION -_OPERATION.fields_by_name[ - "value" -].message_type = google_dot_protobuf_dot_struct__pb2._VALUE -_OPERATION.fields_by_name["value_matcher"].message_type = _VALUEMATCHER -_OPERATION.fields_by_name["path_filters"].message_type = _OPERATION_PATHFILTERSENTRY -_OPERATION.fields_by_name[ - "path_value_matchers" -].message_type = _OPERATION_PATHVALUEMATCHERSENTRY -_OPERATION.oneofs_by_name["path_value"].fields.append( - _OPERATION.fields_by_name["value"] -) -_OPERATION.fields_by_name["value"].containing_oneof = _OPERATION.oneofs_by_name[ - "path_value" -] -_OPERATION.oneofs_by_name["path_value"].fields.append( - _OPERATION.fields_by_name["value_matcher"] -) -_OPERATION.fields_by_name["value_matcher"].containing_oneof = _OPERATION.oneofs_by_name[ - "path_value" -] -_VALUEMATCHER.oneofs_by_name["match_variant"].fields.append( - _VALUEMATCHER.fields_by_name["matches_pattern"] -) -_VALUEMATCHER.fields_by_name[ - "matches_pattern" -].containing_oneof = _VALUEMATCHER.oneofs_by_name["match_variant"] -_COSTPROJECTION.fields_by_name[ - "cost" -].message_type = google_dot_type_dot_money__pb2._MONEY -_COSTPROJECTION.fields_by_name[ - "duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_IMPACT.fields_by_name["category"].enum_type = _IMPACT_CATEGORY -_IMPACT.fields_by_name["cost_projection"].message_type = _COSTPROJECTION -_IMPACT_CATEGORY.containing_type = _IMPACT -_IMPACT.oneofs_by_name["projection"].fields.append( - _IMPACT.fields_by_name["cost_projection"] -) -_IMPACT.fields_by_name["cost_projection"].containing_oneof = _IMPACT.oneofs_by_name[ - "projection" -] -_RECOMMENDATIONSTATEINFO_STATEMETADATAENTRY.containing_type = _RECOMMENDATIONSTATEINFO -_RECOMMENDATIONSTATEINFO.fields_by_name[ - "state" -].enum_type = _RECOMMENDATIONSTATEINFO_STATE -_RECOMMENDATIONSTATEINFO.fields_by_name[ - "state_metadata" -].message_type = _RECOMMENDATIONSTATEINFO_STATEMETADATAENTRY -_RECOMMENDATIONSTATEINFO_STATE.containing_type = _RECOMMENDATIONSTATEINFO -DESCRIPTOR.message_types_by_name["Recommendation"] = _RECOMMENDATION -DESCRIPTOR.message_types_by_name["RecommendationContent"] = _RECOMMENDATIONCONTENT -DESCRIPTOR.message_types_by_name["OperationGroup"] = _OPERATIONGROUP -DESCRIPTOR.message_types_by_name["Operation"] = _OPERATION -DESCRIPTOR.message_types_by_name["ValueMatcher"] = _VALUEMATCHER -DESCRIPTOR.message_types_by_name["CostProjection"] = _COSTPROJECTION -DESCRIPTOR.message_types_by_name["Impact"] = _IMPACT -DESCRIPTOR.message_types_by_name["RecommendationStateInfo"] = _RECOMMENDATIONSTATEINFO -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Recommendation = _reflection.GeneratedProtocolMessageType( - "Recommendation", - (_message.Message,), - { - "InsightReference": _reflection.GeneratedProtocolMessageType( - "InsightReference", - (_message.Message,), - { - "DESCRIPTOR": _RECOMMENDATION_INSIGHTREFERENCE, - "__module__": "google.cloud.recommender_v1beta1.proto.recommendation_pb2", - "__doc__": """Reference to an associated insight. - - Attributes: - insight: - Insight resource name, e.g. ``projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]/insights/[INSIGHT_ID]`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.Recommendation.InsightReference) - }, - ), - "DESCRIPTOR": _RECOMMENDATION, - "__module__": "google.cloud.recommender_v1beta1.proto.recommendation_pb2", - "__doc__": """A recommendation along with a suggested action. E.g., a rightsizing - recommendation for an underutilized VM, IAM role recommendations, etc - - Attributes: - name: - Name of recommendation. - description: - Free-form human readable summary in English. The maximum - length is 500 characters. - recommender_subtype: - Contains an identifier for a subtype of recommendations - produced for the same recommender. Subtype is a function of - content and impact, meaning a new subtype might be added when - significant changes to ``content`` or - ``primary_impact.category`` are introduced. See the - Recommenders section to see a list of subtypes for a given - Recommender. Examples: For recommender = - “google.iam.policy.Recommender”, recommender_subtype can be - one of “REMOVE_ROLE”/“REPLACE_ROLE” - last_refresh_time: - Last time this recommendation was refreshed by the system that - created it in the first place. - primary_impact: - The primary impact that this recommendation can have while - trying to optimize for one category. - additional_impact: - Optional set of additional impact that this recommendation may - have when trying to optimize for the primary category. These - may be positive or negative. - content: - Content of the recommendation describing recommended changes - to resources. - state_info: - Information for state. Contains state and metadata. - etag: - Fingerprint of the Recommendation. Provides optimistic locking - when updating states. - associated_insights: - Insights that led to this recommendation. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.Recommendation) - }, -) -_sym_db.RegisterMessage(Recommendation) -_sym_db.RegisterMessage(Recommendation.InsightReference) - -RecommendationContent = _reflection.GeneratedProtocolMessageType( - "RecommendationContent", - (_message.Message,), - { - "DESCRIPTOR": _RECOMMENDATIONCONTENT, - "__module__": "google.cloud.recommender_v1beta1.proto.recommendation_pb2", - "__doc__": """Contains what resources are changing and how they are changing. - - Attributes: - operation_groups: - Operations to one or more Google Cloud resources grouped in - such a way that, all operations within one group are expected - to be performed atomically and in an order. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.RecommendationContent) - }, -) -_sym_db.RegisterMessage(RecommendationContent) - -OperationGroup = _reflection.GeneratedProtocolMessageType( - "OperationGroup", - (_message.Message,), - { - "DESCRIPTOR": _OPERATIONGROUP, - "__module__": "google.cloud.recommender_v1beta1.proto.recommendation_pb2", - "__doc__": """Group of operations that need to be performed atomically. - - Attributes: - operations: - List of operations across one or more resources that belong to - this group. Loosely based on RFC6902 and should be performed - in the order they appear. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.OperationGroup) - }, -) -_sym_db.RegisterMessage(OperationGroup) - -Operation = _reflection.GeneratedProtocolMessageType( - "Operation", - (_message.Message,), - { - "PathFiltersEntry": _reflection.GeneratedProtocolMessageType( - "PathFiltersEntry", - (_message.Message,), - { - "DESCRIPTOR": _OPERATION_PATHFILTERSENTRY, - "__module__": "google.cloud.recommender_v1beta1.proto.recommendation_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.Operation.PathFiltersEntry) - }, - ), - "PathValueMatchersEntry": _reflection.GeneratedProtocolMessageType( - "PathValueMatchersEntry", - (_message.Message,), - { - "DESCRIPTOR": _OPERATION_PATHVALUEMATCHERSENTRY, - "__module__": "google.cloud.recommender_v1beta1.proto.recommendation_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.Operation.PathValueMatchersEntry) - }, - ), - "DESCRIPTOR": _OPERATION, - "__module__": "google.cloud.recommender_v1beta1.proto.recommendation_pb2", - "__doc__": """Contains an operation for a resource loosely based on the JSON-PATCH - format with support for: - Custom filters for describing partial - array patch. - Extended path values for describing nested arrays. - - Custom fields for describing the resource for which the operation is - being described. - Allows extension to custom operations not natively - supported by RFC6902. See https://tools.ietf.org/html/rfc6902 for - details on the original RFC. - - Attributes: - action: - Type of this operation. Contains one of ‘and’, ‘remove’, - ‘replace’, ‘move’, ‘copy’, ‘test’ and ‘custom’ operations. - This field is case-insensitive and always populated. - resource_type: - Type of GCP resource being modified/tested. This field is - always populated. Example: - cloudresourcemanager.googleapis.com/Project, - compute.googleapis.com/Instance - resource: - Contains the fully qualified resource name. This field is - always populated. ex: - //cloudresourcemanager.googleapis.com/projects/foo. - path: - Path to the target field being operated on. If the operation - is at the resource level, then path should be “/”. This field - is always populated. - source_resource: - Can be set with action ‘copy’ to copy resource configuration - across different resources of the same type. Example: A - resource clone can be done via action = ‘copy’, path = “/”, - from = “/”, source_resource = and resource_name = . This field - is empty for all other values of ``action``. - source_path: - Can be set with action ‘copy’ or ‘move’ to indicate the source - field within resource or source_resource, ignored if provided - for other operation types. - path_value: - One of the fields in the following block will be set and - intend to describe a value for ‘path’ field. - value: - Value for the ``path`` field. Will be set for - actions:‘add’/‘replace’. Maybe set for action: ‘test’. Either - this or ``value_matcher`` will be set for ‘test’ operation. An - exact match must be performed. - value_matcher: - Can be set for action ‘test’ for advanced matching for the - value of ‘path’ field. Either this or ``value`` will be set - for ‘test’ operation. - path_filters: - Set of filters to apply if ``path`` refers to array elements - or nested array elements in order to narrow down to a single - unique element that is being tested/modified. This is intended - to be an exact match per filter. To perform advanced matching, - use path_value_matchers. - Example: ``{ “/versions/*/name" : - "it-123" "/versions/*/targetSize/percent”: 20 }`` - Example: - { “/bindings/*/role": "roles/admin" "/bindings/*/condition” - : null } - Example: ``{ "/bindings/*/role“:”roles/admin" - “/bindings/*/members/*” : [“x@google.com”, “y@google.com”] - }`` When both path_filters and path_value_matchers are set, - an implicit AND must be performed. - path_value_matchers: - Similar to path_filters, this contains set of filters to apply - if ``path`` field referes to array elements. This is meant to - support value matching beyond exact match. To perform exact - match, use path_filters. When both path_filters and - path_value_matchers are set, an implicit AND must be - performed. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.Operation) - }, -) -_sym_db.RegisterMessage(Operation) -_sym_db.RegisterMessage(Operation.PathFiltersEntry) -_sym_db.RegisterMessage(Operation.PathValueMatchersEntry) - -ValueMatcher = _reflection.GeneratedProtocolMessageType( - "ValueMatcher", - (_message.Message,), - { - "DESCRIPTOR": _VALUEMATCHER, - "__module__": "google.cloud.recommender_v1beta1.proto.recommendation_pb2", - "__doc__": """Contains various matching options for values for a GCP resource field. - - Attributes: - matches_pattern: - To be used for full regex matching. The regular expression is - using the Google RE2 syntax - (https://github.com/google/re2/wiki/Syntax), so to be used - with RE2::FullMatch - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.ValueMatcher) - }, -) -_sym_db.RegisterMessage(ValueMatcher) - -CostProjection = _reflection.GeneratedProtocolMessageType( - "CostProjection", - (_message.Message,), - { - "DESCRIPTOR": _COSTPROJECTION, - "__module__": "google.cloud.recommender_v1beta1.proto.recommendation_pb2", - "__doc__": """Contains metadata about how much money a recommendation can save or - incur. - - Attributes: - cost: - An approximate projection on amount saved or amount incurred. - Negative cost units indicate cost savings and positive cost - units indicate increase. See google.type.Money documentation - for positive/negative units. - duration: - Duration for which this cost applies. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.CostProjection) - }, -) -_sym_db.RegisterMessage(CostProjection) - -Impact = _reflection.GeneratedProtocolMessageType( - "Impact", - (_message.Message,), - { - "DESCRIPTOR": _IMPACT, - "__module__": "google.cloud.recommender_v1beta1.proto.recommendation_pb2", - "__doc__": """Contains the impact a recommendation can have for a given category. - - Attributes: - category: - Category that is being targeted. - projection: - Contains projections (if any) for this category. - cost_projection: - Use with CategoryType.COST - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.Impact) - }, -) -_sym_db.RegisterMessage(Impact) - -RecommendationStateInfo = _reflection.GeneratedProtocolMessageType( - "RecommendationStateInfo", - (_message.Message,), - { - "StateMetadataEntry": _reflection.GeneratedProtocolMessageType( - "StateMetadataEntry", - (_message.Message,), - { - "DESCRIPTOR": _RECOMMENDATIONSTATEINFO_STATEMETADATAENTRY, - "__module__": "google.cloud.recommender_v1beta1.proto.recommendation_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.RecommendationStateInfo.StateMetadataEntry) - }, - ), - "DESCRIPTOR": _RECOMMENDATIONSTATEINFO, - "__module__": "google.cloud.recommender_v1beta1.proto.recommendation_pb2", - "__doc__": """Information for state. Contains state and metadata. - - Attributes: - state: - The state of the recommendation, Eg ACTIVE, SUCCEEDED, FAILED. - state_metadata: - A map of metadata for the state, provided by user or - automations systems. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.RecommendationStateInfo) - }, -) -_sym_db.RegisterMessage(RecommendationStateInfo) -_sym_db.RegisterMessage(RecommendationStateInfo.StateMetadataEntry) - - -DESCRIPTOR._options = None -_RECOMMENDATION._options = None -_OPERATION_PATHFILTERSENTRY._options = None -_OPERATION_PATHVALUEMATCHERSENTRY._options = None -_RECOMMENDATIONSTATEINFO_STATEMETADATAENTRY._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/recommender_v1beta1/proto/recommendation_pb2_grpc.py b/google/cloud/recommender_v1beta1/proto/recommendation_pb2_grpc.py deleted file mode 100644 index 8a93939..0000000 --- a/google/cloud/recommender_v1beta1/proto/recommendation_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/recommender_v1beta1/proto/recommender_service.proto b/google/cloud/recommender_v1beta1/proto/recommender_service.proto deleted file mode 100644 index 49a076a..0000000 --- a/google/cloud/recommender_v1beta1/proto/recommender_service.proto +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -syntax = "proto3"; - -package google.cloud.recommender.v1beta1; - -import "google/api/annotations.proto"; -import "google/cloud/recommender/v1beta1/recommendation.proto"; -import "google/longrunning/operations.proto"; -import "google/api/client.proto"; - -option csharp_namespace = "Google.Cloud.Recommmender.V1Beta1"; -option go_package = "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1;recommender"; -option java_multiple_files = true; -option java_outer_classname = "RecommenderProto"; -option java_package = "com.google.cloud.recommender.v1beta1"; -option objc_class_prefix = "CREC"; - -// Provides recommendations for cloud customers for various categories like -// performance optimization, cost savings, reliability, feature discovery, etc. -// These recommendations are generated automatically based on analysis of user -// resources, configuration and monitoring metrics. -service Recommender { - option (google.api.default_host) = "recommender.googleapis.com"; - option (google.api.oauth_scopes) = "https://www.googleapis.com/auth/cloud-platform"; - - // Lists recommendations for a Cloud project. Requires the recommender.*.list - // IAM permission for the specified recommender. - rpc ListRecommendations(ListRecommendationsRequest) returns (ListRecommendationsResponse) { - option (google.api.http) = { - get: "/v1beta1/{parent=projects/*/locations/*/recommenders/*}/recommendations" - }; - } - - // Gets the requested recommendation. Requires the recommender.*.get - // IAM permission for the specified recommender. - rpc GetRecommendation(GetRecommendationRequest) returns (Recommendation) { - option (google.api.http) = { - get: "/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}" - }; - } - - // Mark the Recommendation State as Claimed. Users can use this method to - // indicate to the Recommender API that they are starting to apply the - // recommendation themselves. This stops the recommendation content from being - // updated. - // - // MarkRecommendationClaimed can be applied to recommendations in CLAIMED, - // SUCCEEDED, FAILED, or ACTIVE state. - // - // Requires the recommender.*.update IAM permission for the specified - // recommender. - rpc MarkRecommendationClaimed(MarkRecommendationClaimedRequest) returns (Recommendation) { - option (google.api.http) = { - post: "/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markClaimed" - body: "*" - }; - } - - // Mark the Recommendation State as Succeeded. Users can use this method to - // indicate to the Recommender API that they have applied the recommendation - // themselves, and the operation was successful. This stops the recommendation - // content from being updated. - // - // MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, - // CLAIMED, SUCCEEDED, or FAILED state. - // - // Requires the recommender.*.update IAM permission for the specified - // recommender. - rpc MarkRecommendationSucceeded(MarkRecommendationSucceededRequest) returns (Recommendation) { - option (google.api.http) = { - post: "/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markSucceeded" - body: "*" - }; - } - - // Mark the Recommendation State as Failed. Users can use this method to - // indicate to the Recommender API that they have applied the recommendation - // themselves, and the operation failed. This stops the recommendation content - // from being updated. - // - // MarkRecommendationFailed can be applied to recommendations in ACTIVE, - // CLAIMED, SUCCEEDED, or FAILED state. - // - // Requires the recommender.*.update IAM permission for the specified - // recommender. - rpc MarkRecommendationFailed(MarkRecommendationFailedRequest) returns (Recommendation) { - option (google.api.http) = { - post: "/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markFailed" - body: "*" - }; - } -} - -// Request for the `ListRecommendations` method. -message ListRecommendationsRequest { - // Required. The container resource on which to execute the request. - // Acceptable formats: - // - // 1. - // "projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]", - // - // LOCATION here refers to GCP Locations: - // https://cloud.google.com/about/locations/ - string parent = 1; - - // Optional. The maximum number of results to return from this request. - // Non-positive values are ignored. If not specified, the server will - // determine the number of results to return. - int32 page_size = 2; - - // Optional. If present, retrieves the next batch of results from the - // preceding call to this method. `page_token` must be the value of - // `next_page_token` from the previous response. The values of other method - // parameters must be identical to those in the previous call. - string page_token = 3; - - // Filter expression to restrict the recommendations returned. Supported - // filter fields: state_info.state - // Eg: `state_info.state:"DISMISSED" or state_info.state:"FAILED" - string filter = 5; -} - -// Response to the `ListRecommendations` method. -message ListRecommendationsResponse { - // The set of recommendations for the `parent` resource. - repeated Recommendation recommendations = 1; - - // A token that can be used to request the next page of results. This field is - // empty if there are no additional results. - string next_page_token = 2; -} - -// Request to the `GetRecommendation` method. -message GetRecommendationRequest { - // Name of the recommendation. - string name = 1; -} - -// Request for the `MarkRecommendationClaimed` Method. -message MarkRecommendationClaimedRequest { - // Name of the recommendation. - string name = 1; - - // State properties to include with this state. Overwrites any existing - // `state_metadata`. - map state_metadata = 2; - - // Fingerprint of the Recommendation. Provides optimistic locking. - string etag = 3; -} - -// Request for the `MarkRecommendationSucceeded` Method. -message MarkRecommendationSucceededRequest { - // Name of the recommendation. - string name = 1; - - // State properties to include with this state. Overwrites any existing - // `state_metadata`. - map state_metadata = 2; - - // Fingerprint of the Recommendation. Provides optimistic locking. - string etag = 3; -} - -// Request for the `MarkRecommendationFailed` Method. -message MarkRecommendationFailedRequest { - // Name of the recommendation. - string name = 1; - - // State properties to include with this state. Overwrites any existing - // `state_metadata`. - map state_metadata = 2; - - // Fingerprint of the Recommendation. Provides optimistic locking. - string etag = 3; -} diff --git a/google/cloud/recommender_v1beta1/proto/recommender_service_pb2.py b/google/cloud/recommender_v1beta1/proto/recommender_service_pb2.py deleted file mode 100644 index efa06d1..0000000 --- a/google/cloud/recommender_v1beta1/proto/recommender_service_pb2.py +++ /dev/null @@ -1,1471 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/recommender_v1beta1/proto/recommender_service.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.recommender_v1beta1.proto import ( - insight_pb2 as google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_insight__pb2, -) -from google.cloud.recommender_v1beta1.proto import ( - recommendation_pb2 as google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2, -) - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/recommender_v1beta1/proto/recommender_service.proto", - package="google.cloud.recommender.v1beta1", - syntax="proto3", - serialized_options=b"\n$com.google.cloud.recommender.v1beta1B\020RecommenderProtoP\001ZKgoogle.golang.org/genproto/googleapis/cloud/recommender/v1beta1;recommender\242\002\004CREC\252\002 Google.Cloud.Recommender.V1Beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n@google/cloud/recommender_v1beta1/proto/recommender_service.proto\x12 google.cloud.recommender.v1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x34google/cloud/recommender_v1beta1/proto/insight.proto\x1a;google/cloud/recommender_v1beta1/proto/recommendation.proto"\x9b\x01\n\x13ListInsightsRequest\x12>\n\x06parent\x18\x01 \x01(\tB.\xe0\x41\x02\xfa\x41(\n&recommender.googleapis.com/InsightType\x12\x16\n\tpage_size\x18\x02 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x03 \x01(\tB\x03\xe0\x41\x01\x12\x13\n\x06\x66ilter\x18\x04 \x01(\tB\x03\xe0\x41\x01"l\n\x14ListInsightsResponse\x12;\n\x08insights\x18\x01 \x03(\x0b\x32).google.cloud.recommender.v1beta1.Insight\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"M\n\x11GetInsightRequest\x12\x38\n\x04name\x18\x01 \x01(\tB*\xe0\x41\x02\xfa\x41$\n"recommender.googleapis.com/Insight"\x8d\x02\n\x1aMarkInsightAcceptedRequest\x12\x38\n\x04name\x18\x01 \x01(\tB*\xe0\x41\x02\xfa\x41$\n"recommender.googleapis.com/Insight\x12l\n\x0estate_metadata\x18\x02 \x03(\x0b\x32O.google.cloud.recommender.v1beta1.MarkInsightAcceptedRequest.StateMetadataEntryB\x03\xe0\x41\x01\x12\x11\n\x04\x65tag\x18\x03 \x01(\tB\x03\xe0\x41\x02\x1a\x34\n\x12StateMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\x9d\x01\n\x1aListRecommendationsRequest\x12>\n\x06parent\x18\x01 \x01(\tB.\xe0\x41\x02\xfa\x41(\n&recommender.googleapis.com/Recommender\x12\x16\n\tpage_size\x18\x02 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x03 \x01(\tB\x03\xe0\x41\x01\x12\x0e\n\x06\x66ilter\x18\x05 \x01(\t"\x81\x01\n\x1bListRecommendationsResponse\x12I\n\x0frecommendations\x18\x01 \x03(\x0b\x32\x30.google.cloud.recommender.v1beta1.Recommendation\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"[\n\x18GetRecommendationRequest\x12?\n\x04name\x18\x01 \x01(\tB1\xe0\x41\x02\xfa\x41+\n)recommender.googleapis.com/Recommendation"\x9b\x02\n MarkRecommendationClaimedRequest\x12?\n\x04name\x18\x01 \x01(\tB1\xe0\x41\x02\xfa\x41+\n)recommender.googleapis.com/Recommendation\x12m\n\x0estate_metadata\x18\x02 \x03(\x0b\x32U.google.cloud.recommender.v1beta1.MarkRecommendationClaimedRequest.StateMetadataEntry\x12\x11\n\x04\x65tag\x18\x03 \x01(\tB\x03\xe0\x41\x02\x1a\x34\n\x12StateMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\x9f\x02\n"MarkRecommendationSucceededRequest\x12?\n\x04name\x18\x01 \x01(\tB1\xe0\x41\x02\xfa\x41+\n)recommender.googleapis.com/Recommendation\x12o\n\x0estate_metadata\x18\x02 \x03(\x0b\x32W.google.cloud.recommender.v1beta1.MarkRecommendationSucceededRequest.StateMetadataEntry\x12\x11\n\x04\x65tag\x18\x03 \x01(\tB\x03\xe0\x41\x02\x1a\x34\n\x12StateMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\x99\x02\n\x1fMarkRecommendationFailedRequest\x12?\n\x04name\x18\x01 \x01(\tB1\xe0\x41\x02\xfa\x41+\n)recommender.googleapis.com/Recommendation\x12l\n\x0estate_metadata\x18\x02 \x03(\x0b\x32T.google.cloud.recommender.v1beta1.MarkRecommendationFailedRequest.StateMetadataEntry\x12\x11\n\x04\x65tag\x18\x03 \x01(\tB\x03\xe0\x41\x02\x1a\x34\n\x12StateMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x32\xe8\x0f\n\x0bRecommender\x12\xd0\x01\n\x0cListInsights\x12\x35.google.cloud.recommender.v1beta1.ListInsightsRequest\x1a\x36.google.cloud.recommender.v1beta1.ListInsightsResponse"Q\x82\xd3\xe4\x93\x02\x42\x12@/v1beta1/{parent=projects/*/locations/*/insightTypes/*}/insights\xda\x41\x06parent\x12\xbd\x01\n\nGetInsight\x12\x33.google.cloud.recommender.v1beta1.GetInsightRequest\x1a).google.cloud.recommender.v1beta1.Insight"O\x82\xd3\xe4\x93\x02\x42\x12@/v1beta1/{name=projects/*/locations/*/insightTypes/*/insights/*}\xda\x41\x04name\x12\xf3\x01\n\x13MarkInsightAccepted\x12<.google.cloud.recommender.v1beta1.MarkInsightAcceptedRequest\x1a).google.cloud.recommender.v1beta1.Insight"s\x82\xd3\xe4\x93\x02R"M/v1beta1/{name=projects/*/locations/*/insightTypes/*/insights/*}:markAccepted:\x01*\xda\x41\x18name,state_metadata,etag\x12\xf3\x01\n\x13ListRecommendations\x12<.google.cloud.recommender.v1beta1.ListRecommendationsRequest\x1a=.google.cloud.recommender.v1beta1.ListRecommendationsResponse"_\x82\xd3\xe4\x93\x02I\x12G/v1beta1/{parent=projects/*/locations/*/recommenders/*}/recommendations\xda\x41\rparent,filter\x12\xd9\x01\n\x11GetRecommendation\x12:.google.cloud.recommender.v1beta1.GetRecommendationRequest\x1a\x30.google.cloud.recommender.v1beta1.Recommendation"V\x82\xd3\xe4\x93\x02I\x12G/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}\xda\x41\x04name\x12\x8c\x02\n\x19MarkRecommendationClaimed\x12\x42.google.cloud.recommender.v1beta1.MarkRecommendationClaimedRequest\x1a\x30.google.cloud.recommender.v1beta1.Recommendation"y\x82\xd3\xe4\x93\x02X"S/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markClaimed:\x01*\xda\x41\x18name,state_metadata,etag\x12\x92\x02\n\x1bMarkRecommendationSucceeded\x12\x44.google.cloud.recommender.v1beta1.MarkRecommendationSucceededRequest\x1a\x30.google.cloud.recommender.v1beta1.Recommendation"{\x82\xd3\xe4\x93\x02Z"U/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markSucceeded:\x01*\xda\x41\x18name,state_metadata,etag\x12\x89\x02\n\x18MarkRecommendationFailed\x12\x41.google.cloud.recommender.v1beta1.MarkRecommendationFailedRequest\x1a\x30.google.cloud.recommender.v1beta1.Recommendation"x\x82\xd3\xe4\x93\x02W"R/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markFailed:\x01*\xda\x41\x18name,state_metadata,etag\x1aN\xca\x41\x1arecommender.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\xb1\x01\n$com.google.cloud.recommender.v1beta1B\x10RecommenderProtoP\x01ZKgoogle.golang.org/genproto/googleapis/cloud/recommender/v1beta1;recommender\xa2\x02\x04\x43REC\xaa\x02 Google.Cloud.Recommender.V1Beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_insight__pb2.DESCRIPTOR, - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2.DESCRIPTOR, - ], -) - - -_LISTINSIGHTSREQUEST = _descriptor.Descriptor( - name="ListInsightsRequest", - full_name="google.cloud.recommender.v1beta1.ListInsightsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.recommender.v1beta1.ListInsightsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A(\n&recommender.googleapis.com/InsightType", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.recommender.v1beta1.ListInsightsRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.recommender.v1beta1.ListInsightsRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.recommender.v1beta1.ListInsightsRequest.filter", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=333, - serialized_end=488, -) - - -_LISTINSIGHTSRESPONSE = _descriptor.Descriptor( - name="ListInsightsResponse", - full_name="google.cloud.recommender.v1beta1.ListInsightsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="insights", - full_name="google.cloud.recommender.v1beta1.ListInsightsResponse.insights", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.recommender.v1beta1.ListInsightsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=490, - serialized_end=598, -) - - -_GETINSIGHTREQUEST = _descriptor.Descriptor( - name="GetInsightRequest", - full_name="google.cloud.recommender.v1beta1.GetInsightRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1beta1.GetInsightRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A$\n"recommender.googleapis.com/Insight', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=600, - serialized_end=677, -) - - -_MARKINSIGHTACCEPTEDREQUEST_STATEMETADATAENTRY = _descriptor.Descriptor( - name="StateMetadataEntry", - full_name="google.cloud.recommender.v1beta1.MarkInsightAcceptedRequest.StateMetadataEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1beta1.MarkInsightAcceptedRequest.StateMetadataEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1beta1.MarkInsightAcceptedRequest.StateMetadataEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=897, - serialized_end=949, -) - -_MARKINSIGHTACCEPTEDREQUEST = _descriptor.Descriptor( - name="MarkInsightAcceptedRequest", - full_name="google.cloud.recommender.v1beta1.MarkInsightAcceptedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1beta1.MarkInsightAcceptedRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A$\n"recommender.googleapis.com/Insight', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_metadata", - full_name="google.cloud.recommender.v1beta1.MarkInsightAcceptedRequest.state_metadata", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="etag", - full_name="google.cloud.recommender.v1beta1.MarkInsightAcceptedRequest.etag", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_MARKINSIGHTACCEPTEDREQUEST_STATEMETADATAENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=680, - serialized_end=949, -) - - -_LISTRECOMMENDATIONSREQUEST = _descriptor.Descriptor( - name="ListRecommendationsRequest", - full_name="google.cloud.recommender.v1beta1.ListRecommendationsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.recommender.v1beta1.ListRecommendationsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A(\n&recommender.googleapis.com/Recommender", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.recommender.v1beta1.ListRecommendationsRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.recommender.v1beta1.ListRecommendationsRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.recommender.v1beta1.ListRecommendationsRequest.filter", - index=3, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=952, - serialized_end=1109, -) - - -_LISTRECOMMENDATIONSRESPONSE = _descriptor.Descriptor( - name="ListRecommendationsResponse", - full_name="google.cloud.recommender.v1beta1.ListRecommendationsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="recommendations", - full_name="google.cloud.recommender.v1beta1.ListRecommendationsResponse.recommendations", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.recommender.v1beta1.ListRecommendationsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1112, - serialized_end=1241, -) - - -_GETRECOMMENDATIONREQUEST = _descriptor.Descriptor( - name="GetRecommendationRequest", - full_name="google.cloud.recommender.v1beta1.GetRecommendationRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1beta1.GetRecommendationRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A+\n)recommender.googleapis.com/Recommendation", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1243, - serialized_end=1334, -) - - -_MARKRECOMMENDATIONCLAIMEDREQUEST_STATEMETADATAENTRY = _descriptor.Descriptor( - name="StateMetadataEntry", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationClaimedRequest.StateMetadataEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationClaimedRequest.StateMetadataEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationClaimedRequest.StateMetadataEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=897, - serialized_end=949, -) - -_MARKRECOMMENDATIONCLAIMEDREQUEST = _descriptor.Descriptor( - name="MarkRecommendationClaimedRequest", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationClaimedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationClaimedRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A+\n)recommender.googleapis.com/Recommendation", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_metadata", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationClaimedRequest.state_metadata", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="etag", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationClaimedRequest.etag", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_MARKRECOMMENDATIONCLAIMEDREQUEST_STATEMETADATAENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1337, - serialized_end=1620, -) - - -_MARKRECOMMENDATIONSUCCEEDEDREQUEST_STATEMETADATAENTRY = _descriptor.Descriptor( - name="StateMetadataEntry", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationSucceededRequest.StateMetadataEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationSucceededRequest.StateMetadataEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationSucceededRequest.StateMetadataEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=897, - serialized_end=949, -) - -_MARKRECOMMENDATIONSUCCEEDEDREQUEST = _descriptor.Descriptor( - name="MarkRecommendationSucceededRequest", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationSucceededRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationSucceededRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A+\n)recommender.googleapis.com/Recommendation", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_metadata", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationSucceededRequest.state_metadata", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="etag", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationSucceededRequest.etag", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_MARKRECOMMENDATIONSUCCEEDEDREQUEST_STATEMETADATAENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1623, - serialized_end=1910, -) - - -_MARKRECOMMENDATIONFAILEDREQUEST_STATEMETADATAENTRY = _descriptor.Descriptor( - name="StateMetadataEntry", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationFailedRequest.StateMetadataEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationFailedRequest.StateMetadataEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationFailedRequest.StateMetadataEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=897, - serialized_end=949, -) - -_MARKRECOMMENDATIONFAILEDREQUEST = _descriptor.Descriptor( - name="MarkRecommendationFailedRequest", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationFailedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationFailedRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A+\n)recommender.googleapis.com/Recommendation", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_metadata", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationFailedRequest.state_metadata", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="etag", - full_name="google.cloud.recommender.v1beta1.MarkRecommendationFailedRequest.etag", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_MARKRECOMMENDATIONFAILEDREQUEST_STATEMETADATAENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1913, - serialized_end=2194, -) - -_LISTINSIGHTSRESPONSE.fields_by_name[ - "insights" -].message_type = ( - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_insight__pb2._INSIGHT -) -_MARKINSIGHTACCEPTEDREQUEST_STATEMETADATAENTRY.containing_type = ( - _MARKINSIGHTACCEPTEDREQUEST -) -_MARKINSIGHTACCEPTEDREQUEST.fields_by_name[ - "state_metadata" -].message_type = _MARKINSIGHTACCEPTEDREQUEST_STATEMETADATAENTRY -_LISTRECOMMENDATIONSRESPONSE.fields_by_name[ - "recommendations" -].message_type = ( - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2._RECOMMENDATION -) -_MARKRECOMMENDATIONCLAIMEDREQUEST_STATEMETADATAENTRY.containing_type = ( - _MARKRECOMMENDATIONCLAIMEDREQUEST -) -_MARKRECOMMENDATIONCLAIMEDREQUEST.fields_by_name[ - "state_metadata" -].message_type = _MARKRECOMMENDATIONCLAIMEDREQUEST_STATEMETADATAENTRY -_MARKRECOMMENDATIONSUCCEEDEDREQUEST_STATEMETADATAENTRY.containing_type = ( - _MARKRECOMMENDATIONSUCCEEDEDREQUEST -) -_MARKRECOMMENDATIONSUCCEEDEDREQUEST.fields_by_name[ - "state_metadata" -].message_type = _MARKRECOMMENDATIONSUCCEEDEDREQUEST_STATEMETADATAENTRY -_MARKRECOMMENDATIONFAILEDREQUEST_STATEMETADATAENTRY.containing_type = ( - _MARKRECOMMENDATIONFAILEDREQUEST -) -_MARKRECOMMENDATIONFAILEDREQUEST.fields_by_name[ - "state_metadata" -].message_type = _MARKRECOMMENDATIONFAILEDREQUEST_STATEMETADATAENTRY -DESCRIPTOR.message_types_by_name["ListInsightsRequest"] = _LISTINSIGHTSREQUEST -DESCRIPTOR.message_types_by_name["ListInsightsResponse"] = _LISTINSIGHTSRESPONSE -DESCRIPTOR.message_types_by_name["GetInsightRequest"] = _GETINSIGHTREQUEST -DESCRIPTOR.message_types_by_name[ - "MarkInsightAcceptedRequest" -] = _MARKINSIGHTACCEPTEDREQUEST -DESCRIPTOR.message_types_by_name[ - "ListRecommendationsRequest" -] = _LISTRECOMMENDATIONSREQUEST -DESCRIPTOR.message_types_by_name[ - "ListRecommendationsResponse" -] = _LISTRECOMMENDATIONSRESPONSE -DESCRIPTOR.message_types_by_name["GetRecommendationRequest"] = _GETRECOMMENDATIONREQUEST -DESCRIPTOR.message_types_by_name[ - "MarkRecommendationClaimedRequest" -] = _MARKRECOMMENDATIONCLAIMEDREQUEST -DESCRIPTOR.message_types_by_name[ - "MarkRecommendationSucceededRequest" -] = _MARKRECOMMENDATIONSUCCEEDEDREQUEST -DESCRIPTOR.message_types_by_name[ - "MarkRecommendationFailedRequest" -] = _MARKRECOMMENDATIONFAILEDREQUEST -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -ListInsightsRequest = _reflection.GeneratedProtocolMessageType( - "ListInsightsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTINSIGHTSREQUEST, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2", - "__doc__": """Request for the ``ListInsights`` method. - - Attributes: - parent: - Required. The container resource on which to execute the - request. Acceptable formats: 1. “projects/[PROJECT_NUMBER]/lo - cations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]”, LOCATION - here refers to GCP Locations: - https://cloud.google.com/about/locations/ - page_size: - Optional. The maximum number of results to return from this - request. Non-positive values are ignored. If not specified, - the server will determine the number of results to return. - page_token: - Optional. If present, retrieves the next batch of results from - the preceding call to this method. ``page_token`` must be the - value of ``next_page_token`` from the previous response. The - values of other method parameters must be identical to those - in the previous call. - filter: - Optional. Filter expression to restrict the insights returned. - Supported filter fields: state Eg: \`state:“DISMISSED” or - state:“ACTIVE” .. [1] a-z0-9 .. [2] a-z0-9 .. [3] - a-z0-9 - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.ListInsightsRequest) - }, -) -_sym_db.RegisterMessage(ListInsightsRequest) - -ListInsightsResponse = _reflection.GeneratedProtocolMessageType( - "ListInsightsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTINSIGHTSRESPONSE, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2", - "__doc__": """Response to the ``ListInsights`` method. - - Attributes: - insights: - The set of insights for the ``parent`` resource. - next_page_token: - A token that can be used to request the next page of results. - This field is empty if there are no additional results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.ListInsightsResponse) - }, -) -_sym_db.RegisterMessage(ListInsightsResponse) - -GetInsightRequest = _reflection.GeneratedProtocolMessageType( - "GetInsightRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETINSIGHTREQUEST, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2", - "__doc__": """Request to the ``GetInsight`` method. - - Attributes: - name: - Required. Name of the insight. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.GetInsightRequest) - }, -) -_sym_db.RegisterMessage(GetInsightRequest) - -MarkInsightAcceptedRequest = _reflection.GeneratedProtocolMessageType( - "MarkInsightAcceptedRequest", - (_message.Message,), - { - "StateMetadataEntry": _reflection.GeneratedProtocolMessageType( - "StateMetadataEntry", - (_message.Message,), - { - "DESCRIPTOR": _MARKINSIGHTACCEPTEDREQUEST_STATEMETADATAENTRY, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.MarkInsightAcceptedRequest.StateMetadataEntry) - }, - ), - "DESCRIPTOR": _MARKINSIGHTACCEPTEDREQUEST, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2", - "__doc__": """Request for the ``MarkInsightAccepted`` method. - - Attributes: - name: - Required. Name of the insight. - state_metadata: - Optional. State properties user wish to include with this - state. Full replace of the current state_metadata. - etag: - Required. Fingerprint of the Insight. Provides optimistic - locking. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.MarkInsightAcceptedRequest) - }, -) -_sym_db.RegisterMessage(MarkInsightAcceptedRequest) -_sym_db.RegisterMessage(MarkInsightAcceptedRequest.StateMetadataEntry) - -ListRecommendationsRequest = _reflection.GeneratedProtocolMessageType( - "ListRecommendationsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTRECOMMENDATIONSREQUEST, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2", - "__doc__": """Request for the ``ListRecommendations`` method. - - Attributes: - parent: - Required. The container resource on which to execute the - request. Acceptable formats: 1. “projects/[PROJECT_NUMBER]/lo - cations/[LOCATION]/recommenders/[RECOMMENDER_ID]”, LOCATION - here refers to GCP Locations: - https://cloud.google.com/about/locations/ - page_size: - Optional. The maximum number of results to return from this - request. Non-positive values are ignored. If not specified, - the server will determine the number of results to return. - page_token: - Optional. If present, retrieves the next batch of results from - the preceding call to this method. ``page_token`` must be the - value of ``next_page_token`` from the previous response. The - values of other method parameters must be identical to those - in the previous call. - filter: - Filter expression to restrict the recommendations returned. - Supported filter fields: state_info.state Eg: - \`state_info.state:“DISMISSED” or state_info.state:“FAILED” - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.ListRecommendationsRequest) - }, -) -_sym_db.RegisterMessage(ListRecommendationsRequest) - -ListRecommendationsResponse = _reflection.GeneratedProtocolMessageType( - "ListRecommendationsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTRECOMMENDATIONSRESPONSE, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2", - "__doc__": """Response to the ``ListRecommendations`` method. - - Attributes: - recommendations: - The set of recommendations for the ``parent`` resource. - next_page_token: - A token that can be used to request the next page of results. - This field is empty if there are no additional results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.ListRecommendationsResponse) - }, -) -_sym_db.RegisterMessage(ListRecommendationsResponse) - -GetRecommendationRequest = _reflection.GeneratedProtocolMessageType( - "GetRecommendationRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETRECOMMENDATIONREQUEST, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2", - "__doc__": """Request to the ``GetRecommendation`` method. - - Attributes: - name: - Required. Name of the recommendation. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.GetRecommendationRequest) - }, -) -_sym_db.RegisterMessage(GetRecommendationRequest) - -MarkRecommendationClaimedRequest = _reflection.GeneratedProtocolMessageType( - "MarkRecommendationClaimedRequest", - (_message.Message,), - { - "StateMetadataEntry": _reflection.GeneratedProtocolMessageType( - "StateMetadataEntry", - (_message.Message,), - { - "DESCRIPTOR": _MARKRECOMMENDATIONCLAIMEDREQUEST_STATEMETADATAENTRY, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.MarkRecommendationClaimedRequest.StateMetadataEntry) - }, - ), - "DESCRIPTOR": _MARKRECOMMENDATIONCLAIMEDREQUEST, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2", - "__doc__": """Request for the ``MarkRecommendationClaimed`` Method. - - Attributes: - name: - Required. Name of the recommendation. - state_metadata: - State properties to include with this state. Overwrites any - existing ``state_metadata``. Keys must match the regex ``/ - [1]_[a-z0-9_.-]{0,62}/``. Values must match the regex - ``/^[a-zA-Z0-9_./-]{0,255}/``. - etag: - Required. Fingerprint of the Recommendation. Provides - optimistic locking. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.MarkRecommendationClaimedRequest) - }, -) -_sym_db.RegisterMessage(MarkRecommendationClaimedRequest) -_sym_db.RegisterMessage(MarkRecommendationClaimedRequest.StateMetadataEntry) - -MarkRecommendationSucceededRequest = _reflection.GeneratedProtocolMessageType( - "MarkRecommendationSucceededRequest", - (_message.Message,), - { - "StateMetadataEntry": _reflection.GeneratedProtocolMessageType( - "StateMetadataEntry", - (_message.Message,), - { - "DESCRIPTOR": _MARKRECOMMENDATIONSUCCEEDEDREQUEST_STATEMETADATAENTRY, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.MarkRecommendationSucceededRequest.StateMetadataEntry) - }, - ), - "DESCRIPTOR": _MARKRECOMMENDATIONSUCCEEDEDREQUEST, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2", - "__doc__": """Request for the ``MarkRecommendationSucceeded`` Method. - - Attributes: - name: - Required. Name of the recommendation. - state_metadata: - State properties to include with this state. Overwrites any - existing ``state_metadata``. Keys must match the regex ``/ - [2]_[a-z0-9_.-]{0,62}/``. Values must match the regex - ``/^[a-zA-Z0-9_./-]{0,255}/``. - etag: - Required. Fingerprint of the Recommendation. Provides - optimistic locking. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.MarkRecommendationSucceededRequest) - }, -) -_sym_db.RegisterMessage(MarkRecommendationSucceededRequest) -_sym_db.RegisterMessage(MarkRecommendationSucceededRequest.StateMetadataEntry) - -MarkRecommendationFailedRequest = _reflection.GeneratedProtocolMessageType( - "MarkRecommendationFailedRequest", - (_message.Message,), - { - "StateMetadataEntry": _reflection.GeneratedProtocolMessageType( - "StateMetadataEntry", - (_message.Message,), - { - "DESCRIPTOR": _MARKRECOMMENDATIONFAILEDREQUEST_STATEMETADATAENTRY, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.MarkRecommendationFailedRequest.StateMetadataEntry) - }, - ), - "DESCRIPTOR": _MARKRECOMMENDATIONFAILEDREQUEST, - "__module__": "google.cloud.recommender_v1beta1.proto.recommender_service_pb2", - "__doc__": """Request for the ``MarkRecommendationFailed`` Method. - - Attributes: - name: - Required. Name of the recommendation. - state_metadata: - State properties to include with this state. Overwrites any - existing ``state_metadata``. Keys must match the regex ``/ - [3]_[a-z0-9_.-]{0,62}/``. Values must match the regex - ``/^[a-zA-Z0-9_./-]{0,255}/``. - etag: - Required. Fingerprint of the Recommendation. Provides - optimistic locking. - """, - # @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.MarkRecommendationFailedRequest) - }, -) -_sym_db.RegisterMessage(MarkRecommendationFailedRequest) -_sym_db.RegisterMessage(MarkRecommendationFailedRequest.StateMetadataEntry) - - -DESCRIPTOR._options = None -_LISTINSIGHTSREQUEST.fields_by_name["parent"]._options = None -_LISTINSIGHTSREQUEST.fields_by_name["page_size"]._options = None -_LISTINSIGHTSREQUEST.fields_by_name["page_token"]._options = None -_LISTINSIGHTSREQUEST.fields_by_name["filter"]._options = None -_GETINSIGHTREQUEST.fields_by_name["name"]._options = None -_MARKINSIGHTACCEPTEDREQUEST_STATEMETADATAENTRY._options = None -_MARKINSIGHTACCEPTEDREQUEST.fields_by_name["name"]._options = None -_MARKINSIGHTACCEPTEDREQUEST.fields_by_name["state_metadata"]._options = None -_MARKINSIGHTACCEPTEDREQUEST.fields_by_name["etag"]._options = None -_LISTRECOMMENDATIONSREQUEST.fields_by_name["parent"]._options = None -_LISTRECOMMENDATIONSREQUEST.fields_by_name["page_size"]._options = None -_LISTRECOMMENDATIONSREQUEST.fields_by_name["page_token"]._options = None -_GETRECOMMENDATIONREQUEST.fields_by_name["name"]._options = None -_MARKRECOMMENDATIONCLAIMEDREQUEST_STATEMETADATAENTRY._options = None -_MARKRECOMMENDATIONCLAIMEDREQUEST.fields_by_name["name"]._options = None -_MARKRECOMMENDATIONCLAIMEDREQUEST.fields_by_name["etag"]._options = None -_MARKRECOMMENDATIONSUCCEEDEDREQUEST_STATEMETADATAENTRY._options = None -_MARKRECOMMENDATIONSUCCEEDEDREQUEST.fields_by_name["name"]._options = None -_MARKRECOMMENDATIONSUCCEEDEDREQUEST.fields_by_name["etag"]._options = None -_MARKRECOMMENDATIONFAILEDREQUEST_STATEMETADATAENTRY._options = None -_MARKRECOMMENDATIONFAILEDREQUEST.fields_by_name["name"]._options = None -_MARKRECOMMENDATIONFAILEDREQUEST.fields_by_name["etag"]._options = None - -_RECOMMENDER = _descriptor.ServiceDescriptor( - name="Recommender", - full_name="google.cloud.recommender.v1beta1.Recommender", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\032recommender.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", - create_key=_descriptor._internal_create_key, - serialized_start=2197, - serialized_end=4221, - methods=[ - _descriptor.MethodDescriptor( - name="ListInsights", - full_name="google.cloud.recommender.v1beta1.Recommender.ListInsights", - index=0, - containing_service=None, - input_type=_LISTINSIGHTSREQUEST, - output_type=_LISTINSIGHTSRESPONSE, - serialized_options=b"\202\323\344\223\002B\022@/v1beta1/{parent=projects/*/locations/*/insightTypes/*}/insights\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetInsight", - full_name="google.cloud.recommender.v1beta1.Recommender.GetInsight", - index=1, - containing_service=None, - input_type=_GETINSIGHTREQUEST, - output_type=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_insight__pb2._INSIGHT, - serialized_options=b"\202\323\344\223\002B\022@/v1beta1/{name=projects/*/locations/*/insightTypes/*/insights/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="MarkInsightAccepted", - full_name="google.cloud.recommender.v1beta1.Recommender.MarkInsightAccepted", - index=2, - containing_service=None, - input_type=_MARKINSIGHTACCEPTEDREQUEST, - output_type=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_insight__pb2._INSIGHT, - serialized_options=b'\202\323\344\223\002R"M/v1beta1/{name=projects/*/locations/*/insightTypes/*/insights/*}:markAccepted:\001*\332A\030name,state_metadata,etag', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListRecommendations", - full_name="google.cloud.recommender.v1beta1.Recommender.ListRecommendations", - index=3, - containing_service=None, - input_type=_LISTRECOMMENDATIONSREQUEST, - output_type=_LISTRECOMMENDATIONSRESPONSE, - serialized_options=b"\202\323\344\223\002I\022G/v1beta1/{parent=projects/*/locations/*/recommenders/*}/recommendations\332A\rparent,filter", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetRecommendation", - full_name="google.cloud.recommender.v1beta1.Recommender.GetRecommendation", - index=4, - containing_service=None, - input_type=_GETRECOMMENDATIONREQUEST, - output_type=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2._RECOMMENDATION, - serialized_options=b"\202\323\344\223\002I\022G/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="MarkRecommendationClaimed", - full_name="google.cloud.recommender.v1beta1.Recommender.MarkRecommendationClaimed", - index=5, - containing_service=None, - input_type=_MARKRECOMMENDATIONCLAIMEDREQUEST, - output_type=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2._RECOMMENDATION, - serialized_options=b'\202\323\344\223\002X"S/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markClaimed:\001*\332A\030name,state_metadata,etag', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="MarkRecommendationSucceeded", - full_name="google.cloud.recommender.v1beta1.Recommender.MarkRecommendationSucceeded", - index=6, - containing_service=None, - input_type=_MARKRECOMMENDATIONSUCCEEDEDREQUEST, - output_type=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2._RECOMMENDATION, - serialized_options=b'\202\323\344\223\002Z"U/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markSucceeded:\001*\332A\030name,state_metadata,etag', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="MarkRecommendationFailed", - full_name="google.cloud.recommender.v1beta1.Recommender.MarkRecommendationFailed", - index=7, - containing_service=None, - input_type=_MARKRECOMMENDATIONFAILEDREQUEST, - output_type=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2._RECOMMENDATION, - serialized_options=b'\202\323\344\223\002W"R/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markFailed:\001*\332A\030name,state_metadata,etag', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_RECOMMENDER) - -DESCRIPTOR.services_by_name["Recommender"] = _RECOMMENDER - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/recommender_v1beta1/proto/recommender_service_pb2_grpc.py b/google/cloud/recommender_v1beta1/proto/recommender_service_pb2_grpc.py deleted file mode 100644 index dab9ad0..0000000 --- a/google/cloud/recommender_v1beta1/proto/recommender_service_pb2_grpc.py +++ /dev/null @@ -1,460 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.recommender_v1beta1.proto import ( - insight_pb2 as google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_insight__pb2, -) -from google.cloud.recommender_v1beta1.proto import ( - recommendation_pb2 as google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2, -) -from google.cloud.recommender_v1beta1.proto import ( - recommender_service_pb2 as google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2, -) - - -class RecommenderStub(object): - """Provides insights and recommendations for cloud customers for various - categories like performance optimization, cost savings, reliability, feature - discovery, etc. Insights and recommendations are generated automatically - based on analysis of user resources, configuration and monitoring metrics. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.ListInsights = channel.unary_unary( - "/google.cloud.recommender.v1beta1.Recommender/ListInsights", - request_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.ListInsightsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.ListInsightsResponse.FromString, - ) - self.GetInsight = channel.unary_unary( - "/google.cloud.recommender.v1beta1.Recommender/GetInsight", - request_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.GetInsightRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_insight__pb2.Insight.FromString, - ) - self.MarkInsightAccepted = channel.unary_unary( - "/google.cloud.recommender.v1beta1.Recommender/MarkInsightAccepted", - request_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.MarkInsightAcceptedRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_insight__pb2.Insight.FromString, - ) - self.ListRecommendations = channel.unary_unary( - "/google.cloud.recommender.v1beta1.Recommender/ListRecommendations", - request_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.ListRecommendationsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.ListRecommendationsResponse.FromString, - ) - self.GetRecommendation = channel.unary_unary( - "/google.cloud.recommender.v1beta1.Recommender/GetRecommendation", - request_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.GetRecommendationRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - ) - self.MarkRecommendationClaimed = channel.unary_unary( - "/google.cloud.recommender.v1beta1.Recommender/MarkRecommendationClaimed", - request_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.MarkRecommendationClaimedRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - ) - self.MarkRecommendationSucceeded = channel.unary_unary( - "/google.cloud.recommender.v1beta1.Recommender/MarkRecommendationSucceeded", - request_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.MarkRecommendationSucceededRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - ) - self.MarkRecommendationFailed = channel.unary_unary( - "/google.cloud.recommender.v1beta1.Recommender/MarkRecommendationFailed", - request_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.MarkRecommendationFailedRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - ) - - -class RecommenderServicer(object): - """Provides insights and recommendations for cloud customers for various - categories like performance optimization, cost savings, reliability, feature - discovery, etc. Insights and recommendations are generated automatically - based on analysis of user resources, configuration and monitoring metrics. - """ - - def ListInsights(self, request, context): - """Lists insights for a Cloud project. Requires the recommender.*.list IAM - permission for the specified insight type. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetInsight(self, request, context): - """Gets the requested insight. Requires the recommender.*.get IAM permission - for the specified insight type. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def MarkInsightAccepted(self, request, context): - """Marks the Insight State as Accepted. Users can use this method to - indicate to the Recommender API that they have applied some action based - on the insight. This stops the insight content from being updated. - - MarkInsightAccepted can be applied to insights in ACTIVE state. Requires - the recommender.*.update IAM permission for the specified insight. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListRecommendations(self, request, context): - """Lists recommendations for a Cloud project. Requires the recommender.*.list - IAM permission for the specified recommender. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetRecommendation(self, request, context): - """Gets the requested recommendation. Requires the recommender.*.get - IAM permission for the specified recommender. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def MarkRecommendationClaimed(self, request, context): - """Marks the Recommendation State as Claimed. Users can use this method to - indicate to the Recommender API that they are starting to apply the - recommendation themselves. This stops the recommendation content from being - updated. Associated insights are frozen and placed in the ACCEPTED state. - - MarkRecommendationClaimed can be applied to recommendations in CLAIMED or - ACTIVE state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def MarkRecommendationSucceeded(self, request, context): - """Marks the Recommendation State as Succeeded. Users can use this method to - indicate to the Recommender API that they have applied the recommendation - themselves, and the operation was successful. This stops the recommendation - content from being updated. Associated insights are frozen and placed in - the ACCEPTED state. - - MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, - CLAIMED, SUCCEEDED, or FAILED state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def MarkRecommendationFailed(self, request, context): - """Marks the Recommendation State as Failed. Users can use this method to - indicate to the Recommender API that they have applied the recommendation - themselves, and the operation failed. This stops the recommendation content - from being updated. Associated insights are frozen and placed in the - ACCEPTED state. - - MarkRecommendationFailed can be applied to recommendations in ACTIVE, - CLAIMED, SUCCEEDED, or FAILED state. - - Requires the recommender.*.update IAM permission for the specified - recommender. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_RecommenderServicer_to_server(servicer, server): - rpc_method_handlers = { - "ListInsights": grpc.unary_unary_rpc_method_handler( - servicer.ListInsights, - request_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.ListInsightsRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.ListInsightsResponse.SerializeToString, - ), - "GetInsight": grpc.unary_unary_rpc_method_handler( - servicer.GetInsight, - request_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.GetInsightRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_insight__pb2.Insight.SerializeToString, - ), - "MarkInsightAccepted": grpc.unary_unary_rpc_method_handler( - servicer.MarkInsightAccepted, - request_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.MarkInsightAcceptedRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_insight__pb2.Insight.SerializeToString, - ), - "ListRecommendations": grpc.unary_unary_rpc_method_handler( - servicer.ListRecommendations, - request_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.ListRecommendationsRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.ListRecommendationsResponse.SerializeToString, - ), - "GetRecommendation": grpc.unary_unary_rpc_method_handler( - servicer.GetRecommendation, - request_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.GetRecommendationRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2.Recommendation.SerializeToString, - ), - "MarkRecommendationClaimed": grpc.unary_unary_rpc_method_handler( - servicer.MarkRecommendationClaimed, - request_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.MarkRecommendationClaimedRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2.Recommendation.SerializeToString, - ), - "MarkRecommendationSucceeded": grpc.unary_unary_rpc_method_handler( - servicer.MarkRecommendationSucceeded, - request_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.MarkRecommendationSucceededRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2.Recommendation.SerializeToString, - ), - "MarkRecommendationFailed": grpc.unary_unary_rpc_method_handler( - servicer.MarkRecommendationFailed, - request_deserializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.MarkRecommendationFailedRequest.FromString, - response_serializer=google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2.Recommendation.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.recommender.v1beta1.Recommender", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class Recommender(object): - """Provides insights and recommendations for cloud customers for various - categories like performance optimization, cost savings, reliability, feature - discovery, etc. Insights and recommendations are generated automatically - based on analysis of user resources, configuration and monitoring metrics. - """ - - @staticmethod - def ListInsights( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1beta1.Recommender/ListInsights", - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.ListInsightsRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.ListInsightsResponse.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetInsight( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1beta1.Recommender/GetInsight", - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.GetInsightRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_insight__pb2.Insight.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def MarkInsightAccepted( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1beta1.Recommender/MarkInsightAccepted", - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.MarkInsightAcceptedRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_insight__pb2.Insight.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListRecommendations( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1beta1.Recommender/ListRecommendations", - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.ListRecommendationsRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.ListRecommendationsResponse.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetRecommendation( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1beta1.Recommender/GetRecommendation", - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.GetRecommendationRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def MarkRecommendationClaimed( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1beta1.Recommender/MarkRecommendationClaimed", - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.MarkRecommendationClaimedRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def MarkRecommendationSucceeded( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1beta1.Recommender/MarkRecommendationSucceeded", - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.MarkRecommendationSucceededRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def MarkRecommendationFailed( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - insecure=False, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.recommender.v1beta1.Recommender/MarkRecommendationFailed", - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommender__service__pb2.MarkRecommendationFailedRequest.SerializeToString, - google_dot_cloud_dot_recommender__v1beta1_dot_proto_dot_recommendation__pb2.Recommendation.FromString, - options, - channel_credentials, - insecure, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/recommender_v1beta1/py.typed b/google/cloud/recommender_v1beta1/py.typed new file mode 100644 index 0000000..f9105be --- /dev/null +++ b/google/cloud/recommender_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-recommender package uses inline types. diff --git a/google/cloud/recommender_v1beta1/services/__init__.py b/google/cloud/recommender_v1beta1/services/__init__.py new file mode 100644 index 0000000..42ffdf2 --- /dev/null +++ b/google/cloud/recommender_v1beta1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/google/cloud/__init__.py b/google/cloud/recommender_v1beta1/services/recommender/__init__.py similarity index 71% rename from google/cloud/__init__.py rename to google/cloud/recommender_v1beta1/services/recommender/__init__.py index 9a1b64a..bfe4af8 100644 --- a/google/cloud/__init__.py +++ b/google/cloud/recommender_v1beta1/services/recommender/__init__.py @@ -1,24 +1,24 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil +from .client import RecommenderClient +from .async_client import RecommenderAsyncClient - __path__ = pkgutil.extend_path(__path__, __name__) +__all__ = ( + "RecommenderClient", + "RecommenderAsyncClient", +) diff --git a/google/cloud/recommender_v1beta1/services/recommender/async_client.py b/google/cloud/recommender_v1beta1/services/recommender/async_client.py new file mode 100644 index 0000000..834ee51 --- /dev/null +++ b/google/cloud/recommender_v1beta1/services/recommender/async_client.py @@ -0,0 +1,957 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.recommender_v1beta1.services.recommender import pagers +from google.cloud.recommender_v1beta1.types import insight +from google.cloud.recommender_v1beta1.types import recommendation +from google.cloud.recommender_v1beta1.types import recommender_service +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import RecommenderTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RecommenderGrpcAsyncIOTransport +from .client import RecommenderClient + + +class RecommenderAsyncClient: + """Provides insights and recommendations for cloud customers for + various categories like performance optimization, cost savings, + reliability, feature discovery, etc. Insights and + recommendations are generated automatically based on analysis of + user resources, configuration and monitoring metrics. + """ + + _client: RecommenderClient + + DEFAULT_ENDPOINT = RecommenderClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RecommenderClient.DEFAULT_MTLS_ENDPOINT + + insight_path = staticmethod(RecommenderClient.insight_path) + parse_insight_path = staticmethod(RecommenderClient.parse_insight_path) + insight_type_path = staticmethod(RecommenderClient.insight_type_path) + parse_insight_type_path = staticmethod(RecommenderClient.parse_insight_type_path) + recommendation_path = staticmethod(RecommenderClient.recommendation_path) + parse_recommendation_path = staticmethod( + RecommenderClient.parse_recommendation_path + ) + recommender_path = staticmethod(RecommenderClient.recommender_path) + parse_recommender_path = staticmethod(RecommenderClient.parse_recommender_path) + + common_billing_account_path = staticmethod( + RecommenderClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + RecommenderClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(RecommenderClient.common_folder_path) + parse_common_folder_path = staticmethod(RecommenderClient.parse_common_folder_path) + + common_organization_path = staticmethod(RecommenderClient.common_organization_path) + parse_common_organization_path = staticmethod( + RecommenderClient.parse_common_organization_path + ) + + common_project_path = staticmethod(RecommenderClient.common_project_path) + parse_common_project_path = staticmethod( + RecommenderClient.parse_common_project_path + ) + + common_location_path = staticmethod(RecommenderClient.common_location_path) + parse_common_location_path = staticmethod( + RecommenderClient.parse_common_location_path + ) + + from_service_account_file = RecommenderClient.from_service_account_file + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RecommenderTransport: + """Return the transport used by the client instance. + + Returns: + RecommenderTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(RecommenderClient).get_transport_class, type(RecommenderClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, RecommenderTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the recommender client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RecommenderTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + 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. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = RecommenderClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_insights( + self, + request: recommender_service.ListInsightsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInsightsAsyncPager: + r"""Lists insights for a Cloud project. Requires the + recommender.*.list IAM permission for the specified insight + type. + + Args: + request (:class:`~.recommender_service.ListInsightsRequest`): + The request object. Request for the `ListInsights` + method. + parent (:class:`str`): + Required. The container resource on which to execute the + request. Acceptable formats: + + 1. + + "projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]", + + LOCATION here refers to GCP Locations: + https://cloud.google.com/about/locations/ + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListInsightsAsyncPager: + Response to the ``ListInsights`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.ListInsightsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_insights, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListInsightsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_insight( + self, + request: recommender_service.GetInsightRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> insight.Insight: + r"""Gets the requested insight. Requires the recommender.*.get IAM + permission for the specified insight type. + + Args: + request (:class:`~.recommender_service.GetInsightRequest`): + The request object. Request to the `GetInsight` method. + name (:class:`str`): + Required. Name of the insight. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.insight.Insight: + An insight along with the information + used to derive the insight. The insight + may have associated recomendations as + well. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.GetInsightRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_insight, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def mark_insight_accepted( + self, + request: recommender_service.MarkInsightAcceptedRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkInsightAcceptedRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> insight.Insight: + r"""Marks the Insight State as Accepted. Users can use this method + to indicate to the Recommender API that they have applied some + action based on the insight. This stops the insight content from + being updated. + + MarkInsightAccepted can be applied to insights in ACTIVE state. + Requires the recommender.*.update IAM permission for the + specified insight. + + Args: + request (:class:`~.recommender_service.MarkInsightAcceptedRequest`): + The request object. Request for the + `MarkInsightAccepted` method. + name (:class:`str`): + Required. Name of the insight. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkInsightAcceptedRequest.StateMetadataEntry]`): + Optional. State properties user wish to include with + this state. Full replace of the current state_metadata. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the Insight. + Provides optimistic locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.insight.Insight: + An insight along with the information + used to derive the insight. The insight + may have associated recomendations as + well. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.MarkInsightAcceptedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.mark_insight_accepted, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_recommendations( + self, + request: recommender_service.ListRecommendationsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListRecommendationsAsyncPager: + r"""Lists recommendations for a Cloud project. Requires the + recommender.*.list IAM permission for the specified recommender. + + Args: + request (:class:`~.recommender_service.ListRecommendationsRequest`): + The request object. Request for the + `ListRecommendations` method. + parent (:class:`str`): + Required. The container resource on which to execute the + request. Acceptable formats: + + 1. + + "projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]", + + LOCATION here refers to GCP Locations: + https://cloud.google.com/about/locations/ + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Filter expression to restrict the recommendations + returned. Supported filter fields: state_info.state Eg: + \`state_info.state:"DISMISSED" or + state_info.state:"FAILED". + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListRecommendationsAsyncPager: + Response to the ``ListRecommendations`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.ListRecommendationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_recommendations, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListRecommendationsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_recommendation( + self, + request: recommender_service.GetRecommendationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Gets the requested recommendation. Requires the + recommender.*.get IAM permission for the specified recommender. + + Args: + request (:class:`~.recommender_service.GetRecommendationRequest`): + The request object. Request to the `GetRecommendation` + method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.GetRecommendationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_recommendation, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def mark_recommendation_claimed( + self, + request: recommender_service.MarkRecommendationClaimedRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkRecommendationClaimedRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Marks the Recommendation State as Claimed. Users can use this + method to indicate to the Recommender API that they are starting + to apply the recommendation themselves. This stops the + recommendation content from being updated. Associated insights + are frozen and placed in the ACCEPTED state. + + MarkRecommendationClaimed can be applied to recommendations in + CLAIMED or ACTIVE state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Args: + request (:class:`~.recommender_service.MarkRecommendationClaimedRequest`): + The request object. Request for the + `MarkRecommendationClaimed` Method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkRecommendationClaimedRequest.StateMetadataEntry]`): + State properties to include with this state. Overwrites + any existing ``state_metadata``. Keys must match the + regex ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match + the regex ``/^[a-zA-Z0-9_./-]{0,255}$/``. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the + Recommendation. Provides optimistic + locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.MarkRecommendationClaimedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.mark_recommendation_claimed, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def mark_recommendation_succeeded( + self, + request: recommender_service.MarkRecommendationSucceededRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkRecommendationSucceededRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Marks the Recommendation State as Succeeded. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation was successful. + This stops the recommendation content from being updated. + Associated insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationSucceeded can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Args: + request (:class:`~.recommender_service.MarkRecommendationSucceededRequest`): + The request object. Request for the + `MarkRecommendationSucceeded` Method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkRecommendationSucceededRequest.StateMetadataEntry]`): + State properties to include with this state. Overwrites + any existing ``state_metadata``. Keys must match the + regex ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match + the regex ``/^[a-zA-Z0-9_./-]{0,255}$/``. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the + Recommendation. Provides optimistic + locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.MarkRecommendationSucceededRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.mark_recommendation_succeeded, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def mark_recommendation_failed( + self, + request: recommender_service.MarkRecommendationFailedRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkRecommendationFailedRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Marks the Recommendation State as Failed. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation failed. This + stops the recommendation content from being updated. Associated + insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationFailed can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Args: + request (:class:`~.recommender_service.MarkRecommendationFailedRequest`): + The request object. Request for the + `MarkRecommendationFailed` Method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkRecommendationFailedRequest.StateMetadataEntry]`): + State properties to include with this state. Overwrites + any existing ``state_metadata``. Keys must match the + regex ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match + the regex ``/^[a-zA-Z0-9_./-]{0,255}$/``. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the + Recommendation. Provides optimistic + locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = recommender_service.MarkRecommendationFailedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.mark_recommendation_failed, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommender", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("RecommenderAsyncClient",) diff --git a/google/cloud/recommender_v1beta1/services/recommender/client.py b/google/cloud/recommender_v1beta1/services/recommender/client.py new file mode 100644 index 0000000..8534acb --- /dev/null +++ b/google/cloud/recommender_v1beta1/services/recommender/client.py @@ -0,0 +1,1186 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import 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 + +from google.cloud.recommender_v1beta1.services.recommender import pagers +from google.cloud.recommender_v1beta1.types import insight +from google.cloud.recommender_v1beta1.types import recommendation +from google.cloud.recommender_v1beta1.types import recommender_service +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import RecommenderTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RecommenderGrpcTransport +from .transports.grpc_asyncio import RecommenderGrpcAsyncIOTransport + + +class RecommenderClientMeta(type): + """Metaclass for the Recommender client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[RecommenderTransport]] + _transport_registry["grpc"] = RecommenderGrpcTransport + _transport_registry["grpc_asyncio"] = RecommenderGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[RecommenderTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RecommenderClient(metaclass=RecommenderClientMeta): + """Provides insights and recommendations for cloud customers for + various categories like performance optimization, cost savings, + reliability, feature discovery, etc. Insights and + recommendations are generated automatically based on analysis of + user resources, configuration and monitoring metrics. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "recommender.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RecommenderTransport: + """Return the transport used by the client instance. + + Returns: + RecommenderTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def insight_path( + project: str, location: str, insight_type: str, insight: str, + ) -> str: + """Return a fully-qualified insight string.""" + return "projects/{project}/locations/{location}/insightTypes/{insight_type}/insights/{insight}".format( + project=project, + location=location, + insight_type=insight_type, + insight=insight, + ) + + @staticmethod + def parse_insight_path(path: str) -> Dict[str, str]: + """Parse a insight path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/insightTypes/(?P.+?)/insights/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def insight_type_path(project: str, location: str, insight_type: str,) -> str: + """Return a fully-qualified insight_type string.""" + return "projects/{project}/locations/{location}/insightTypes/{insight_type}".format( + project=project, location=location, insight_type=insight_type, + ) + + @staticmethod + def parse_insight_type_path(path: str) -> Dict[str, str]: + """Parse a insight_type path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/insightTypes/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def recommendation_path( + project: str, location: str, recommender: str, recommendation: str, + ) -> str: + """Return a fully-qualified recommendation string.""" + return "projects/{project}/locations/{location}/recommenders/{recommender}/recommendations/{recommendation}".format( + project=project, + location=location, + recommender=recommender, + recommendation=recommendation, + ) + + @staticmethod + def parse_recommendation_path(path: str) -> Dict[str, str]: + """Parse a recommendation path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/recommenders/(?P.+?)/recommendations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def recommender_path(project: str, location: str, recommender: str,) -> str: + """Return a fully-qualified recommender string.""" + return "projects/{project}/locations/{location}/recommenders/{recommender}".format( + project=project, location=location, recommender=recommender, + ) + + @staticmethod + def parse_recommender_path(path: str) -> Dict[str, str]: + """Parse a recommender path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/recommenders/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + 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: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + 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: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + 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: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + 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: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + 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 {} + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, RecommenderTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the recommender client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RecommenderTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + 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. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RecommenderTransport): + # transport is a RecommenderTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_insights( + self, + request: recommender_service.ListInsightsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInsightsPager: + r"""Lists insights for a Cloud project. Requires the + recommender.*.list IAM permission for the specified insight + type. + + Args: + request (:class:`~.recommender_service.ListInsightsRequest`): + The request object. Request for the `ListInsights` + method. + parent (:class:`str`): + Required. The container resource on which to execute the + request. Acceptable formats: + + 1. + + "projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]", + + LOCATION here refers to GCP Locations: + https://cloud.google.com/about/locations/ + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListInsightsPager: + Response to the ``ListInsights`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.ListInsightsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommender_service.ListInsightsRequest): + request = recommender_service.ListInsightsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_insights] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListInsightsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_insight( + self, + request: recommender_service.GetInsightRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> insight.Insight: + r"""Gets the requested insight. Requires the recommender.*.get IAM + permission for the specified insight type. + + Args: + request (:class:`~.recommender_service.GetInsightRequest`): + The request object. Request to the `GetInsight` method. + name (:class:`str`): + Required. Name of the insight. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.insight.Insight: + An insight along with the information + used to derive the insight. The insight + may have associated recomendations as + well. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.GetInsightRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommender_service.GetInsightRequest): + request = recommender_service.GetInsightRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_insight] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def mark_insight_accepted( + self, + request: recommender_service.MarkInsightAcceptedRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkInsightAcceptedRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> insight.Insight: + r"""Marks the Insight State as Accepted. Users can use this method + to indicate to the Recommender API that they have applied some + action based on the insight. This stops the insight content from + being updated. + + MarkInsightAccepted can be applied to insights in ACTIVE state. + Requires the recommender.*.update IAM permission for the + specified insight. + + Args: + request (:class:`~.recommender_service.MarkInsightAcceptedRequest`): + The request object. Request for the + `MarkInsightAccepted` method. + name (:class:`str`): + Required. Name of the insight. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkInsightAcceptedRequest.StateMetadataEntry]`): + Optional. State properties user wish to include with + this state. Full replace of the current state_metadata. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the Insight. + Provides optimistic locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.insight.Insight: + An insight along with the information + used to derive the insight. The insight + may have associated recomendations as + well. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.MarkInsightAcceptedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommender_service.MarkInsightAcceptedRequest): + request = recommender_service.MarkInsightAcceptedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.mark_insight_accepted] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_recommendations( + self, + request: recommender_service.ListRecommendationsRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListRecommendationsPager: + r"""Lists recommendations for a Cloud project. Requires the + recommender.*.list IAM permission for the specified recommender. + + Args: + request (:class:`~.recommender_service.ListRecommendationsRequest`): + The request object. Request for the + `ListRecommendations` method. + parent (:class:`str`): + Required. The container resource on which to execute the + request. Acceptable formats: + + 1. + + "projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]", + + LOCATION here refers to GCP Locations: + https://cloud.google.com/about/locations/ + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Filter expression to restrict the recommendations + returned. Supported filter fields: state_info.state Eg: + \`state_info.state:"DISMISSED" or + state_info.state:"FAILED". + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListRecommendationsPager: + Response to the ``ListRecommendations`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.ListRecommendationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommender_service.ListRecommendationsRequest): + request = recommender_service.ListRecommendationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_recommendations] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRecommendationsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_recommendation( + self, + request: recommender_service.GetRecommendationRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Gets the requested recommendation. Requires the + recommender.*.get IAM permission for the specified recommender. + + Args: + request (:class:`~.recommender_service.GetRecommendationRequest`): + The request object. Request to the `GetRecommendation` + method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.GetRecommendationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommender_service.GetRecommendationRequest): + request = recommender_service.GetRecommendationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_recommendation] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def mark_recommendation_claimed( + self, + request: recommender_service.MarkRecommendationClaimedRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkRecommendationClaimedRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Marks the Recommendation State as Claimed. Users can use this + method to indicate to the Recommender API that they are starting + to apply the recommendation themselves. This stops the + recommendation content from being updated. Associated insights + are frozen and placed in the ACCEPTED state. + + MarkRecommendationClaimed can be applied to recommendations in + CLAIMED or ACTIVE state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Args: + request (:class:`~.recommender_service.MarkRecommendationClaimedRequest`): + The request object. Request for the + `MarkRecommendationClaimed` Method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkRecommendationClaimedRequest.StateMetadataEntry]`): + State properties to include with this state. Overwrites + any existing ``state_metadata``. Keys must match the + regex ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match + the regex ``/^[a-zA-Z0-9_./-]{0,255}$/``. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the + Recommendation. Provides optimistic + locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.MarkRecommendationClaimedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, recommender_service.MarkRecommendationClaimedRequest + ): + request = recommender_service.MarkRecommendationClaimedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.mark_recommendation_claimed + ] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def mark_recommendation_succeeded( + self, + request: recommender_service.MarkRecommendationSucceededRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkRecommendationSucceededRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Marks the Recommendation State as Succeeded. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation was successful. + This stops the recommendation content from being updated. + Associated insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationSucceeded can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Args: + request (:class:`~.recommender_service.MarkRecommendationSucceededRequest`): + The request object. Request for the + `MarkRecommendationSucceeded` Method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkRecommendationSucceededRequest.StateMetadataEntry]`): + State properties to include with this state. Overwrites + any existing ``state_metadata``. Keys must match the + regex ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match + the regex ``/^[a-zA-Z0-9_./-]{0,255}$/``. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the + Recommendation. Provides optimistic + locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.MarkRecommendationSucceededRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, recommender_service.MarkRecommendationSucceededRequest + ): + request = recommender_service.MarkRecommendationSucceededRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.mark_recommendation_succeeded + ] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def mark_recommendation_failed( + self, + request: recommender_service.MarkRecommendationFailedRequest = None, + *, + name: str = None, + state_metadata: Sequence[ + recommender_service.MarkRecommendationFailedRequest.StateMetadataEntry + ] = None, + etag: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation.Recommendation: + r"""Marks the Recommendation State as Failed. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation failed. This + stops the recommendation content from being updated. Associated + insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationFailed can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Args: + request (:class:`~.recommender_service.MarkRecommendationFailedRequest`): + The request object. Request for the + `MarkRecommendationFailed` Method. + name (:class:`str`): + Required. Name of the recommendation. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state_metadata (:class:`Sequence[~.recommender_service.MarkRecommendationFailedRequest.StateMetadataEntry]`): + State properties to include with this state. Overwrites + any existing ``state_metadata``. Keys must match the + regex ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match + the regex ``/^[a-zA-Z0-9_./-]{0,255}$/``. + This corresponds to the ``state_metadata`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Required. Fingerprint of the + Recommendation. Provides optimistic + locking. + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation.Recommendation: + A recommendation along with a + suggested action. E.g., a rightsizing + recommendation for an underutilized VM, + IAM role recommendations, etc + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state_metadata, etag]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a recommender_service.MarkRecommendationFailedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommender_service.MarkRecommendationFailedRequest): + request = recommender_service.MarkRecommendationFailedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + if state_metadata: + request.state_metadata.update(state_metadata) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.mark_recommendation_failed + ] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommender", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("RecommenderClient",) diff --git a/google/cloud/recommender_v1beta1/services/recommender/pagers.py b/google/cloud/recommender_v1beta1/services/recommender/pagers.py new file mode 100644 index 0000000..cbcf8d9 --- /dev/null +++ b/google/cloud/recommender_v1beta1/services/recommender/pagers.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.recommender_v1beta1.types import insight +from google.cloud.recommender_v1beta1.types import recommendation +from google.cloud.recommender_v1beta1.types import recommender_service + + +class ListInsightsPager: + """A pager for iterating through ``list_insights`` requests. + + This class thinly wraps an initial + :class:`~.recommender_service.ListInsightsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``insights`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInsights`` requests and continue to iterate + through the ``insights`` field on the + corresponding responses. + + All the usual :class:`~.recommender_service.ListInsightsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., recommender_service.ListInsightsResponse], + request: recommender_service.ListInsightsRequest, + response: recommender_service.ListInsightsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.recommender_service.ListInsightsRequest`): + The initial request object. + response (:class:`~.recommender_service.ListInsightsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = recommender_service.ListInsightsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[recommender_service.ListInsightsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[insight.Insight]: + for page in self.pages: + yield from page.insights + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListInsightsAsyncPager: + """A pager for iterating through ``list_insights`` requests. + + This class thinly wraps an initial + :class:`~.recommender_service.ListInsightsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``insights`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInsights`` requests and continue to iterate + through the ``insights`` field on the + corresponding responses. + + All the usual :class:`~.recommender_service.ListInsightsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[recommender_service.ListInsightsResponse]], + request: recommender_service.ListInsightsRequest, + response: recommender_service.ListInsightsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.recommender_service.ListInsightsRequest`): + The initial request object. + response (:class:`~.recommender_service.ListInsightsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = recommender_service.ListInsightsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[recommender_service.ListInsightsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[insight.Insight]: + async def async_generator(): + async for page in self.pages: + for response in page.insights: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRecommendationsPager: + """A pager for iterating through ``list_recommendations`` requests. + + This class thinly wraps an initial + :class:`~.recommender_service.ListRecommendationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``recommendations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRecommendations`` requests and continue to iterate + through the ``recommendations`` field on the + corresponding responses. + + All the usual :class:`~.recommender_service.ListRecommendationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., recommender_service.ListRecommendationsResponse], + request: recommender_service.ListRecommendationsRequest, + response: recommender_service.ListRecommendationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.recommender_service.ListRecommendationsRequest`): + The initial request object. + response (:class:`~.recommender_service.ListRecommendationsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = recommender_service.ListRecommendationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[recommender_service.ListRecommendationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[recommendation.Recommendation]: + for page in self.pages: + yield from page.recommendations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRecommendationsAsyncPager: + """A pager for iterating through ``list_recommendations`` requests. + + This class thinly wraps an initial + :class:`~.recommender_service.ListRecommendationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``recommendations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRecommendations`` requests and continue to iterate + through the ``recommendations`` field on the + corresponding responses. + + All the usual :class:`~.recommender_service.ListRecommendationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[recommender_service.ListRecommendationsResponse] + ], + request: recommender_service.ListRecommendationsRequest, + response: recommender_service.ListRecommendationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.recommender_service.ListRecommendationsRequest`): + The initial request object. + response (:class:`~.recommender_service.ListRecommendationsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = recommender_service.ListRecommendationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[recommender_service.ListRecommendationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[recommendation.Recommendation]: + async def async_generator(): + async for page in self.pages: + for response in page.recommendations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/recommender_v1beta1/services/recommender/transports/__init__.py b/google/cloud/recommender_v1beta1/services/recommender/transports/__init__.py new file mode 100644 index 0000000..d099ae4 --- /dev/null +++ b/google/cloud/recommender_v1beta1/services/recommender/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import RecommenderTransport +from .grpc import RecommenderGrpcTransport +from .grpc_asyncio import RecommenderGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RecommenderTransport]] +_transport_registry["grpc"] = RecommenderGrpcTransport +_transport_registry["grpc_asyncio"] = RecommenderGrpcAsyncIOTransport + + +__all__ = ( + "RecommenderTransport", + "RecommenderGrpcTransport", + "RecommenderGrpcAsyncIOTransport", +) diff --git a/google/cloud/recommender_v1beta1/services/recommender/transports/base.py b/google/cloud/recommender_v1beta1/services/recommender/transports/base.py new file mode 100644 index 0000000..00e2b76 --- /dev/null +++ b/google/cloud/recommender_v1beta1/services/recommender/transports/base.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.recommender_v1beta1.types import insight +from google.cloud.recommender_v1beta1.types import recommendation +from google.cloud.recommender_v1beta1.types import recommender_service + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-recommender", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class RecommenderTransport(abc.ABC): + """Abstract transport class for Recommender.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "recommender.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_insights: gapic_v1.method.wrap_method( + self.list_insights, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_insight: gapic_v1.method.wrap_method( + self.get_insight, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=client_info, + ), + self.mark_insight_accepted: gapic_v1.method.wrap_method( + self.mark_insight_accepted, + default_timeout=60.0, + client_info=client_info, + ), + self.list_recommendations: gapic_v1.method.wrap_method( + self.list_recommendations, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_recommendation: gapic_v1.method.wrap_method( + self.get_recommendation, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=client_info, + ), + self.mark_recommendation_claimed: gapic_v1.method.wrap_method( + self.mark_recommendation_claimed, + default_timeout=60.0, + client_info=client_info, + ), + self.mark_recommendation_succeeded: gapic_v1.method.wrap_method( + self.mark_recommendation_succeeded, + default_timeout=60.0, + client_info=client_info, + ), + self.mark_recommendation_failed: gapic_v1.method.wrap_method( + self.mark_recommendation_failed, + default_timeout=60.0, + client_info=client_info, + ), + } + + @property + def list_insights( + self, + ) -> typing.Callable[ + [recommender_service.ListInsightsRequest], + typing.Union[ + recommender_service.ListInsightsResponse, + typing.Awaitable[recommender_service.ListInsightsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_insight( + self, + ) -> typing.Callable[ + [recommender_service.GetInsightRequest], + typing.Union[insight.Insight, typing.Awaitable[insight.Insight]], + ]: + raise NotImplementedError() + + @property + def mark_insight_accepted( + self, + ) -> typing.Callable[ + [recommender_service.MarkInsightAcceptedRequest], + typing.Union[insight.Insight, typing.Awaitable[insight.Insight]], + ]: + raise NotImplementedError() + + @property + def list_recommendations( + self, + ) -> typing.Callable[ + [recommender_service.ListRecommendationsRequest], + typing.Union[ + recommender_service.ListRecommendationsResponse, + typing.Awaitable[recommender_service.ListRecommendationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_recommendation( + self, + ) -> typing.Callable[ + [recommender_service.GetRecommendationRequest], + typing.Union[ + recommendation.Recommendation, + typing.Awaitable[recommendation.Recommendation], + ], + ]: + raise NotImplementedError() + + @property + def mark_recommendation_claimed( + self, + ) -> typing.Callable[ + [recommender_service.MarkRecommendationClaimedRequest], + typing.Union[ + recommendation.Recommendation, + typing.Awaitable[recommendation.Recommendation], + ], + ]: + raise NotImplementedError() + + @property + def mark_recommendation_succeeded( + self, + ) -> typing.Callable[ + [recommender_service.MarkRecommendationSucceededRequest], + typing.Union[ + recommendation.Recommendation, + typing.Awaitable[recommendation.Recommendation], + ], + ]: + raise NotImplementedError() + + @property + def mark_recommendation_failed( + self, + ) -> typing.Callable[ + [recommender_service.MarkRecommendationFailedRequest], + typing.Union[ + recommendation.Recommendation, + typing.Awaitable[recommendation.Recommendation], + ], + ]: + raise NotImplementedError() + + +__all__ = ("RecommenderTransport",) diff --git a/google/cloud/recommender_v1beta1/services/recommender/transports/grpc.py b/google/cloud/recommender_v1beta1/services/recommender/transports/grpc.py new file mode 100644 index 0000000..a7a11e5 --- /dev/null +++ b/google/cloud/recommender_v1beta1/services/recommender/transports/grpc.py @@ -0,0 +1,508 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.recommender_v1beta1.types import insight +from google.cloud.recommender_v1beta1.types import recommendation +from google.cloud.recommender_v1beta1.types import recommender_service + +from .base import RecommenderTransport, DEFAULT_CLIENT_INFO + + +class RecommenderGrpcTransport(RecommenderTransport): + """gRPC backend transport for Recommender. + + Provides insights and recommendations for cloud customers for + various categories like performance optimization, cost savings, + reliability, feature discovery, etc. Insights and + recommendations are generated automatically based on analysis of + user resources, configuration and monitoring metrics. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + 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 = "recommender.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "recommender.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_insights( + self, + ) -> Callable[ + [recommender_service.ListInsightsRequest], + recommender_service.ListInsightsResponse, + ]: + r"""Return a callable for the list insights method over gRPC. + + Lists insights for a Cloud project. Requires the + recommender.*.list IAM permission for the specified insight + type. + + Returns: + Callable[[~.ListInsightsRequest], + ~.ListInsightsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_insights" not in self._stubs: + self._stubs["list_insights"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/ListInsights", + request_serializer=recommender_service.ListInsightsRequest.serialize, + response_deserializer=recommender_service.ListInsightsResponse.deserialize, + ) + return self._stubs["list_insights"] + + @property + def get_insight( + self, + ) -> Callable[[recommender_service.GetInsightRequest], insight.Insight]: + r"""Return a callable for the get insight method over gRPC. + + Gets the requested insight. Requires the recommender.*.get IAM + permission for the specified insight type. + + Returns: + Callable[[~.GetInsightRequest], + ~.Insight]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_insight" not in self._stubs: + self._stubs["get_insight"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/GetInsight", + request_serializer=recommender_service.GetInsightRequest.serialize, + response_deserializer=insight.Insight.deserialize, + ) + return self._stubs["get_insight"] + + @property + def mark_insight_accepted( + self, + ) -> Callable[[recommender_service.MarkInsightAcceptedRequest], insight.Insight]: + r"""Return a callable for the mark insight accepted method over gRPC. + + Marks the Insight State as Accepted. Users can use this method + to indicate to the Recommender API that they have applied some + action based on the insight. This stops the insight content from + being updated. + + MarkInsightAccepted can be applied to insights in ACTIVE state. + Requires the recommender.*.update IAM permission for the + specified insight. + + Returns: + Callable[[~.MarkInsightAcceptedRequest], + ~.Insight]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_insight_accepted" not in self._stubs: + self._stubs["mark_insight_accepted"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/MarkInsightAccepted", + request_serializer=recommender_service.MarkInsightAcceptedRequest.serialize, + response_deserializer=insight.Insight.deserialize, + ) + return self._stubs["mark_insight_accepted"] + + @property + def list_recommendations( + self, + ) -> Callable[ + [recommender_service.ListRecommendationsRequest], + recommender_service.ListRecommendationsResponse, + ]: + r"""Return a callable for the list recommendations method over gRPC. + + Lists recommendations for a Cloud project. Requires the + recommender.*.list IAM permission for the specified recommender. + + Returns: + Callable[[~.ListRecommendationsRequest], + ~.ListRecommendationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_recommendations" not in self._stubs: + self._stubs["list_recommendations"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/ListRecommendations", + request_serializer=recommender_service.ListRecommendationsRequest.serialize, + response_deserializer=recommender_service.ListRecommendationsResponse.deserialize, + ) + return self._stubs["list_recommendations"] + + @property + def get_recommendation( + self, + ) -> Callable[ + [recommender_service.GetRecommendationRequest], recommendation.Recommendation + ]: + r"""Return a callable for the get recommendation method over gRPC. + + Gets the requested recommendation. Requires the + recommender.*.get IAM permission for the specified recommender. + + Returns: + Callable[[~.GetRecommendationRequest], + ~.Recommendation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_recommendation" not in self._stubs: + self._stubs["get_recommendation"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/GetRecommendation", + request_serializer=recommender_service.GetRecommendationRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["get_recommendation"] + + @property + def mark_recommendation_claimed( + self, + ) -> Callable[ + [recommender_service.MarkRecommendationClaimedRequest], + recommendation.Recommendation, + ]: + r"""Return a callable for the mark recommendation claimed method over gRPC. + + Marks the Recommendation State as Claimed. Users can use this + method to indicate to the Recommender API that they are starting + to apply the recommendation themselves. This stops the + recommendation content from being updated. Associated insights + are frozen and placed in the ACCEPTED state. + + MarkRecommendationClaimed can be applied to recommendations in + CLAIMED or ACTIVE state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Returns: + Callable[[~.MarkRecommendationClaimedRequest], + ~.Recommendation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_recommendation_claimed" not in self._stubs: + self._stubs["mark_recommendation_claimed"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/MarkRecommendationClaimed", + request_serializer=recommender_service.MarkRecommendationClaimedRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["mark_recommendation_claimed"] + + @property + def mark_recommendation_succeeded( + self, + ) -> Callable[ + [recommender_service.MarkRecommendationSucceededRequest], + recommendation.Recommendation, + ]: + r"""Return a callable for the mark recommendation succeeded method over gRPC. + + Marks the Recommendation State as Succeeded. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation was successful. + This stops the recommendation content from being updated. + Associated insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationSucceeded can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Returns: + Callable[[~.MarkRecommendationSucceededRequest], + ~.Recommendation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_recommendation_succeeded" not in self._stubs: + self._stubs[ + "mark_recommendation_succeeded" + ] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/MarkRecommendationSucceeded", + request_serializer=recommender_service.MarkRecommendationSucceededRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["mark_recommendation_succeeded"] + + @property + def mark_recommendation_failed( + self, + ) -> Callable[ + [recommender_service.MarkRecommendationFailedRequest], + recommendation.Recommendation, + ]: + r"""Return a callable for the mark recommendation failed method over gRPC. + + Marks the Recommendation State as Failed. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation failed. This + stops the recommendation content from being updated. Associated + insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationFailed can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Returns: + Callable[[~.MarkRecommendationFailedRequest], + ~.Recommendation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_recommendation_failed" not in self._stubs: + self._stubs["mark_recommendation_failed"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/MarkRecommendationFailed", + request_serializer=recommender_service.MarkRecommendationFailedRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["mark_recommendation_failed"] + + +__all__ = ("RecommenderGrpcTransport",) diff --git a/google/cloud/recommender_v1beta1/services/recommender/transports/grpc_asyncio.py b/google/cloud/recommender_v1beta1/services/recommender/transports/grpc_asyncio.py new file mode 100644 index 0000000..8ff572b --- /dev/null +++ b/google/cloud/recommender_v1beta1/services/recommender/transports/grpc_asyncio.py @@ -0,0 +1,515 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.recommender_v1beta1.types import insight +from google.cloud.recommender_v1beta1.types import recommendation +from google.cloud.recommender_v1beta1.types import recommender_service + +from .base import RecommenderTransport, DEFAULT_CLIENT_INFO +from .grpc import RecommenderGrpcTransport + + +class RecommenderGrpcAsyncIOTransport(RecommenderTransport): + """gRPC AsyncIO backend transport for Recommender. + + Provides insights and recommendations for cloud customers for + various categories like performance optimization, cost savings, + reliability, feature discovery, etc. Insights and + recommendations are generated automatically based on analysis of + user resources, configuration and monitoring metrics. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "recommender.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "recommender.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_insights( + self, + ) -> Callable[ + [recommender_service.ListInsightsRequest], + Awaitable[recommender_service.ListInsightsResponse], + ]: + r"""Return a callable for the list insights method over gRPC. + + Lists insights for a Cloud project. Requires the + recommender.*.list IAM permission for the specified insight + type. + + Returns: + Callable[[~.ListInsightsRequest], + Awaitable[~.ListInsightsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_insights" not in self._stubs: + self._stubs["list_insights"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/ListInsights", + request_serializer=recommender_service.ListInsightsRequest.serialize, + response_deserializer=recommender_service.ListInsightsResponse.deserialize, + ) + return self._stubs["list_insights"] + + @property + def get_insight( + self, + ) -> Callable[[recommender_service.GetInsightRequest], Awaitable[insight.Insight]]: + r"""Return a callable for the get insight method over gRPC. + + Gets the requested insight. Requires the recommender.*.get IAM + permission for the specified insight type. + + Returns: + Callable[[~.GetInsightRequest], + Awaitable[~.Insight]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_insight" not in self._stubs: + self._stubs["get_insight"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/GetInsight", + request_serializer=recommender_service.GetInsightRequest.serialize, + response_deserializer=insight.Insight.deserialize, + ) + return self._stubs["get_insight"] + + @property + def mark_insight_accepted( + self, + ) -> Callable[ + [recommender_service.MarkInsightAcceptedRequest], Awaitable[insight.Insight] + ]: + r"""Return a callable for the mark insight accepted method over gRPC. + + Marks the Insight State as Accepted. Users can use this method + to indicate to the Recommender API that they have applied some + action based on the insight. This stops the insight content from + being updated. + + MarkInsightAccepted can be applied to insights in ACTIVE state. + Requires the recommender.*.update IAM permission for the + specified insight. + + Returns: + Callable[[~.MarkInsightAcceptedRequest], + Awaitable[~.Insight]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_insight_accepted" not in self._stubs: + self._stubs["mark_insight_accepted"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/MarkInsightAccepted", + request_serializer=recommender_service.MarkInsightAcceptedRequest.serialize, + response_deserializer=insight.Insight.deserialize, + ) + return self._stubs["mark_insight_accepted"] + + @property + def list_recommendations( + self, + ) -> Callable[ + [recommender_service.ListRecommendationsRequest], + Awaitable[recommender_service.ListRecommendationsResponse], + ]: + r"""Return a callable for the list recommendations method over gRPC. + + Lists recommendations for a Cloud project. Requires the + recommender.*.list IAM permission for the specified recommender. + + Returns: + Callable[[~.ListRecommendationsRequest], + Awaitable[~.ListRecommendationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_recommendations" not in self._stubs: + self._stubs["list_recommendations"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/ListRecommendations", + request_serializer=recommender_service.ListRecommendationsRequest.serialize, + response_deserializer=recommender_service.ListRecommendationsResponse.deserialize, + ) + return self._stubs["list_recommendations"] + + @property + def get_recommendation( + self, + ) -> Callable[ + [recommender_service.GetRecommendationRequest], + Awaitable[recommendation.Recommendation], + ]: + r"""Return a callable for the get recommendation method over gRPC. + + Gets the requested recommendation. Requires the + recommender.*.get IAM permission for the specified recommender. + + Returns: + Callable[[~.GetRecommendationRequest], + Awaitable[~.Recommendation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_recommendation" not in self._stubs: + self._stubs["get_recommendation"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/GetRecommendation", + request_serializer=recommender_service.GetRecommendationRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["get_recommendation"] + + @property + def mark_recommendation_claimed( + self, + ) -> Callable[ + [recommender_service.MarkRecommendationClaimedRequest], + Awaitable[recommendation.Recommendation], + ]: + r"""Return a callable for the mark recommendation claimed method over gRPC. + + Marks the Recommendation State as Claimed. Users can use this + method to indicate to the Recommender API that they are starting + to apply the recommendation themselves. This stops the + recommendation content from being updated. Associated insights + are frozen and placed in the ACCEPTED state. + + MarkRecommendationClaimed can be applied to recommendations in + CLAIMED or ACTIVE state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Returns: + Callable[[~.MarkRecommendationClaimedRequest], + Awaitable[~.Recommendation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_recommendation_claimed" not in self._stubs: + self._stubs["mark_recommendation_claimed"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/MarkRecommendationClaimed", + request_serializer=recommender_service.MarkRecommendationClaimedRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["mark_recommendation_claimed"] + + @property + def mark_recommendation_succeeded( + self, + ) -> Callable[ + [recommender_service.MarkRecommendationSucceededRequest], + Awaitable[recommendation.Recommendation], + ]: + r"""Return a callable for the mark recommendation succeeded method over gRPC. + + Marks the Recommendation State as Succeeded. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation was successful. + This stops the recommendation content from being updated. + Associated insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationSucceeded can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Returns: + Callable[[~.MarkRecommendationSucceededRequest], + Awaitable[~.Recommendation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_recommendation_succeeded" not in self._stubs: + self._stubs[ + "mark_recommendation_succeeded" + ] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/MarkRecommendationSucceeded", + request_serializer=recommender_service.MarkRecommendationSucceededRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["mark_recommendation_succeeded"] + + @property + def mark_recommendation_failed( + self, + ) -> Callable[ + [recommender_service.MarkRecommendationFailedRequest], + Awaitable[recommendation.Recommendation], + ]: + r"""Return a callable for the mark recommendation failed method over gRPC. + + Marks the Recommendation State as Failed. Users can use this + method to indicate to the Recommender API that they have applied + the recommendation themselves, and the operation failed. This + stops the recommendation content from being updated. Associated + insights are frozen and placed in the ACCEPTED state. + + MarkRecommendationFailed can be applied to recommendations in + ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. + + Requires the recommender.*.update IAM permission for the + specified recommender. + + Returns: + Callable[[~.MarkRecommendationFailedRequest], + Awaitable[~.Recommendation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_recommendation_failed" not in self._stubs: + self._stubs["mark_recommendation_failed"] = self.grpc_channel.unary_unary( + "/google.cloud.recommender.v1beta1.Recommender/MarkRecommendationFailed", + request_serializer=recommender_service.MarkRecommendationFailedRequest.serialize, + response_deserializer=recommendation.Recommendation.deserialize, + ) + return self._stubs["mark_recommendation_failed"] + + +__all__ = ("RecommenderGrpcAsyncIOTransport",) diff --git a/google/cloud/recommender_v1beta1/types.py b/google/cloud/recommender_v1beta1/types.py deleted file mode 100644 index 608f387..0000000 --- a/google/cloud/recommender_v1beta1/types.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.recommender_v1beta1.proto import insight_pb2 -from google.cloud.recommender_v1beta1.proto import recommendation_pb2 -from google.cloud.recommender_v1beta1.proto import recommender_service_pb2 -from google.protobuf import duration_pb2 -from google.protobuf import struct_pb2 -from google.protobuf import timestamp_pb2 -from google.type import money_pb2 - - -_shared_modules = [ - duration_pb2, - struct_pb2, - timestamp_pb2, - money_pb2, -] - -_local_modules = [ - insight_pb2, - recommendation_pb2, - recommender_service_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.recommender_v1beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/recommender_v1beta1/types/__init__.py b/google/cloud/recommender_v1beta1/types/__init__.py new file mode 100644 index 0000000..04032ec --- /dev/null +++ b/google/cloud/recommender_v1beta1/types/__init__.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .insight import ( + Insight, + InsightStateInfo, +) +from .recommendation import ( + Recommendation, + RecommendationContent, + OperationGroup, + Operation, + ValueMatcher, + CostProjection, + Impact, + RecommendationStateInfo, +) +from .recommender_service import ( + ListInsightsRequest, + ListInsightsResponse, + GetInsightRequest, + MarkInsightAcceptedRequest, + ListRecommendationsRequest, + ListRecommendationsResponse, + GetRecommendationRequest, + MarkRecommendationClaimedRequest, + MarkRecommendationSucceededRequest, + MarkRecommendationFailedRequest, +) + + +__all__ = ( + "Insight", + "InsightStateInfo", + "Recommendation", + "RecommendationContent", + "OperationGroup", + "Operation", + "ValueMatcher", + "CostProjection", + "Impact", + "RecommendationStateInfo", + "ListInsightsRequest", + "ListInsightsResponse", + "GetInsightRequest", + "MarkInsightAcceptedRequest", + "ListRecommendationsRequest", + "ListRecommendationsResponse", + "GetRecommendationRequest", + "MarkRecommendationClaimedRequest", + "MarkRecommendationSucceededRequest", + "MarkRecommendationFailedRequest", +) diff --git a/google/cloud/recommender_v1beta1/types/insight.py b/google/cloud/recommender_v1beta1/types/insight.py new file mode 100644 index 0000000..d842980 --- /dev/null +++ b/google/cloud/recommender_v1beta1/types/insight.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.recommender.v1beta1", + manifest={"Insight", "InsightStateInfo",}, +) + + +class Insight(proto.Message): + r"""An insight along with the information used to derive the + insight. The insight may have associated recomendations as well. + + Attributes: + name (str): + Name of the insight. + description (str): + Free-form human readable summary in English. + The maximum length is 500 characters. + target_resources (Sequence[str]): + Fully qualified resource names that this + insight is targeting. + insight_subtype (str): + Insight subtype. Insight content schema will + be stable for a given subtype. + content (~.struct.Struct): + A struct of custom fields to explain the + insight. Example: "grantedPermissionsCount": + "1000". + last_refresh_time (~.timestamp.Timestamp): + Timestamp of the latest data used to generate + the insight. + observation_period (~.duration.Duration): + Observation period that led to the insight. The source data + used to generate the insight ends at last_refresh_time and + begins at (last_refresh_time - observation_period). + state_info (~.insight.InsightStateInfo): + Information state and metadata. + category (~.insight.Insight.Category): + Category being targeted by the insight. + etag (str): + Fingerprint of the Insight. Provides + optimistic locking when updating states. + associated_recommendations (Sequence[~.insight.Insight.RecommendationReference]): + Recommendations derived from this insight. + """ + + class Category(proto.Enum): + r"""Insight category.""" + CATEGORY_UNSPECIFIED = 0 + COST = 1 + SECURITY = 2 + PERFORMANCE = 3 + MANAGEABILITY = 4 + + class RecommendationReference(proto.Message): + r"""Reference to an associated recommendation. + + Attributes: + recommendation (str): + Recommendation resource name, e.g. + projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/recommendations/[RECOMMENDATION_ID] + """ + + recommendation = proto.Field(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=1) + + description = proto.Field(proto.STRING, number=2) + + target_resources = proto.RepeatedField(proto.STRING, number=9) + + insight_subtype = proto.Field(proto.STRING, number=10) + + content = proto.Field(proto.MESSAGE, number=3, message=struct.Struct,) + + last_refresh_time = proto.Field( + proto.MESSAGE, number=4, message=timestamp.Timestamp, + ) + + observation_period = proto.Field( + proto.MESSAGE, number=5, message=duration.Duration, + ) + + state_info = proto.Field(proto.MESSAGE, number=6, message="InsightStateInfo",) + + category = proto.Field(proto.ENUM, number=7, enum=Category,) + + etag = proto.Field(proto.STRING, number=11) + + associated_recommendations = proto.RepeatedField( + proto.MESSAGE, number=8, message=RecommendationReference, + ) + + +class InsightStateInfo(proto.Message): + r"""Information related to insight state. + + Attributes: + state (~.insight.InsightStateInfo.State): + Insight state. + state_metadata (Sequence[~.insight.InsightStateInfo.StateMetadataEntry]): + A map of metadata for the state, provided by + user or automations systems. + """ + + class State(proto.Enum): + r"""Represents insight state.""" + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + ACCEPTED = 2 + DISMISSED = 3 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + state_metadata = proto.MapField(proto.STRING, proto.STRING, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/recommender_v1beta1/types/recommendation.py b/google/cloud/recommender_v1beta1/types/recommendation.py new file mode 100644 index 0000000..bcb9d6e --- /dev/null +++ b/google/cloud/recommender_v1beta1/types/recommendation.py @@ -0,0 +1,353 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import duration_pb2 as gp_duration # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.type import money_pb2 as money # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.recommender.v1beta1", + manifest={ + "Recommendation", + "RecommendationContent", + "OperationGroup", + "Operation", + "ValueMatcher", + "CostProjection", + "Impact", + "RecommendationStateInfo", + }, +) + + +class Recommendation(proto.Message): + r"""A recommendation along with a suggested action. E.g., a + rightsizing recommendation for an underutilized VM, IAM role + recommendations, etc + + Attributes: + name (str): + Name of recommendation. + description (str): + Free-form human readable summary in English. + The maximum length is 500 characters. + recommender_subtype (str): + Contains an identifier for a subtype of recommendations + produced for the same recommender. Subtype is a function of + content and impact, meaning a new subtype might be added + when significant changes to ``content`` or + ``primary_impact.category`` are introduced. See the + Recommenders section to see a list of subtypes for a given + Recommender. + + Examples: For recommender = "google.iam.policy.Recommender", + recommender_subtype can be one of + "REMOVE_ROLE"/"REPLACE_ROLE". + last_refresh_time (~.timestamp.Timestamp): + Last time this recommendation was refreshed + by the system that created it in the first + place. + primary_impact (~.recommendation.Impact): + The primary impact that this recommendation + can have while trying to optimize for one + category. + additional_impact (Sequence[~.recommendation.Impact]): + Optional set of additional impact that this + recommendation may have when trying to optimize + for the primary category. These may be positive + or negative. + content (~.recommendation.RecommendationContent): + Content of the recommendation describing + recommended changes to resources. + state_info (~.recommendation.RecommendationStateInfo): + Information for state. Contains state and + metadata. + etag (str): + Fingerprint of the Recommendation. Provides + optimistic locking when updating states. + associated_insights (Sequence[~.recommendation.Recommendation.InsightReference]): + Insights that led to this recommendation. + """ + + class InsightReference(proto.Message): + r"""Reference to an associated insight. + + Attributes: + insight (str): + Insight resource name, e.g. + projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]/insights/[INSIGHT_ID] + """ + + insight = proto.Field(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=1) + + description = proto.Field(proto.STRING, number=2) + + recommender_subtype = proto.Field(proto.STRING, number=12) + + last_refresh_time = proto.Field( + proto.MESSAGE, number=4, message=timestamp.Timestamp, + ) + + primary_impact = proto.Field(proto.MESSAGE, number=5, message="Impact",) + + additional_impact = proto.RepeatedField(proto.MESSAGE, number=6, message="Impact",) + + content = proto.Field(proto.MESSAGE, number=7, message="RecommendationContent",) + + state_info = proto.Field( + proto.MESSAGE, number=10, message="RecommendationStateInfo", + ) + + etag = proto.Field(proto.STRING, number=11) + + associated_insights = proto.RepeatedField( + proto.MESSAGE, number=14, message=InsightReference, + ) + + +class RecommendationContent(proto.Message): + r"""Contains what resources are changing and how they are + changing. + + Attributes: + operation_groups (Sequence[~.recommendation.OperationGroup]): + Operations to one or more Google Cloud + resources grouped in such a way that, all + operations within one group are expected to be + performed atomically and in an order. + """ + + operation_groups = proto.RepeatedField( + proto.MESSAGE, number=2, message="OperationGroup", + ) + + +class OperationGroup(proto.Message): + r"""Group of operations that need to be performed atomically. + + Attributes: + operations (Sequence[~.recommendation.Operation]): + List of operations across one or more + resources that belong to this group. Loosely + based on RFC6902 and should be performed in the + order they appear. + """ + + operations = proto.RepeatedField(proto.MESSAGE, number=1, message="Operation",) + + +class Operation(proto.Message): + r"""Contains an operation for a resource loosely based on the JSON-PATCH + format with support for: + + - Custom filters for describing partial array patch. + - Extended path values for describing nested arrays. + - Custom fields for describing the resource for which the operation + is being described. + - Allows extension to custom operations not natively supported by + RFC6902. See https://tools.ietf.org/html/rfc6902 for details on + the original RFC. + + Attributes: + action (str): + Type of this operation. Contains one of + 'and', 'remove', 'replace', 'move', 'copy', + 'test' and 'custom' operations. This field is + case-insensitive and always populated. + resource_type (str): + Type of GCP resource being modified/tested. + This field is always populated. Example: + cloudresourcemanager.googleapis.com/Project, + compute.googleapis.com/Instance + resource (str): + Contains the fully qualified resource name. + This field is always populated. ex: + //cloudresourcemanager.googleapis.com/projects/foo. + path (str): + Path to the target field being operated on. + If the operation is at the resource level, then + path should be "/". This field is always + populated. + source_resource (str): + Can be set with action 'copy' to copy resource configuration + across different resources of the same type. Example: A + resource clone can be done via action = 'copy', path = "/", + from = "/", source_resource = and resource_name = . This + field is empty for all other values of ``action``. + source_path (str): + Can be set with action 'copy' or 'move' to indicate the + source field within resource or source_resource, ignored if + provided for other operation types. + value (~.struct.Value): + Value for the ``path`` field. Will be set for + actions:'add'/'replace'. Maybe set for action: 'test'. + Either this or ``value_matcher`` will be set for 'test' + operation. An exact match must be performed. + value_matcher (~.recommendation.ValueMatcher): + Can be set for action 'test' for advanced matching for the + value of 'path' field. Either this or ``value`` will be set + for 'test' operation. + path_filters (Sequence[~.recommendation.Operation.PathFiltersEntry]): + Set of filters to apply if ``path`` refers to array elements + or nested array elements in order to narrow down to a single + unique element that is being tested/modified. This is + intended to be an exact match per filter. To perform + advanced matching, use path_value_matchers. + + - Example: ``{ "/versions/*/name" : "it-123" + "/versions/*/targetSize/percent": 20 }`` + - Example: ``{ "/bindings/*/role": "roles/admin" + "/bindings/*/condition" : null }`` + - Example: ``{ "/bindings/*/role": "roles/admin" + "/bindings/*/members/*" : ["x@google.com", + "y@google.com"] }`` When both path_filters and + path_value_matchers are set, an implicit AND must be + performed. + path_value_matchers (Sequence[~.recommendation.Operation.PathValueMatchersEntry]): + Similar to path_filters, this contains set of filters to + apply if ``path`` field referes to array elements. This is + meant to support value matching beyond exact match. To + perform exact match, use path_filters. When both + path_filters and path_value_matchers are set, an implicit + AND must be performed. + """ + + action = proto.Field(proto.STRING, number=1) + + resource_type = proto.Field(proto.STRING, number=2) + + resource = proto.Field(proto.STRING, number=3) + + path = proto.Field(proto.STRING, number=4) + + source_resource = proto.Field(proto.STRING, number=5) + + source_path = proto.Field(proto.STRING, number=6) + + value = proto.Field( + proto.MESSAGE, number=7, oneof="path_value", message=struct.Value, + ) + + value_matcher = proto.Field( + proto.MESSAGE, number=10, oneof="path_value", message="ValueMatcher", + ) + + path_filters = proto.MapField( + proto.STRING, proto.MESSAGE, number=8, message=struct.Value, + ) + + path_value_matchers = proto.MapField( + proto.STRING, proto.MESSAGE, number=11, message="ValueMatcher", + ) + + +class ValueMatcher(proto.Message): + r"""Contains various matching options for values for a GCP + resource field. + + Attributes: + matches_pattern (str): + To be used for full regex matching. The + regular expression is using the Google RE2 + syntax + (https://github.com/google/re2/wiki/Syntax), so + to be used with RE2::FullMatch + """ + + matches_pattern = proto.Field(proto.STRING, number=1, oneof="match_variant") + + +class CostProjection(proto.Message): + r"""Contains metadata about how much money a recommendation can + save or incur. + + Attributes: + cost (~.money.Money): + An approximate projection on amount saved or + amount incurred. Negative cost units indicate + cost savings and positive cost units indicate + increase. See google.type.Money documentation + for positive/negative units. + duration (~.gp_duration.Duration): + Duration for which this cost applies. + """ + + cost = proto.Field(proto.MESSAGE, number=1, message=money.Money,) + + duration = proto.Field(proto.MESSAGE, number=2, message=gp_duration.Duration,) + + +class Impact(proto.Message): + r"""Contains the impact a recommendation can have for a given + category. + + Attributes: + category (~.recommendation.Impact.Category): + Category that is being targeted. + cost_projection (~.recommendation.CostProjection): + Use with CategoryType.COST + """ + + class Category(proto.Enum): + r"""The category of the impact.""" + CATEGORY_UNSPECIFIED = 0 + COST = 1 + SECURITY = 2 + PERFORMANCE = 3 + MANAGEABILITY = 4 + + category = proto.Field(proto.ENUM, number=1, enum=Category,) + + cost_projection = proto.Field( + proto.MESSAGE, number=100, oneof="projection", message="CostProjection", + ) + + +class RecommendationStateInfo(proto.Message): + r"""Information for state. Contains state and metadata. + + Attributes: + state (~.recommendation.RecommendationStateInfo.State): + The state of the recommendation, Eg ACTIVE, + SUCCEEDED, FAILED. + state_metadata (Sequence[~.recommendation.RecommendationStateInfo.StateMetadataEntry]): + A map of metadata for the state, provided by + user or automations systems. + """ + + class State(proto.Enum): + r"""Represents Recommendation State.""" + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + CLAIMED = 6 + SUCCEEDED = 3 + FAILED = 4 + DISMISSED = 5 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + state_metadata = proto.MapField(proto.STRING, proto.STRING, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/recommender_v1beta1/types/recommender_service.py b/google/cloud/recommender_v1beta1/types/recommender_service.py new file mode 100644 index 0000000..11d2748 --- /dev/null +++ b/google/cloud/recommender_v1beta1/types/recommender_service.py @@ -0,0 +1,278 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.recommender_v1beta1.types import insight +from google.cloud.recommender_v1beta1.types import recommendation + + +__protobuf__ = proto.module( + package="google.cloud.recommender.v1beta1", + manifest={ + "ListInsightsRequest", + "ListInsightsResponse", + "GetInsightRequest", + "MarkInsightAcceptedRequest", + "ListRecommendationsRequest", + "ListRecommendationsResponse", + "GetRecommendationRequest", + "MarkRecommendationClaimedRequest", + "MarkRecommendationSucceededRequest", + "MarkRecommendationFailedRequest", + }, +) + + +class ListInsightsRequest(proto.Message): + r"""Request for the ``ListInsights`` method. + + Attributes: + parent (str): + Required. The container resource on which to execute the + request. Acceptable formats: + + 1. + + "projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]", + + LOCATION here refers to GCP Locations: + https://cloud.google.com/about/locations/ + page_size (int): + Optional. The maximum number of results to + return from this request. Non-positive values + are ignored. If not specified, the server will + determine the number of results to return. + page_token (str): + Optional. If present, retrieves the next batch of results + from the preceding call to this method. ``page_token`` must + be the value of ``next_page_token`` from the previous + response. The values of other method parameters must be + identical to those in the previous call. + filter (str): + Optional. Filter expression to restrict the insights + returned. Supported filter fields: state Eg: + \`state:"DISMISSED" or state:"ACTIVE". + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + filter = proto.Field(proto.STRING, number=4) + + +class ListInsightsResponse(proto.Message): + r"""Response to the ``ListInsights`` method. + + Attributes: + insights (Sequence[~.insight.Insight]): + The set of insights for the ``parent`` resource. + next_page_token (str): + A token that can be used to request the next + page of results. This field is empty if there + are no additional results. + """ + + @property + def raw_page(self): + return self + + insights = proto.RepeatedField(proto.MESSAGE, number=1, message=insight.Insight,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetInsightRequest(proto.Message): + r"""Request to the ``GetInsight`` method. + + Attributes: + name (str): + Required. Name of the insight. + """ + + name = proto.Field(proto.STRING, number=1) + + +class MarkInsightAcceptedRequest(proto.Message): + r"""Request for the ``MarkInsightAccepted`` method. + + Attributes: + name (str): + Required. Name of the insight. + state_metadata (Sequence[~.recommender_service.MarkInsightAcceptedRequest.StateMetadataEntry]): + Optional. State properties user wish to include with this + state. Full replace of the current state_metadata. + etag (str): + Required. Fingerprint of the Insight. + Provides optimistic locking. + """ + + name = proto.Field(proto.STRING, number=1) + + state_metadata = proto.MapField(proto.STRING, proto.STRING, number=2) + + etag = proto.Field(proto.STRING, number=3) + + +class ListRecommendationsRequest(proto.Message): + r"""Request for the ``ListRecommendations`` method. + + Attributes: + parent (str): + Required. The container resource on which to execute the + request. Acceptable formats: + + 1. + + "projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]", + + LOCATION here refers to GCP Locations: + https://cloud.google.com/about/locations/ + page_size (int): + Optional. The maximum number of results to + return from this request. Non-positive values + are ignored. If not specified, the server will + determine the number of results to return. + page_token (str): + Optional. If present, retrieves the next batch of results + from the preceding call to this method. ``page_token`` must + be the value of ``next_page_token`` from the previous + response. The values of other method parameters must be + identical to those in the previous call. + filter (str): + Filter expression to restrict the recommendations returned. + Supported filter fields: state_info.state Eg: + \`state_info.state:"DISMISSED" or state_info.state:"FAILED". + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + filter = proto.Field(proto.STRING, number=5) + + +class ListRecommendationsResponse(proto.Message): + r"""Response to the ``ListRecommendations`` method. + + Attributes: + recommendations (Sequence[~.recommendation.Recommendation]): + The set of recommendations for the ``parent`` resource. + next_page_token (str): + A token that can be used to request the next + page of results. This field is empty if there + are no additional results. + """ + + @property + def raw_page(self): + return self + + recommendations = proto.RepeatedField( + proto.MESSAGE, number=1, message=recommendation.Recommendation, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetRecommendationRequest(proto.Message): + r"""Request to the ``GetRecommendation`` method. + + Attributes: + name (str): + Required. Name of the recommendation. + """ + + name = proto.Field(proto.STRING, number=1) + + +class MarkRecommendationClaimedRequest(proto.Message): + r"""Request for the ``MarkRecommendationClaimed`` Method. + + Attributes: + name (str): + Required. Name of the recommendation. + state_metadata (Sequence[~.recommender_service.MarkRecommendationClaimedRequest.StateMetadataEntry]): + State properties to include with this state. Overwrites any + existing ``state_metadata``. Keys must match the regex + ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match the regex + ``/^[a-zA-Z0-9_./-]{0,255}$/``. + etag (str): + Required. Fingerprint of the Recommendation. + Provides optimistic locking. + """ + + name = proto.Field(proto.STRING, number=1) + + state_metadata = proto.MapField(proto.STRING, proto.STRING, number=2) + + etag = proto.Field(proto.STRING, number=3) + + +class MarkRecommendationSucceededRequest(proto.Message): + r"""Request for the ``MarkRecommendationSucceeded`` Method. + + Attributes: + name (str): + Required. Name of the recommendation. + state_metadata (Sequence[~.recommender_service.MarkRecommendationSucceededRequest.StateMetadataEntry]): + State properties to include with this state. Overwrites any + existing ``state_metadata``. Keys must match the regex + ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match the regex + ``/^[a-zA-Z0-9_./-]{0,255}$/``. + etag (str): + Required. Fingerprint of the Recommendation. + Provides optimistic locking. + """ + + name = proto.Field(proto.STRING, number=1) + + state_metadata = proto.MapField(proto.STRING, proto.STRING, number=2) + + etag = proto.Field(proto.STRING, number=3) + + +class MarkRecommendationFailedRequest(proto.Message): + r"""Request for the ``MarkRecommendationFailed`` Method. + + Attributes: + name (str): + Required. Name of the recommendation. + state_metadata (Sequence[~.recommender_service.MarkRecommendationFailedRequest.StateMetadataEntry]): + State properties to include with this state. Overwrites any + existing ``state_metadata``. Keys must match the regex + ``/^[a-z0-9][a-z0-9_.-]{0,62}$/``. Values must match the regex + ``/^[a-zA-Z0-9_./-]{0,255}$/``. + etag (str): + Required. Fingerprint of the Recommendation. + Provides optimistic locking. + """ + + name = proto.Field(proto.STRING, number=1) + + state_metadata = proto.MapField(proto.STRING, proto.STRING, number=2) + + etag = proto.Field(proto.STRING, number=3) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/mypy.ini b/mypy.ini index f23e6b5..4505b48 100644 --- a/mypy.ini +++ b/mypy.ini @@ -1,3 +1,3 @@ [mypy] -python_version = 3.5 +python_version = 3.6 namespace_packages = True diff --git a/noxfile.py b/noxfile.py index 12e01fe..8f4826e 100644 --- a/noxfile.py +++ b/noxfile.py @@ -72,7 +72,9 @@ def default(session): # Install all test dependencies, then install this package in-place. session.install("asyncmock", "pytest-asyncio") - session.install("mock", "pytest", "pytest-cov") + session.install( + "mock", "pytest", "pytest-cov", + ) session.install("-e", ".") # Run py.test against the unit tests. @@ -141,7 +143,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=80") + session.run("coverage", "report", "--show-missing", "--fail-under=100") session.run("coverage", "erase") @@ -151,7 +153,7 @@ def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") + session.install("sphinx", "alabaster", "recommonmark") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( diff --git a/samples/AUTHORING_GUIDE.md b/samples/AUTHORING_GUIDE.md new file mode 100644 index 0000000..55c97b3 --- /dev/null +++ b/samples/AUTHORING_GUIDE.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/AUTHORING_GUIDE.md \ No newline at end of file diff --git a/samples/CONTRIBUTING.md b/samples/CONTRIBUTING.md new file mode 100644 index 0000000..34c882b --- /dev/null +++ b/samples/CONTRIBUTING.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/CONTRIBUTING.md \ No newline at end of file diff --git a/scripts/fixup_recommender_v1_keywords.py b/scripts/fixup_recommender_v1_keywords.py new file mode 100644 index 0000000..bd80e8c --- /dev/null +++ b/scripts/fixup_recommender_v1_keywords.py @@ -0,0 +1,186 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class recommenderCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'get_insight': ('name', ), + 'get_recommendation': ('name', ), + 'list_insights': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_recommendations': ('parent', 'page_size', 'page_token', 'filter', ), + 'mark_insight_accepted': ('name', 'etag', 'state_metadata', ), + 'mark_recommendation_claimed': ('name', 'etag', 'state_metadata', ), + 'mark_recommendation_failed': ('name', 'etag', 'state_metadata', ), + 'mark_recommendation_succeeded': ('name', 'etag', 'state_metadata', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=recommenderCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the recommender client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/fixup_recommender_v1beta1_keywords.py b/scripts/fixup_recommender_v1beta1_keywords.py new file mode 100644 index 0000000..bd80e8c --- /dev/null +++ b/scripts/fixup_recommender_v1beta1_keywords.py @@ -0,0 +1,186 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class recommenderCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'get_insight': ('name', ), + 'get_recommendation': ('name', ), + 'list_insights': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_recommendations': ('parent', 'page_size', 'page_token', 'filter', ), + 'mark_insight_accepted': ('name', 'etag', 'state_metadata', ), + 'mark_recommendation_claimed': ('name', 'etag', 'state_metadata', ), + 'mark_recommendation_failed': ('name', 'etag', 'state_metadata', ), + 'mark_recommendation_succeeded': ('name', 'etag', 'state_metadata', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=recommenderCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the recommender client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/setup.py b/setup.py index 6c2940f..1869d65 100644 --- a/setup.py +++ b/setup.py @@ -23,7 +23,12 @@ description = "Cloud Recommender API client library" version = "1.1.1" release_status = "Development Status :: 5 - Production/Stable" -dependencies = ["google-api-core[grpc] >= 1.14.0, < 2.0.0dev"] +dependencies = ["google-api-core[grpc] >= 1.22.0, < 2.0.0dev", "proto-plus >= 1.10.0"] +extras = {"libcst": "libcst >= 0.2.5"} +scripts = [ + "scripts/fixup_recommender_v1_keywords.py", + "scripts/fixup_recommender_v1beta1_keywords.py", +] package_root = os.path.abspath(os.path.dirname(__file__)) @@ -32,7 +37,9 @@ readme = readme_file.read() packages = [ - package for package in setuptools.find_packages() if package.startswith("google") + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") ] namespaces = ["google"] @@ -54,9 +61,9 @@ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", "Topic :: Internet", ], @@ -64,7 +71,9 @@ packages=packages, namespace_packages=namespaces, install_requires=dependencies, - python_requires=">=3.5", + extras_require=extras, + python_requires=">=3.6", + scripts=scripts, include_package_data=True, zip_safe=False, ) diff --git a/synth.metadata b/synth.metadata index 5cc126c..64b4c90 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,30 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-recommender.git", - "sha": "ddbef1904ab1d5736c777de18f666b1c48ab5143" + "remote": "git@github.com:danoscarmike/python-recommender", + "sha": "8538b29f6938d2967ef71845ddf43e2c286a6147" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "ab0498dc4bd2bcfcb70ab257e8edfa00f86083a6", - "internalRef": "339531446" + "sha": "7ea91db77f53f169a08726bd33efb73042c38284", + "internalRef": "343321102" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "ea52b8a0bd560f72f376efcf45197fb7c8869120" + "sha": "68742c6016bf0d16948a572633d17955a8737414" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "ea52b8a0bd560f72f376efcf45197fb7c8869120" + "sha": "68742c6016bf0d16948a572633d17955a8737414" } } ], @@ -49,110 +49,5 @@ "generator": "bazel" } } - ], - "generatedFiles": [ - ".coveragerc", - ".flake8", - ".github/CONTRIBUTING.md", - ".github/ISSUE_TEMPLATE/bug_report.md", - ".github/ISSUE_TEMPLATE/feature_request.md", - ".github/ISSUE_TEMPLATE/support_request.md", - ".github/PULL_REQUEST_TEMPLATE.md", - ".github/release-please.yml", - ".github/snippet-bot.yml", - ".gitignore", - ".kokoro/build.sh", - ".kokoro/continuous/common.cfg", - ".kokoro/continuous/continuous.cfg", - ".kokoro/docker/docs/Dockerfile", - ".kokoro/docker/docs/fetch_gpg_keys.sh", - ".kokoro/docs/common.cfg", - ".kokoro/docs/docs-presubmit.cfg", - ".kokoro/docs/docs.cfg", - ".kokoro/populate-secrets.sh", - ".kokoro/presubmit/common.cfg", - ".kokoro/presubmit/presubmit.cfg", - ".kokoro/publish-docs.sh", - ".kokoro/release.sh", - ".kokoro/release/common.cfg", - ".kokoro/release/release.cfg", - ".kokoro/samples/lint/common.cfg", - ".kokoro/samples/lint/continuous.cfg", - ".kokoro/samples/lint/periodic.cfg", - ".kokoro/samples/lint/presubmit.cfg", - ".kokoro/samples/python3.6/common.cfg", - ".kokoro/samples/python3.6/continuous.cfg", - ".kokoro/samples/python3.6/periodic.cfg", - ".kokoro/samples/python3.6/presubmit.cfg", - ".kokoro/samples/python3.7/common.cfg", - ".kokoro/samples/python3.7/continuous.cfg", - ".kokoro/samples/python3.7/periodic.cfg", - ".kokoro/samples/python3.7/presubmit.cfg", - ".kokoro/samples/python3.8/common.cfg", - ".kokoro/samples/python3.8/continuous.cfg", - ".kokoro/samples/python3.8/periodic.cfg", - ".kokoro/samples/python3.8/presubmit.cfg", - ".kokoro/test-samples.sh", - ".kokoro/trampoline.sh", - ".kokoro/trampoline_v2.sh", - ".trampolinerc", - "CODE_OF_CONDUCT.md", - "CONTRIBUTING.rst", - "LICENSE", - "MANIFEST.in", - "docs/_static/custom.css", - "docs/_templates/layout.html", - "docs/conf.py", - "docs/gapic/v1/api.rst", - "docs/gapic/v1/types.rst", - "docs/gapic/v1beta1/api.rst", - "docs/gapic/v1beta1/types.rst", - "docs/multiprocessing.rst", - "google/__init__.py", - "google/cloud/__init__.py", - "google/cloud/recommender.py", - "google/cloud/recommender_v1/__init__.py", - "google/cloud/recommender_v1/gapic/__init__.py", - "google/cloud/recommender_v1/gapic/enums.py", - "google/cloud/recommender_v1/gapic/recommender_client.py", - "google/cloud/recommender_v1/gapic/recommender_client_config.py", - "google/cloud/recommender_v1/gapic/transports/__init__.py", - "google/cloud/recommender_v1/gapic/transports/recommender_grpc_transport.py", - "google/cloud/recommender_v1/proto/__init__.py", - "google/cloud/recommender_v1/proto/insight_pb2.py", - "google/cloud/recommender_v1/proto/insight_pb2_grpc.py", - "google/cloud/recommender_v1/proto/recommendation_pb2.py", - "google/cloud/recommender_v1/proto/recommendation_pb2_grpc.py", - "google/cloud/recommender_v1/proto/recommender_service_pb2.py", - "google/cloud/recommender_v1/proto/recommender_service_pb2_grpc.py", - "google/cloud/recommender_v1/types.py", - "google/cloud/recommender_v1beta1/__init__.py", - "google/cloud/recommender_v1beta1/gapic/__init__.py", - "google/cloud/recommender_v1beta1/gapic/enums.py", - "google/cloud/recommender_v1beta1/gapic/recommender_client.py", - "google/cloud/recommender_v1beta1/gapic/recommender_client_config.py", - "google/cloud/recommender_v1beta1/gapic/transports/__init__.py", - "google/cloud/recommender_v1beta1/gapic/transports/recommender_grpc_transport.py", - "google/cloud/recommender_v1beta1/proto/__init__.py", - "google/cloud/recommender_v1beta1/proto/insight_pb2.py", - "google/cloud/recommender_v1beta1/proto/insight_pb2_grpc.py", - "google/cloud/recommender_v1beta1/proto/recommendation_pb2.py", - "google/cloud/recommender_v1beta1/proto/recommendation_pb2_grpc.py", - "google/cloud/recommender_v1beta1/proto/recommender_service_pb2.py", - "google/cloud/recommender_v1beta1/proto/recommender_service_pb2_grpc.py", - "google/cloud/recommender_v1beta1/types.py", - "noxfile.py", - "renovate.json", - "scripts/decrypt-secrets.sh", - "scripts/readme-gen/readme_gen.py", - "scripts/readme-gen/templates/README.tmpl.rst", - "scripts/readme-gen/templates/auth.tmpl.rst", - "scripts/readme-gen/templates/auth_api_key.tmpl.rst", - "scripts/readme-gen/templates/install_deps.tmpl.rst", - "scripts/readme-gen/templates/install_portaudio.tmpl.rst", - "setup.cfg", - "testing/.gitignore", - "tests/unit/gapic/v1/test_recommender_client_v1.py", - "tests/unit/gapic/v1beta1/test_recommender_client_v1beta1.py" ] } \ No newline at end of file diff --git a/synth.py b/synth.py index 96d1027..359fece 100644 --- a/synth.py +++ b/synth.py @@ -33,44 +33,37 @@ version=version, bazel_target=f"//google/cloud/recommender/{version}:recommender-{version}-py", ) - s.move(library, excludes=["nox.py", "docs/index.rst", "README.rst", "setup.py"]) + s.move(library, excludes=["docs/index.rst", "README.rst", "setup.py"]) # Fix docstring with regex pattern that breaks docgen -s.replace("google/**/recommender_client.py", "(/\^.*\$/)", "``\g<1>``") +s.replace("google/**/*client.py", "(/\^.*\$/)", "``\g<1>``") # Fix more regex in docstrings -s.replace("google/**/*_pb2.py", ":math:`(/)", "\g<1>") -s.replace("google/**/*_pb2.py", "`/\.", "/.") -s.replace("google/**/*_pb2.py", "(regex\s+)(/.*?/)\.", "\g<1>``\g<2>``.", flags=re.MULTILINE | re.DOTALL,) +s.replace( + "google/**/types/*.py", + "(regex\s+)(/.*?/)\.", + "\g<1>``\g<2>``.", + flags=re.MULTILINE | re.DOTALL, +) # Fix docstring with JSON example by wrapping with backticks s.replace( - "google/**/recommendation_pb2.py", + "google/**/types/recommendation.py", "( - Example: )(\{.*?\})", "\g<1>``\g<2>``", flags=re.MULTILINE | re.DOTALL, ) -# Fix multiline path -s.replace( - "google/**/recommendation_pb2.py", - """projects/\[PROJECT_NUMBER\]/location - s/\[LOCATION\]/insightTypes/\[INSIGHT\_TYPE\_ID\]/insights/\[INSIGHT_ - ID\]""", - """``projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]/insights/[INSIGHT_ID]``""" -) - - -python.fix_pb2_headers() -python.fix_pb2_grpc_headers() # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- -templated_files = common.py_library(microgenerator=True, cov_level=80) -s.move(templated_files) - -# TODO(busunkim): Use latest sphinx after microgenerator transition -s.replace("noxfile.py", """['"]sphinx['"]""", '"sphinx<3.0.0"') +templated_files = common.py_library( + samples=False, # set to True only if there are samples + microgenerator=True, +) +s.move( + templated_files, excludes=[".coveragerc"] +) # microgenerator has a good .coveragerc file s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/tests/unit/gapic/recommender_v1/__init__.py b/tests/unit/gapic/recommender_v1/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tests/unit/gapic/recommender_v1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/recommender_v1/test_recommender.py b/tests/unit/gapic/recommender_v1/test_recommender.py new file mode 100644 index 0000000..1ee5b68 --- /dev/null +++ b/tests/unit/gapic/recommender_v1/test_recommender.py @@ -0,0 +1,3115 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.recommender_v1.services.recommender import RecommenderAsyncClient +from google.cloud.recommender_v1.services.recommender import RecommenderClient +from google.cloud.recommender_v1.services.recommender import pagers +from google.cloud.recommender_v1.services.recommender import transports +from google.cloud.recommender_v1.types import insight +from google.cloud.recommender_v1.types import recommendation +from google.cloud.recommender_v1.types import recommender_service +from google.oauth2 import service_account +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RecommenderClient._get_default_mtls_endpoint(None) is None + assert ( + RecommenderClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + RecommenderClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RecommenderClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RecommenderClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert RecommenderClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [RecommenderClient, RecommenderAsyncClient]) +def test_recommender_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + + assert client.transport._host == "recommender.googleapis.com:443" + + +def test_recommender_client_get_transport_class(): + transport = RecommenderClient.get_transport_class() + assert transport == transports.RecommenderGrpcTransport + + transport = RecommenderClient.get_transport_class("grpc") + assert transport == transports.RecommenderGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RecommenderClient, transports.RecommenderGrpcTransport, "grpc"), + ( + RecommenderAsyncClient, + transports.RecommenderGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + RecommenderClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommenderClient) +) +@mock.patch.object( + RecommenderAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RecommenderAsyncClient), +) +def test_recommender_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RecommenderClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RecommenderClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (RecommenderClient, transports.RecommenderGrpcTransport, "grpc", "true"), + ( + RecommenderAsyncClient, + transports.RecommenderGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (RecommenderClient, transports.RecommenderGrpcTransport, "grpc", "false"), + ( + RecommenderAsyncClient, + transports.RecommenderGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + RecommenderClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommenderClient) +) +@mock.patch.object( + RecommenderAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RecommenderAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_recommender_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RecommenderClient, transports.RecommenderGrpcTransport, "grpc"), + ( + RecommenderAsyncClient, + transports.RecommenderGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_recommender_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RecommenderClient, transports.RecommenderGrpcTransport, "grpc"), + ( + RecommenderAsyncClient, + transports.RecommenderGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_recommender_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_recommender_client_client_options_from_dict(): + with mock.patch( + "google.cloud.recommender_v1.services.recommender.transports.RecommenderGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = RecommenderClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_list_insights( + transport: str = "grpc", request_type=recommender_service.ListInsightsRequest +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = recommender_service.ListInsightsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.ListInsightsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListInsightsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_insights_from_dict(): + test_list_insights(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_insights_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.ListInsightsRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListInsightsResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.ListInsightsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInsightsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_insights_async_from_dict(): + await test_list_insights_async(request_type=dict) + + +def test_list_insights_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.ListInsightsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + call.return_value = recommender_service.ListInsightsResponse() + + client.list_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_insights_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.ListInsightsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListInsightsResponse() + ) + + await client.list_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_insights_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = recommender_service.ListInsightsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_insights(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_insights_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_insights( + recommender_service.ListInsightsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_insights_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = recommender_service.ListInsightsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListInsightsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_insights(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_insights_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_insights( + recommender_service.ListInsightsRequest(), parent="parent_value", + ) + + +def test_list_insights_pager(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(), insight.Insight(),], + next_page_token="abc", + ), + recommender_service.ListInsightsResponse( + insights=[], next_page_token="def", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(),], next_page_token="ghi", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_insights(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, insight.Insight) for i in results) + + +def test_list_insights_pages(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(), insight.Insight(),], + next_page_token="abc", + ), + recommender_service.ListInsightsResponse( + insights=[], next_page_token="def", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(),], next_page_token="ghi", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(),], + ), + RuntimeError, + ) + pages = list(client.list_insights(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_insights_async_pager(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_insights), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(), insight.Insight(),], + next_page_token="abc", + ), + recommender_service.ListInsightsResponse( + insights=[], next_page_token="def", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(),], next_page_token="ghi", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(),], + ), + RuntimeError, + ) + async_pager = await client.list_insights(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, insight.Insight) for i in responses) + + +@pytest.mark.asyncio +async def test_list_insights_async_pages(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_insights), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(), insight.Insight(),], + next_page_token="abc", + ), + recommender_service.ListInsightsResponse( + insights=[], next_page_token="def", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(),], next_page_token="ghi", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_insights(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_insight( + transport: str = "grpc", request_type=recommender_service.GetInsightRequest +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + etag="etag_value", + ) + + response = client.get_insight(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.GetInsightRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, insight.Insight) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.target_resources == ["target_resources_value"] + + assert response.insight_subtype == "insight_subtype_value" + + assert response.category == insight.Insight.Category.COST + + assert response.etag == "etag_value" + + +def test_get_insight_from_dict(): + test_get_insight(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_insight_async( + transport: str = "grpc_asyncio", request_type=recommender_service.GetInsightRequest +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + etag="etag_value", + ) + ) + + response = await client.get_insight(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.GetInsightRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, insight.Insight) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.target_resources == ["target_resources_value"] + + assert response.insight_subtype == "insight_subtype_value" + + assert response.category == insight.Insight.Category.COST + + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_get_insight_async_from_dict(): + await test_get_insight_async(request_type=dict) + + +def test_get_insight_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.GetInsightRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + call.return_value = insight.Insight() + + client.get_insight(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_insight_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.GetInsightRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(insight.Insight()) + + await client.get_insight(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_insight_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = insight.Insight() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_insight(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_insight_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_insight( + recommender_service.GetInsightRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_insight_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = insight.Insight() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(insight.Insight()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_insight(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_insight_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_insight( + recommender_service.GetInsightRequest(), name="name_value", + ) + + +def test_mark_insight_accepted( + transport: str = "grpc", request_type=recommender_service.MarkInsightAcceptedRequest +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + etag="etag_value", + ) + + response = client.mark_insight_accepted(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkInsightAcceptedRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, insight.Insight) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.target_resources == ["target_resources_value"] + + assert response.insight_subtype == "insight_subtype_value" + + assert response.category == insight.Insight.Category.COST + + assert response.etag == "etag_value" + + +def test_mark_insight_accepted_from_dict(): + test_mark_insight_accepted(request_type=dict) + + +@pytest.mark.asyncio +async def test_mark_insight_accepted_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.MarkInsightAcceptedRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + etag="etag_value", + ) + ) + + response = await client.mark_insight_accepted(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkInsightAcceptedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, insight.Insight) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.target_resources == ["target_resources_value"] + + assert response.insight_subtype == "insight_subtype_value" + + assert response.category == insight.Insight.Category.COST + + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_insight_accepted_async_from_dict(): + await test_mark_insight_accepted_async(request_type=dict) + + +def test_mark_insight_accepted_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkInsightAcceptedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + call.return_value = insight.Insight() + + client.mark_insight_accepted(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_mark_insight_accepted_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkInsightAcceptedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(insight.Insight()) + + await client.mark_insight_accepted(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_mark_insight_accepted_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = insight.Insight() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mark_insight_accepted( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +def test_mark_insight_accepted_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mark_insight_accepted( + recommender_service.MarkInsightAcceptedRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +@pytest.mark.asyncio +async def test_mark_insight_accepted_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = insight.Insight() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(insight.Insight()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mark_insight_accepted( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_insight_accepted_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.mark_insight_accepted( + recommender_service.MarkInsightAcceptedRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +def test_list_recommendations( + transport: str = "grpc", request_type=recommender_service.ListRecommendationsRequest +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommender_service.ListRecommendationsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_recommendations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.ListRecommendationsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListRecommendationsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_recommendations_from_dict(): + test_list_recommendations(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_recommendations_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.ListRecommendationsRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListRecommendationsResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_recommendations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.ListRecommendationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRecommendationsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_recommendations_async_from_dict(): + await test_list_recommendations_async(request_type=dict) + + +def test_list_recommendations_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.ListRecommendationsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + call.return_value = recommender_service.ListRecommendationsResponse() + + client.list_recommendations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_recommendations_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.ListRecommendationsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListRecommendationsResponse() + ) + + await client.list_recommendations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_recommendations_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommender_service.ListRecommendationsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_recommendations( + parent="parent_value", filter="filter_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].filter == "filter_value" + + +def test_list_recommendations_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_recommendations( + recommender_service.ListRecommendationsRequest(), + parent="parent_value", + filter="filter_value", + ) + + +@pytest.mark.asyncio +async def test_list_recommendations_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommender_service.ListRecommendationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListRecommendationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_recommendations( + parent="parent_value", filter="filter_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].filter == "filter_value" + + +@pytest.mark.asyncio +async def test_list_recommendations_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_recommendations( + recommender_service.ListRecommendationsRequest(), + parent="parent_value", + filter="filter_value", + ) + + +def test_list_recommendations_pager(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + next_page_token="abc", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[], next_page_token="def", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[recommendation.Recommendation(),], + next_page_token="ghi", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_recommendations(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, recommendation.Recommendation) for i in results) + + +def test_list_recommendations_pages(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + next_page_token="abc", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[], next_page_token="def", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[recommendation.Recommendation(),], + next_page_token="ghi", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_recommendations(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_recommendations_async_pager(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + next_page_token="abc", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[], next_page_token="def", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[recommendation.Recommendation(),], + next_page_token="ghi", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_recommendations(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, recommendation.Recommendation) for i in responses) + + +@pytest.mark.asyncio +async def test_list_recommendations_async_pages(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + next_page_token="abc", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[], next_page_token="def", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[recommendation.Recommendation(),], + next_page_token="ghi", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_recommendations(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_recommendation( + transport: str = "grpc", request_type=recommender_service.GetRecommendationRequest +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + + response = client.get_recommendation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.GetRecommendationRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +def test_get_recommendation_from_dict(): + test_get_recommendation(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_recommendation_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.GetRecommendationRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + ) + + response = await client.get_recommendation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.GetRecommendationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_get_recommendation_async_from_dict(): + await test_get_recommendation_async(request_type=dict) + + +def test_get_recommendation_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.GetRecommendationRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + + client.get_recommendation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_recommendation_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.GetRecommendationRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + + await client.get_recommendation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_recommendation_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_recommendation(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_recommendation_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_recommendation( + recommender_service.GetRecommendationRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_recommendation_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_recommendation(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_recommendation_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_recommendation( + recommender_service.GetRecommendationRequest(), name="name_value", + ) + + +def test_mark_recommendation_claimed( + transport: str = "grpc", + request_type=recommender_service.MarkRecommendationClaimedRequest, +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + + response = client.mark_recommendation_claimed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkRecommendationClaimedRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +def test_mark_recommendation_claimed_from_dict(): + test_mark_recommendation_claimed(request_type=dict) + + +@pytest.mark.asyncio +async def test_mark_recommendation_claimed_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.MarkRecommendationClaimedRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + ) + + response = await client.mark_recommendation_claimed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkRecommendationClaimedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_recommendation_claimed_async_from_dict(): + await test_mark_recommendation_claimed_async(request_type=dict) + + +def test_mark_recommendation_claimed_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkRecommendationClaimedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + + client.mark_recommendation_claimed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_mark_recommendation_claimed_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkRecommendationClaimedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + + await client.mark_recommendation_claimed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_mark_recommendation_claimed_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mark_recommendation_claimed( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +def test_mark_recommendation_claimed_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mark_recommendation_claimed( + recommender_service.MarkRecommendationClaimedRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +@pytest.mark.asyncio +async def test_mark_recommendation_claimed_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mark_recommendation_claimed( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_recommendation_claimed_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.mark_recommendation_claimed( + recommender_service.MarkRecommendationClaimedRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +def test_mark_recommendation_succeeded( + transport: str = "grpc", + request_type=recommender_service.MarkRecommendationSucceededRequest, +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + + response = client.mark_recommendation_succeeded(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkRecommendationSucceededRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +def test_mark_recommendation_succeeded_from_dict(): + test_mark_recommendation_succeeded(request_type=dict) + + +@pytest.mark.asyncio +async def test_mark_recommendation_succeeded_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.MarkRecommendationSucceededRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + ) + + response = await client.mark_recommendation_succeeded(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkRecommendationSucceededRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_recommendation_succeeded_async_from_dict(): + await test_mark_recommendation_succeeded_async(request_type=dict) + + +def test_mark_recommendation_succeeded_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkRecommendationSucceededRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + + client.mark_recommendation_succeeded(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_mark_recommendation_succeeded_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkRecommendationSucceededRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + + await client.mark_recommendation_succeeded(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_mark_recommendation_succeeded_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mark_recommendation_succeeded( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +def test_mark_recommendation_succeeded_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mark_recommendation_succeeded( + recommender_service.MarkRecommendationSucceededRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +@pytest.mark.asyncio +async def test_mark_recommendation_succeeded_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mark_recommendation_succeeded( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_recommendation_succeeded_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.mark_recommendation_succeeded( + recommender_service.MarkRecommendationSucceededRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +def test_mark_recommendation_failed( + transport: str = "grpc", + request_type=recommender_service.MarkRecommendationFailedRequest, +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + + response = client.mark_recommendation_failed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkRecommendationFailedRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +def test_mark_recommendation_failed_from_dict(): + test_mark_recommendation_failed(request_type=dict) + + +@pytest.mark.asyncio +async def test_mark_recommendation_failed_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.MarkRecommendationFailedRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + ) + + response = await client.mark_recommendation_failed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkRecommendationFailedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_recommendation_failed_async_from_dict(): + await test_mark_recommendation_failed_async(request_type=dict) + + +def test_mark_recommendation_failed_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkRecommendationFailedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + + client.mark_recommendation_failed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_mark_recommendation_failed_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkRecommendationFailedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + + await client.mark_recommendation_failed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_mark_recommendation_failed_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mark_recommendation_failed( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +def test_mark_recommendation_failed_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mark_recommendation_failed( + recommender_service.MarkRecommendationFailedRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +@pytest.mark.asyncio +async def test_mark_recommendation_failed_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mark_recommendation_failed( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_recommendation_failed_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.mark_recommendation_failed( + recommender_service.MarkRecommendationFailedRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommenderClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommenderClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = RecommenderClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RecommenderGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [transports.RecommenderGrpcTransport, transports.RecommenderGrpcAsyncIOTransport], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.RecommenderGrpcTransport,) + + +def test_recommender_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.RecommenderTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_recommender_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.recommender_v1.services.recommender.transports.RecommenderTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RecommenderTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_insights", + "get_insight", + "mark_insight_accepted", + "list_recommendations", + "get_recommendation", + "mark_recommendation_claimed", + "mark_recommendation_succeeded", + "mark_recommendation_failed", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_recommender_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.recommender_v1.services.recommender.transports.RecommenderTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.RecommenderTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_recommender_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.recommender_v1.services.recommender.transports.RecommenderTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.RecommenderTransport() + adc.assert_called_once() + + +def test_recommender_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + RecommenderClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_recommender_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.RecommenderGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_recommender_host_no_port(): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="recommender.googleapis.com" + ), + ) + assert client.transport._host == "recommender.googleapis.com:443" + + +def test_recommender_host_with_port(): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="recommender.googleapis.com:8000" + ), + ) + assert client.transport._host == "recommender.googleapis.com:8000" + + +def test_recommender_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.RecommenderGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_recommender_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.RecommenderGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +@pytest.mark.parametrize( + "transport_class", + [transports.RecommenderGrpcTransport, transports.RecommenderGrpcAsyncIOTransport], +) +def test_recommender_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +@pytest.mark.parametrize( + "transport_class", + [transports.RecommenderGrpcTransport, transports.RecommenderGrpcAsyncIOTransport], +) +def test_recommender_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_insight_path(): + project = "squid" + location = "clam" + insight_type = "whelk" + insight = "octopus" + + expected = "projects/{project}/locations/{location}/insightTypes/{insight_type}/insights/{insight}".format( + project=project, location=location, insight_type=insight_type, insight=insight, + ) + actual = RecommenderClient.insight_path(project, location, insight_type, insight) + assert expected == actual + + +def test_parse_insight_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "insight_type": "cuttlefish", + "insight": "mussel", + } + path = RecommenderClient.insight_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_insight_path(path) + assert expected == actual + + +def test_insight_type_path(): + project = "winkle" + location = "nautilus" + insight_type = "scallop" + + expected = "projects/{project}/locations/{location}/insightTypes/{insight_type}".format( + project=project, location=location, insight_type=insight_type, + ) + actual = RecommenderClient.insight_type_path(project, location, insight_type) + assert expected == actual + + +def test_parse_insight_type_path(): + expected = { + "project": "abalone", + "location": "squid", + "insight_type": "clam", + } + path = RecommenderClient.insight_type_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_insight_type_path(path) + assert expected == actual + + +def test_recommendation_path(): + project = "whelk" + location = "octopus" + recommender = "oyster" + recommendation = "nudibranch" + + expected = "projects/{project}/locations/{location}/recommenders/{recommender}/recommendations/{recommendation}".format( + project=project, + location=location, + recommender=recommender, + recommendation=recommendation, + ) + actual = RecommenderClient.recommendation_path( + project, location, recommender, recommendation + ) + assert expected == actual + + +def test_parse_recommendation_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "recommender": "winkle", + "recommendation": "nautilus", + } + path = RecommenderClient.recommendation_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_recommendation_path(path) + assert expected == actual + + +def test_recommender_path(): + project = "scallop" + location = "abalone" + recommender = "squid" + + expected = "projects/{project}/locations/{location}/recommenders/{recommender}".format( + project=project, location=location, recommender=recommender, + ) + actual = RecommenderClient.recommender_path(project, location, recommender) + assert expected == actual + + +def test_parse_recommender_path(): + expected = { + "project": "clam", + "location": "whelk", + "recommender": "octopus", + } + path = RecommenderClient.recommender_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_recommender_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "oyster" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RecommenderClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = RecommenderClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "cuttlefish" + + expected = "folders/{folder}".format(folder=folder,) + actual = RecommenderClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = RecommenderClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "winkle" + + expected = "organizations/{organization}".format(organization=organization,) + actual = RecommenderClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = RecommenderClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "scallop" + + expected = "projects/{project}".format(project=project,) + actual = RecommenderClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = RecommenderClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "squid" + location = "clam" + + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = RecommenderClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = RecommenderClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.RecommenderTransport, "_prep_wrapped_messages" + ) as prep: + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RecommenderTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RecommenderClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/recommender_v1beta1/__init__.py b/tests/unit/gapic/recommender_v1beta1/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tests/unit/gapic/recommender_v1beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/recommender_v1beta1/test_recommender.py b/tests/unit/gapic/recommender_v1beta1/test_recommender.py new file mode 100644 index 0000000..2844736 --- /dev/null +++ b/tests/unit/gapic/recommender_v1beta1/test_recommender.py @@ -0,0 +1,3115 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.recommender_v1beta1.services.recommender import RecommenderAsyncClient +from google.cloud.recommender_v1beta1.services.recommender import RecommenderClient +from google.cloud.recommender_v1beta1.services.recommender import pagers +from google.cloud.recommender_v1beta1.services.recommender import transports +from google.cloud.recommender_v1beta1.types import insight +from google.cloud.recommender_v1beta1.types import recommendation +from google.cloud.recommender_v1beta1.types import recommender_service +from google.oauth2 import service_account +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RecommenderClient._get_default_mtls_endpoint(None) is None + assert ( + RecommenderClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + RecommenderClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RecommenderClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RecommenderClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert RecommenderClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [RecommenderClient, RecommenderAsyncClient]) +def test_recommender_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + + assert client.transport._host == "recommender.googleapis.com:443" + + +def test_recommender_client_get_transport_class(): + transport = RecommenderClient.get_transport_class() + assert transport == transports.RecommenderGrpcTransport + + transport = RecommenderClient.get_transport_class("grpc") + assert transport == transports.RecommenderGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RecommenderClient, transports.RecommenderGrpcTransport, "grpc"), + ( + RecommenderAsyncClient, + transports.RecommenderGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + RecommenderClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommenderClient) +) +@mock.patch.object( + RecommenderAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RecommenderAsyncClient), +) +def test_recommender_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RecommenderClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RecommenderClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (RecommenderClient, transports.RecommenderGrpcTransport, "grpc", "true"), + ( + RecommenderAsyncClient, + transports.RecommenderGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (RecommenderClient, transports.RecommenderGrpcTransport, "grpc", "false"), + ( + RecommenderAsyncClient, + transports.RecommenderGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + RecommenderClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommenderClient) +) +@mock.patch.object( + RecommenderAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RecommenderAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_recommender_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RecommenderClient, transports.RecommenderGrpcTransport, "grpc"), + ( + RecommenderAsyncClient, + transports.RecommenderGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_recommender_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RecommenderClient, transports.RecommenderGrpcTransport, "grpc"), + ( + RecommenderAsyncClient, + transports.RecommenderGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_recommender_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_recommender_client_client_options_from_dict(): + with mock.patch( + "google.cloud.recommender_v1beta1.services.recommender.transports.RecommenderGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = RecommenderClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_list_insights( + transport: str = "grpc", request_type=recommender_service.ListInsightsRequest +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = recommender_service.ListInsightsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.ListInsightsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListInsightsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_insights_from_dict(): + test_list_insights(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_insights_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.ListInsightsRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListInsightsResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.ListInsightsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInsightsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_insights_async_from_dict(): + await test_list_insights_async(request_type=dict) + + +def test_list_insights_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.ListInsightsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + call.return_value = recommender_service.ListInsightsResponse() + + client.list_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_insights_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.ListInsightsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListInsightsResponse() + ) + + await client.list_insights(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_insights_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = recommender_service.ListInsightsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_insights(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_insights_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_insights( + recommender_service.ListInsightsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_insights_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = recommender_service.ListInsightsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListInsightsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_insights(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_insights_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_insights( + recommender_service.ListInsightsRequest(), parent="parent_value", + ) + + +def test_list_insights_pager(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(), insight.Insight(),], + next_page_token="abc", + ), + recommender_service.ListInsightsResponse( + insights=[], next_page_token="def", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(),], next_page_token="ghi", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_insights(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, insight.Insight) for i in results) + + +def test_list_insights_pages(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(), insight.Insight(),], + next_page_token="abc", + ), + recommender_service.ListInsightsResponse( + insights=[], next_page_token="def", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(),], next_page_token="ghi", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(),], + ), + RuntimeError, + ) + pages = list(client.list_insights(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_insights_async_pager(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_insights), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(), insight.Insight(),], + next_page_token="abc", + ), + recommender_service.ListInsightsResponse( + insights=[], next_page_token="def", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(),], next_page_token="ghi", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(),], + ), + RuntimeError, + ) + async_pager = await client.list_insights(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, insight.Insight) for i in responses) + + +@pytest.mark.asyncio +async def test_list_insights_async_pages(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_insights), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(), insight.Insight(),], + next_page_token="abc", + ), + recommender_service.ListInsightsResponse( + insights=[], next_page_token="def", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(),], next_page_token="ghi", + ), + recommender_service.ListInsightsResponse( + insights=[insight.Insight(), insight.Insight(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_insights(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_insight( + transport: str = "grpc", request_type=recommender_service.GetInsightRequest +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + etag="etag_value", + ) + + response = client.get_insight(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.GetInsightRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, insight.Insight) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.target_resources == ["target_resources_value"] + + assert response.insight_subtype == "insight_subtype_value" + + assert response.category == insight.Insight.Category.COST + + assert response.etag == "etag_value" + + +def test_get_insight_from_dict(): + test_get_insight(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_insight_async( + transport: str = "grpc_asyncio", request_type=recommender_service.GetInsightRequest +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + etag="etag_value", + ) + ) + + response = await client.get_insight(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.GetInsightRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, insight.Insight) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.target_resources == ["target_resources_value"] + + assert response.insight_subtype == "insight_subtype_value" + + assert response.category == insight.Insight.Category.COST + + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_get_insight_async_from_dict(): + await test_get_insight_async(request_type=dict) + + +def test_get_insight_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.GetInsightRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + call.return_value = insight.Insight() + + client.get_insight(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_insight_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.GetInsightRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(insight.Insight()) + + await client.get_insight(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_insight_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = insight.Insight() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_insight(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_insight_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_insight( + recommender_service.GetInsightRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_insight_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = insight.Insight() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(insight.Insight()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_insight(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_insight_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_insight( + recommender_service.GetInsightRequest(), name="name_value", + ) + + +def test_mark_insight_accepted( + transport: str = "grpc", request_type=recommender_service.MarkInsightAcceptedRequest +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + etag="etag_value", + ) + + response = client.mark_insight_accepted(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkInsightAcceptedRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, insight.Insight) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.target_resources == ["target_resources_value"] + + assert response.insight_subtype == "insight_subtype_value" + + assert response.category == insight.Insight.Category.COST + + assert response.etag == "etag_value" + + +def test_mark_insight_accepted_from_dict(): + test_mark_insight_accepted(request_type=dict) + + +@pytest.mark.asyncio +async def test_mark_insight_accepted_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.MarkInsightAcceptedRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + etag="etag_value", + ) + ) + + response = await client.mark_insight_accepted(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkInsightAcceptedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, insight.Insight) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.target_resources == ["target_resources_value"] + + assert response.insight_subtype == "insight_subtype_value" + + assert response.category == insight.Insight.Category.COST + + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_insight_accepted_async_from_dict(): + await test_mark_insight_accepted_async(request_type=dict) + + +def test_mark_insight_accepted_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkInsightAcceptedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + call.return_value = insight.Insight() + + client.mark_insight_accepted(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_mark_insight_accepted_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkInsightAcceptedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(insight.Insight()) + + await client.mark_insight_accepted(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_mark_insight_accepted_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = insight.Insight() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mark_insight_accepted( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +def test_mark_insight_accepted_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mark_insight_accepted( + recommender_service.MarkInsightAcceptedRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +@pytest.mark.asyncio +async def test_mark_insight_accepted_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = insight.Insight() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(insight.Insight()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mark_insight_accepted( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_insight_accepted_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.mark_insight_accepted( + recommender_service.MarkInsightAcceptedRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +def test_list_recommendations( + transport: str = "grpc", request_type=recommender_service.ListRecommendationsRequest +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommender_service.ListRecommendationsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_recommendations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.ListRecommendationsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListRecommendationsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_recommendations_from_dict(): + test_list_recommendations(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_recommendations_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.ListRecommendationsRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListRecommendationsResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_recommendations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.ListRecommendationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRecommendationsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_recommendations_async_from_dict(): + await test_list_recommendations_async(request_type=dict) + + +def test_list_recommendations_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.ListRecommendationsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + call.return_value = recommender_service.ListRecommendationsResponse() + + client.list_recommendations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_recommendations_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.ListRecommendationsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListRecommendationsResponse() + ) + + await client.list_recommendations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_recommendations_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommender_service.ListRecommendationsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_recommendations( + parent="parent_value", filter="filter_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].filter == "filter_value" + + +def test_list_recommendations_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_recommendations( + recommender_service.ListRecommendationsRequest(), + parent="parent_value", + filter="filter_value", + ) + + +@pytest.mark.asyncio +async def test_list_recommendations_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommender_service.ListRecommendationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListRecommendationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_recommendations( + parent="parent_value", filter="filter_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].filter == "filter_value" + + +@pytest.mark.asyncio +async def test_list_recommendations_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_recommendations( + recommender_service.ListRecommendationsRequest(), + parent="parent_value", + filter="filter_value", + ) + + +def test_list_recommendations_pager(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + next_page_token="abc", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[], next_page_token="def", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[recommendation.Recommendation(),], + next_page_token="ghi", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_recommendations(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, recommendation.Recommendation) for i in results) + + +def test_list_recommendations_pages(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + next_page_token="abc", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[], next_page_token="def", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[recommendation.Recommendation(),], + next_page_token="ghi", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_recommendations(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_recommendations_async_pager(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + next_page_token="abc", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[], next_page_token="def", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[recommendation.Recommendation(),], + next_page_token="ghi", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_recommendations(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, recommendation.Recommendation) for i in responses) + + +@pytest.mark.asyncio +async def test_list_recommendations_async_pages(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + next_page_token="abc", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[], next_page_token="def", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[recommendation.Recommendation(),], + next_page_token="ghi", + ), + recommender_service.ListRecommendationsResponse( + recommendations=[ + recommendation.Recommendation(), + recommendation.Recommendation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_recommendations(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_recommendation( + transport: str = "grpc", request_type=recommender_service.GetRecommendationRequest +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + + response = client.get_recommendation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.GetRecommendationRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +def test_get_recommendation_from_dict(): + test_get_recommendation(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_recommendation_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.GetRecommendationRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + ) + + response = await client.get_recommendation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.GetRecommendationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_get_recommendation_async_from_dict(): + await test_get_recommendation_async(request_type=dict) + + +def test_get_recommendation_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.GetRecommendationRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + + client.get_recommendation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_recommendation_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.GetRecommendationRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + + await client.get_recommendation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_recommendation_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_recommendation(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_recommendation_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_recommendation( + recommender_service.GetRecommendationRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_recommendation_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_recommendation(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_recommendation_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_recommendation( + recommender_service.GetRecommendationRequest(), name="name_value", + ) + + +def test_mark_recommendation_claimed( + transport: str = "grpc", + request_type=recommender_service.MarkRecommendationClaimedRequest, +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + + response = client.mark_recommendation_claimed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkRecommendationClaimedRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +def test_mark_recommendation_claimed_from_dict(): + test_mark_recommendation_claimed(request_type=dict) + + +@pytest.mark.asyncio +async def test_mark_recommendation_claimed_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.MarkRecommendationClaimedRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + ) + + response = await client.mark_recommendation_claimed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkRecommendationClaimedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_recommendation_claimed_async_from_dict(): + await test_mark_recommendation_claimed_async(request_type=dict) + + +def test_mark_recommendation_claimed_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkRecommendationClaimedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + + client.mark_recommendation_claimed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_mark_recommendation_claimed_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkRecommendationClaimedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + + await client.mark_recommendation_claimed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_mark_recommendation_claimed_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mark_recommendation_claimed( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +def test_mark_recommendation_claimed_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mark_recommendation_claimed( + recommender_service.MarkRecommendationClaimedRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +@pytest.mark.asyncio +async def test_mark_recommendation_claimed_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mark_recommendation_claimed( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_recommendation_claimed_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.mark_recommendation_claimed( + recommender_service.MarkRecommendationClaimedRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +def test_mark_recommendation_succeeded( + transport: str = "grpc", + request_type=recommender_service.MarkRecommendationSucceededRequest, +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + + response = client.mark_recommendation_succeeded(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkRecommendationSucceededRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +def test_mark_recommendation_succeeded_from_dict(): + test_mark_recommendation_succeeded(request_type=dict) + + +@pytest.mark.asyncio +async def test_mark_recommendation_succeeded_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.MarkRecommendationSucceededRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + ) + + response = await client.mark_recommendation_succeeded(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkRecommendationSucceededRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_recommendation_succeeded_async_from_dict(): + await test_mark_recommendation_succeeded_async(request_type=dict) + + +def test_mark_recommendation_succeeded_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkRecommendationSucceededRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + + client.mark_recommendation_succeeded(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_mark_recommendation_succeeded_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkRecommendationSucceededRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + + await client.mark_recommendation_succeeded(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_mark_recommendation_succeeded_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mark_recommendation_succeeded( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +def test_mark_recommendation_succeeded_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mark_recommendation_succeeded( + recommender_service.MarkRecommendationSucceededRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +@pytest.mark.asyncio +async def test_mark_recommendation_succeeded_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mark_recommendation_succeeded( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_recommendation_succeeded_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.mark_recommendation_succeeded( + recommender_service.MarkRecommendationSucceededRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +def test_mark_recommendation_failed( + transport: str = "grpc", + request_type=recommender_service.MarkRecommendationFailedRequest, +): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + + response = client.mark_recommendation_failed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkRecommendationFailedRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +def test_mark_recommendation_failed_from_dict(): + test_mark_recommendation_failed(request_type=dict) + + +@pytest.mark.asyncio +async def test_mark_recommendation_failed_async( + transport: str = "grpc_asyncio", + request_type=recommender_service.MarkRecommendationFailedRequest, +): + client = RecommenderAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + etag="etag_value", + ) + ) + + response = await client.mark_recommendation_failed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == recommender_service.MarkRecommendationFailedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.recommender_subtype == "recommender_subtype_value" + + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_recommendation_failed_async_from_dict(): + await test_mark_recommendation_failed_async(request_type=dict) + + +def test_mark_recommendation_failed_field_headers(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkRecommendationFailedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + + client.mark_recommendation_failed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_mark_recommendation_failed_field_headers_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommender_service.MarkRecommendationFailedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + + await client.mark_recommendation_failed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_mark_recommendation_failed_flattened(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mark_recommendation_failed( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +def test_mark_recommendation_failed_flattened_error(): + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mark_recommendation_failed( + recommender_service.MarkRecommendationFailedRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +@pytest.mark.asyncio +async def test_mark_recommendation_failed_flattened_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation.Recommendation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mark_recommendation_failed( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].state_metadata == {"key_value": "value_value"} + + assert args[0].etag == "etag_value" + + +@pytest.mark.asyncio +async def test_mark_recommendation_failed_flattened_error_async(): + client = RecommenderAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.mark_recommendation_failed( + recommender_service.MarkRecommendationFailedRequest(), + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommenderClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommenderClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = RecommenderClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RecommenderGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [transports.RecommenderGrpcTransport, transports.RecommenderGrpcAsyncIOTransport], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RecommenderClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.RecommenderGrpcTransport,) + + +def test_recommender_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.RecommenderTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_recommender_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.recommender_v1beta1.services.recommender.transports.RecommenderTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RecommenderTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_insights", + "get_insight", + "mark_insight_accepted", + "list_recommendations", + "get_recommendation", + "mark_recommendation_claimed", + "mark_recommendation_succeeded", + "mark_recommendation_failed", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_recommender_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.recommender_v1beta1.services.recommender.transports.RecommenderTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.RecommenderTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_recommender_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.recommender_v1beta1.services.recommender.transports.RecommenderTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.RecommenderTransport() + adc.assert_called_once() + + +def test_recommender_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + RecommenderClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_recommender_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.RecommenderGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_recommender_host_no_port(): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="recommender.googleapis.com" + ), + ) + assert client.transport._host == "recommender.googleapis.com:443" + + +def test_recommender_host_with_port(): + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="recommender.googleapis.com:8000" + ), + ) + assert client.transport._host == "recommender.googleapis.com:8000" + + +def test_recommender_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.RecommenderGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_recommender_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.RecommenderGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +@pytest.mark.parametrize( + "transport_class", + [transports.RecommenderGrpcTransport, transports.RecommenderGrpcAsyncIOTransport], +) +def test_recommender_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +@pytest.mark.parametrize( + "transport_class", + [transports.RecommenderGrpcTransport, transports.RecommenderGrpcAsyncIOTransport], +) +def test_recommender_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_insight_path(): + project = "squid" + location = "clam" + insight_type = "whelk" + insight = "octopus" + + expected = "projects/{project}/locations/{location}/insightTypes/{insight_type}/insights/{insight}".format( + project=project, location=location, insight_type=insight_type, insight=insight, + ) + actual = RecommenderClient.insight_path(project, location, insight_type, insight) + assert expected == actual + + +def test_parse_insight_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "insight_type": "cuttlefish", + "insight": "mussel", + } + path = RecommenderClient.insight_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_insight_path(path) + assert expected == actual + + +def test_insight_type_path(): + project = "winkle" + location = "nautilus" + insight_type = "scallop" + + expected = "projects/{project}/locations/{location}/insightTypes/{insight_type}".format( + project=project, location=location, insight_type=insight_type, + ) + actual = RecommenderClient.insight_type_path(project, location, insight_type) + assert expected == actual + + +def test_parse_insight_type_path(): + expected = { + "project": "abalone", + "location": "squid", + "insight_type": "clam", + } + path = RecommenderClient.insight_type_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_insight_type_path(path) + assert expected == actual + + +def test_recommendation_path(): + project = "whelk" + location = "octopus" + recommender = "oyster" + recommendation = "nudibranch" + + expected = "projects/{project}/locations/{location}/recommenders/{recommender}/recommendations/{recommendation}".format( + project=project, + location=location, + recommender=recommender, + recommendation=recommendation, + ) + actual = RecommenderClient.recommendation_path( + project, location, recommender, recommendation + ) + assert expected == actual + + +def test_parse_recommendation_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "recommender": "winkle", + "recommendation": "nautilus", + } + path = RecommenderClient.recommendation_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_recommendation_path(path) + assert expected == actual + + +def test_recommender_path(): + project = "scallop" + location = "abalone" + recommender = "squid" + + expected = "projects/{project}/locations/{location}/recommenders/{recommender}".format( + project=project, location=location, recommender=recommender, + ) + actual = RecommenderClient.recommender_path(project, location, recommender) + assert expected == actual + + +def test_parse_recommender_path(): + expected = { + "project": "clam", + "location": "whelk", + "recommender": "octopus", + } + path = RecommenderClient.recommender_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_recommender_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "oyster" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RecommenderClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = RecommenderClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "cuttlefish" + + expected = "folders/{folder}".format(folder=folder,) + actual = RecommenderClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = RecommenderClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "winkle" + + expected = "organizations/{organization}".format(organization=organization,) + actual = RecommenderClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = RecommenderClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "scallop" + + expected = "projects/{project}".format(project=project,) + actual = RecommenderClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = RecommenderClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "squid" + location = "clam" + + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = RecommenderClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = RecommenderClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RecommenderClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.RecommenderTransport, "_prep_wrapped_messages" + ) as prep: + client = RecommenderClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RecommenderTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RecommenderClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/v1/test_recommender_client_v1.py b/tests/unit/gapic/v1/test_recommender_client_v1.py deleted file mode 100644 index e4957dd..0000000 --- a/tests/unit/gapic/v1/test_recommender_client_v1.py +++ /dev/null @@ -1,474 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import recommender_v1 -from google.cloud.recommender_v1.proto import insight_pb2 -from google.cloud.recommender_v1.proto import recommendation_pb2 -from google.cloud.recommender_v1.proto import recommender_service_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestRecommenderClient(object): - def test_list_insights(self): - # Setup Expected Response - next_page_token = "" - insights_element = {} - insights = [insights_element] - expected_response = {"next_page_token": next_page_token, "insights": insights} - expected_response = recommender_service_pb2.ListInsightsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup Request - parent = client.insight_type_path("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]") - - paged_list_response = client.list_insights(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.insights[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.ListInsightsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_insights_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup request - parent = client.insight_type_path("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]") - - paged_list_response = client.list_insights(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_insight(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - insight_subtype = "insightSubtype-1491142701" - etag = "etag3123477" - expected_response = { - "name": name_2, - "description": description, - "insight_subtype": insight_subtype, - "etag": etag, - } - expected_response = insight_pb2.Insight(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup Request - name = client.insight_path( - "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]" - ) - - response = client.get_insight(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.GetInsightRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_insight_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup request - name = client.insight_path( - "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]" - ) - - with pytest.raises(CustomException): - client.get_insight(name) - - def test_mark_insight_accepted(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - insight_subtype = "insightSubtype-1491142701" - etag_2 = "etag2-1293302904" - expected_response = { - "name": name_2, - "description": description, - "insight_subtype": insight_subtype, - "etag": etag_2, - } - expected_response = insight_pb2.Insight(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup Request - name = client.insight_path( - "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]" - ) - etag = "etag3123477" - - response = client.mark_insight_accepted(name, etag) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.MarkInsightAcceptedRequest( - name=name, etag=etag - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_mark_insight_accepted_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup request - name = client.insight_path( - "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]" - ) - etag = "etag3123477" - - with pytest.raises(CustomException): - client.mark_insight_accepted(name, etag) - - def test_list_recommendations(self): - # Setup Expected Response - next_page_token = "" - recommendations_element = {} - recommendations = [recommendations_element] - expected_response = { - "next_page_token": next_page_token, - "recommendations": recommendations, - } - expected_response = recommender_service_pb2.ListRecommendationsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup Request - parent = client.recommender_path("[PROJECT]", "[LOCATION]", "[RECOMMENDER]") - - paged_list_response = client.list_recommendations(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.recommendations[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.ListRecommendationsRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_recommendations_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup request - parent = client.recommender_path("[PROJECT]", "[LOCATION]", "[RECOMMENDER]") - - paged_list_response = client.list_recommendations(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_recommendation(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - recommender_subtype = "recommenderSubtype-1488504412" - etag = "etag3123477" - expected_response = { - "name": name_2, - "description": description, - "recommender_subtype": recommender_subtype, - "etag": etag, - } - expected_response = recommendation_pb2.Recommendation(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup Request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - - response = client.get_recommendation(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.GetRecommendationRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_recommendation_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - - with pytest.raises(CustomException): - client.get_recommendation(name) - - def test_mark_recommendation_claimed(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - recommender_subtype = "recommenderSubtype-1488504412" - etag_2 = "etag2-1293302904" - expected_response = { - "name": name_2, - "description": description, - "recommender_subtype": recommender_subtype, - "etag": etag_2, - } - expected_response = recommendation_pb2.Recommendation(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup Request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - etag = "etag3123477" - - response = client.mark_recommendation_claimed(name, etag) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.MarkRecommendationClaimedRequest( - name=name, etag=etag - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_mark_recommendation_claimed_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - etag = "etag3123477" - - with pytest.raises(CustomException): - client.mark_recommendation_claimed(name, etag) - - def test_mark_recommendation_succeeded(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - recommender_subtype = "recommenderSubtype-1488504412" - etag_2 = "etag2-1293302904" - expected_response = { - "name": name_2, - "description": description, - "recommender_subtype": recommender_subtype, - "etag": etag_2, - } - expected_response = recommendation_pb2.Recommendation(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup Request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - etag = "etag3123477" - - response = client.mark_recommendation_succeeded(name, etag) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.MarkRecommendationSucceededRequest( - name=name, etag=etag - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_mark_recommendation_succeeded_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - etag = "etag3123477" - - with pytest.raises(CustomException): - client.mark_recommendation_succeeded(name, etag) - - def test_mark_recommendation_failed(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - recommender_subtype = "recommenderSubtype-1488504412" - etag_2 = "etag2-1293302904" - expected_response = { - "name": name_2, - "description": description, - "recommender_subtype": recommender_subtype, - "etag": etag_2, - } - expected_response = recommendation_pb2.Recommendation(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup Request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - etag = "etag3123477" - - response = client.mark_recommendation_failed(name, etag) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.MarkRecommendationFailedRequest( - name=name, etag=etag - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_mark_recommendation_failed_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1.RecommenderClient() - - # Setup request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - etag = "etag3123477" - - with pytest.raises(CustomException): - client.mark_recommendation_failed(name, etag) diff --git a/tests/unit/gapic/v1beta1/test_recommender_client_v1beta1.py b/tests/unit/gapic/v1beta1/test_recommender_client_v1beta1.py deleted file mode 100644 index 8c84608..0000000 --- a/tests/unit/gapic/v1beta1/test_recommender_client_v1beta1.py +++ /dev/null @@ -1,474 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import recommender_v1beta1 -from google.cloud.recommender_v1beta1.proto import insight_pb2 -from google.cloud.recommender_v1beta1.proto import recommendation_pb2 -from google.cloud.recommender_v1beta1.proto import recommender_service_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestRecommenderClient(object): - def test_list_insights(self): - # Setup Expected Response - next_page_token = "" - insights_element = {} - insights = [insights_element] - expected_response = {"next_page_token": next_page_token, "insights": insights} - expected_response = recommender_service_pb2.ListInsightsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup Request - parent = client.insight_type_path("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]") - - paged_list_response = client.list_insights(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.insights[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.ListInsightsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_insights_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup request - parent = client.insight_type_path("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]") - - paged_list_response = client.list_insights(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_insight(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - insight_subtype = "insightSubtype-1491142701" - etag = "etag3123477" - expected_response = { - "name": name_2, - "description": description, - "insight_subtype": insight_subtype, - "etag": etag, - } - expected_response = insight_pb2.Insight(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup Request - name = client.insight_path( - "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]" - ) - - response = client.get_insight(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.GetInsightRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_insight_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup request - name = client.insight_path( - "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]" - ) - - with pytest.raises(CustomException): - client.get_insight(name) - - def test_mark_insight_accepted(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - insight_subtype = "insightSubtype-1491142701" - etag_2 = "etag2-1293302904" - expected_response = { - "name": name_2, - "description": description, - "insight_subtype": insight_subtype, - "etag": etag_2, - } - expected_response = insight_pb2.Insight(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup Request - name = client.insight_path( - "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]" - ) - etag = "etag3123477" - - response = client.mark_insight_accepted(name, etag) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.MarkInsightAcceptedRequest( - name=name, etag=etag - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_mark_insight_accepted_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup request - name = client.insight_path( - "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]" - ) - etag = "etag3123477" - - with pytest.raises(CustomException): - client.mark_insight_accepted(name, etag) - - def test_list_recommendations(self): - # Setup Expected Response - next_page_token = "" - recommendations_element = {} - recommendations = [recommendations_element] - expected_response = { - "next_page_token": next_page_token, - "recommendations": recommendations, - } - expected_response = recommender_service_pb2.ListRecommendationsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup Request - parent = client.recommender_path("[PROJECT]", "[LOCATION]", "[RECOMMENDER]") - - paged_list_response = client.list_recommendations(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.recommendations[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.ListRecommendationsRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_recommendations_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup request - parent = client.recommender_path("[PROJECT]", "[LOCATION]", "[RECOMMENDER]") - - paged_list_response = client.list_recommendations(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_recommendation(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - recommender_subtype = "recommenderSubtype-1488504412" - etag = "etag3123477" - expected_response = { - "name": name_2, - "description": description, - "recommender_subtype": recommender_subtype, - "etag": etag, - } - expected_response = recommendation_pb2.Recommendation(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup Request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - - response = client.get_recommendation(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.GetRecommendationRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_recommendation_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - - with pytest.raises(CustomException): - client.get_recommendation(name) - - def test_mark_recommendation_claimed(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - recommender_subtype = "recommenderSubtype-1488504412" - etag_2 = "etag2-1293302904" - expected_response = { - "name": name_2, - "description": description, - "recommender_subtype": recommender_subtype, - "etag": etag_2, - } - expected_response = recommendation_pb2.Recommendation(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup Request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - etag = "etag3123477" - - response = client.mark_recommendation_claimed(name, etag) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.MarkRecommendationClaimedRequest( - name=name, etag=etag - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_mark_recommendation_claimed_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - etag = "etag3123477" - - with pytest.raises(CustomException): - client.mark_recommendation_claimed(name, etag) - - def test_mark_recommendation_succeeded(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - recommender_subtype = "recommenderSubtype-1488504412" - etag_2 = "etag2-1293302904" - expected_response = { - "name": name_2, - "description": description, - "recommender_subtype": recommender_subtype, - "etag": etag_2, - } - expected_response = recommendation_pb2.Recommendation(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup Request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - etag = "etag3123477" - - response = client.mark_recommendation_succeeded(name, etag) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.MarkRecommendationSucceededRequest( - name=name, etag=etag - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_mark_recommendation_succeeded_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - etag = "etag3123477" - - with pytest.raises(CustomException): - client.mark_recommendation_succeeded(name, etag) - - def test_mark_recommendation_failed(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - recommender_subtype = "recommenderSubtype-1488504412" - etag_2 = "etag2-1293302904" - expected_response = { - "name": name_2, - "description": description, - "recommender_subtype": recommender_subtype, - "etag": etag_2, - } - expected_response = recommendation_pb2.Recommendation(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup Request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - etag = "etag3123477" - - response = client.mark_recommendation_failed(name, etag) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = recommender_service_pb2.MarkRecommendationFailedRequest( - name=name, etag=etag - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_mark_recommendation_failed_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = recommender_v1beta1.RecommenderClient() - - # Setup request - name = client.recommendation_path( - "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]" - ) - etag = "etag3123477" - - with pytest.raises(CustomException): - client.mark_recommendation_failed(name, etag)