From 8d64728d8ffff41a814672c38f1abafdb92660a6 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 22 Mar 2023 19:58:21 +0000 Subject: [PATCH 1/2] docs: Fix formatting of request arg in docstring chore: Update gapic-generator-python to v1.9.1 PiperOrigin-RevId: 518604533 Source-Link: https://github.com/googleapis/googleapis/commit/8a085aeddfa010af5bcef090827aac5255383d7e Source-Link: https://github.com/googleapis/googleapis-gen/commit/b2ab4b0a0ae2907e812c209198a74e0898afcb04 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjJhYjRiMGEwYWUyOTA3ZTgxMmMyMDkxOThhNzRlMDg5OGFmY2IwNCJ9 --- owl-bot-staging/v1/.coveragerc | 13 + owl-bot-staging/v1/.flake8 | 33 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + owl-bot-staging/v1/docs/conf.py | 376 ++++ owl-bot-staging/v1/docs/index.rst | 7 + .../servicecontrol_v1/quota_controller.rst | 6 + .../servicecontrol_v1/service_controller.rst | 6 + .../v1/docs/servicecontrol_v1/services.rst | 7 + .../v1/docs/servicecontrol_v1/types.rst | 6 + .../google/cloud/servicecontrol/__init__.py | 65 + .../cloud/servicecontrol/gapic_version.py | 16 + .../v1/google/cloud/servicecontrol/py.typed | 2 + .../cloud/servicecontrol_v1/__init__.py | 66 + .../servicecontrol_v1/gapic_metadata.json | 92 + .../cloud/servicecontrol_v1/gapic_version.py | 16 + .../google/cloud/servicecontrol_v1/py.typed | 2 + .../servicecontrol_v1/services/__init__.py | 15 + .../services/quota_controller/__init__.py | 22 + .../services/quota_controller/async_client.py | 291 +++ .../services/quota_controller/client.py | 487 +++++ .../quota_controller/transports/__init__.py | 38 + .../quota_controller/transports/base.py | 149 ++ .../quota_controller/transports/grpc.py | 278 +++ .../transports/grpc_asyncio.py | 277 +++ .../quota_controller/transports/rest.py | 295 +++ .../services/service_controller/__init__.py | 22 + .../service_controller/async_client.py | 400 ++++ .../services/service_controller/client.py | 591 ++++++ .../service_controller/transports/__init__.py | 38 + .../service_controller/transports/base.py | 169 ++ .../service_controller/transports/grpc.py | 328 ++++ .../transports/grpc_asyncio.py | 327 ++++ .../service_controller/transports/rest.py | 408 ++++ .../cloud/servicecontrol_v1/types/__init__.py | 68 + .../servicecontrol_v1/types/check_error.py | 164 ++ .../servicecontrol_v1/types/distribution.py | 241 +++ .../servicecontrol_v1/types/http_request.py | 156 ++ .../servicecontrol_v1/types/log_entry.py | 238 +++ .../servicecontrol_v1/types/metric_value.py | 153 ++ .../servicecontrol_v1/types/operation.py | 186 ++ .../types/quota_controller.py | 328 ++++ .../types/service_controller.py | 322 +++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 184 ++ ...d_quota_controller_allocate_quota_async.py | 51 + ...ed_quota_controller_allocate_quota_sync.py | 51 + ...enerated_service_controller_check_async.py | 51 + ...generated_service_controller_check_sync.py | 51 + ...nerated_service_controller_report_async.py | 51 + ...enerated_service_controller_report_sync.py | 51 + ...metadata_google.api.servicecontrol.v1.json | 474 +++++ .../fixup_servicecontrol_v1_keywords.py | 178 ++ owl-bot-staging/v1/setup.py | 90 + .../v1/testing/constraints-3.10.txt | 6 + .../v1/testing/constraints-3.11.txt | 6 + .../v1/testing/constraints-3.12.txt | 6 + .../v1/testing/constraints-3.7.txt | 9 + .../v1/testing/constraints-3.8.txt | 6 + .../v1/testing/constraints-3.9.txt | 6 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/servicecontrol_v1/__init__.py | 16 + .../test_quota_controller.py | 1464 ++++++++++++++ .../test_service_controller.py | 1740 +++++++++++++++++ owl-bot-staging/v2/.coveragerc | 13 + owl-bot-staging/v2/.flake8 | 33 + owl-bot-staging/v2/MANIFEST.in | 2 + owl-bot-staging/v2/README.rst | 49 + owl-bot-staging/v2/docs/conf.py | 376 ++++ owl-bot-staging/v2/docs/index.rst | 7 + .../servicecontrol_v2/service_controller.rst | 6 + .../v2/docs/servicecontrol_v2/services.rst | 6 + .../v2/docs/servicecontrol_v2/types.rst | 6 + .../google/cloud/servicecontrol/__init__.py | 37 + .../cloud/servicecontrol/gapic_version.py | 16 + .../v2/google/cloud/servicecontrol/py.typed | 2 + .../cloud/servicecontrol_v2/__init__.py | 38 + .../servicecontrol_v2/gapic_metadata.json | 58 + .../cloud/servicecontrol_v2/gapic_version.py | 16 + .../google/cloud/servicecontrol_v2/py.typed | 2 + .../servicecontrol_v2/services/__init__.py | 15 + .../services/service_controller/__init__.py | 22 + .../service_controller/async_client.py | 413 ++++ .../services/service_controller/client.py | 604 ++++++ .../service_controller/transports/__init__.py | 38 + .../service_controller/transports/base.py | 169 ++ .../service_controller/transports/grpc.py | 339 ++++ .../transports/grpc_asyncio.py | 338 ++++ .../service_controller/transports/rest.py | 415 ++++ .../cloud/servicecontrol_v2/types/__init__.py | 30 + .../types/service_controller.py | 216 ++ owl-bot-staging/v2/mypy.ini | 3 + owl-bot-staging/v2/noxfile.py | 184 ++ ...enerated_service_controller_check_async.py | 51 + ...generated_service_controller_check_sync.py | 51 + ...nerated_service_controller_report_async.py | 51 + ...enerated_service_controller_report_sync.py | 51 + ...metadata_google.api.servicecontrol.v2.json | 321 +++ .../fixup_servicecontrol_v2_keywords.py | 177 ++ owl-bot-staging/v2/setup.py | 90 + .../v2/testing/constraints-3.10.txt | 6 + .../v2/testing/constraints-3.11.txt | 6 + .../v2/testing/constraints-3.12.txt | 6 + .../v2/testing/constraints-3.7.txt | 9 + .../v2/testing/constraints-3.8.txt | 6 + .../v2/testing/constraints-3.9.txt | 6 + owl-bot-staging/v2/tests/__init__.py | 16 + owl-bot-staging/v2/tests/unit/__init__.py | 16 + .../v2/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/servicecontrol_v2/__init__.py | 16 + .../test_service_controller.py | 1704 ++++++++++++++++ 113 files changed, 17349 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/.flake8 create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/docs/servicecontrol_v1/quota_controller.rst create mode 100644 owl-bot-staging/v1/docs/servicecontrol_v1/service_controller.rst create mode 100644 owl-bot-staging/v1/docs/servicecontrol_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/servicecontrol_v1/types.rst create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/client.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/rest.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/client.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/rest.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/check_error.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/distribution.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/http_request.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/log_entry.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/metric_value.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/operation.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/quota_controller.py create mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/service_controller.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json create mode 100644 owl-bot-staging/v1/scripts/fixup_servicecontrol_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_quota_controller.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_service_controller.py create mode 100644 owl-bot-staging/v2/.coveragerc create mode 100644 owl-bot-staging/v2/.flake8 create mode 100644 owl-bot-staging/v2/MANIFEST.in create mode 100644 owl-bot-staging/v2/README.rst create mode 100644 owl-bot-staging/v2/docs/conf.py create mode 100644 owl-bot-staging/v2/docs/index.rst create mode 100644 owl-bot-staging/v2/docs/servicecontrol_v2/service_controller.rst create mode 100644 owl-bot-staging/v2/docs/servicecontrol_v2/services.rst create mode 100644 owl-bot-staging/v2/docs/servicecontrol_v2/types.rst create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol/gapic_version.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_metadata.json create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_version.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/py.typed create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/async_client.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/client.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/base.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/rest.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/__init__.py create mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/service_controller.py create mode 100644 owl-bot-staging/v2/mypy.ini create mode 100644 owl-bot-staging/v2/noxfile.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_async.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_sync.py create mode 100644 owl-bot-staging/v2/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json create mode 100644 owl-bot-staging/v2/scripts/fixup_servicecontrol_v2_keywords.py create mode 100644 owl-bot-staging/v2/setup.py create mode 100644 owl-bot-staging/v2/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v2/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v2/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v2/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v2/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v2/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v2/tests/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/__init__.py create mode 100644 owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/test_service_controller.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 0000000..db73969 --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/servicecontrol/__init__.py + google/cloud/servicecontrol/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/v1/.flake8 b/owl-bot-staging/v1/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- 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. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 0000000..145db90 --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/servicecontrol *.py +recursive-include google/cloud/servicecontrol_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 0000000..68e4838 --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Servicecontrol API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Servicecontrol API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 0000000..4c7d6b4 --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +# +# google-cloud-service-control documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-service-control" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-service-control-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-service-control.tex", + u"google-cloud-service-control Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-service-control", + u"Google Cloud Servicecontrol Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-service-control", + u"google-cloud-service-control Documentation", + author, + "google-cloud-service-control", + "GAPIC library for Google Cloud Servicecontrol API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 0000000..cc2d937 --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + servicecontrol_v1/services + servicecontrol_v1/types diff --git a/owl-bot-staging/v1/docs/servicecontrol_v1/quota_controller.rst b/owl-bot-staging/v1/docs/servicecontrol_v1/quota_controller.rst new file mode 100644 index 0000000..7f694a1 --- /dev/null +++ b/owl-bot-staging/v1/docs/servicecontrol_v1/quota_controller.rst @@ -0,0 +1,6 @@ +QuotaController +--------------------------------- + +.. automodule:: google.cloud.servicecontrol_v1.services.quota_controller + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/servicecontrol_v1/service_controller.rst b/owl-bot-staging/v1/docs/servicecontrol_v1/service_controller.rst new file mode 100644 index 0000000..f3d8986 --- /dev/null +++ b/owl-bot-staging/v1/docs/servicecontrol_v1/service_controller.rst @@ -0,0 +1,6 @@ +ServiceController +----------------------------------- + +.. automodule:: google.cloud.servicecontrol_v1.services.service_controller + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/servicecontrol_v1/services.rst b/owl-bot-staging/v1/docs/servicecontrol_v1/services.rst new file mode 100644 index 0000000..779f197 --- /dev/null +++ b/owl-bot-staging/v1/docs/servicecontrol_v1/services.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Servicecontrol v1 API +=============================================== +.. toctree:: + :maxdepth: 2 + + quota_controller + service_controller diff --git a/owl-bot-staging/v1/docs/servicecontrol_v1/types.rst b/owl-bot-staging/v1/docs/servicecontrol_v1/types.rst new file mode 100644 index 0000000..eda22be --- /dev/null +++ b/owl-bot-staging/v1/docs/servicecontrol_v1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Servicecontrol v1 API +============================================ + +.. automodule:: google.cloud.servicecontrol_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol/__init__.py new file mode 100644 index 0000000..8256c92 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol/__init__.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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.servicecontrol import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.servicecontrol_v1.services.quota_controller.client import QuotaControllerClient +from google.cloud.servicecontrol_v1.services.quota_controller.async_client import QuotaControllerAsyncClient +from google.cloud.servicecontrol_v1.services.service_controller.client import ServiceControllerClient +from google.cloud.servicecontrol_v1.services.service_controller.async_client import ServiceControllerAsyncClient + +from google.cloud.servicecontrol_v1.types.check_error import CheckError +from google.cloud.servicecontrol_v1.types.distribution import Distribution +from google.cloud.servicecontrol_v1.types.http_request import HttpRequest +from google.cloud.servicecontrol_v1.types.log_entry import LogEntry +from google.cloud.servicecontrol_v1.types.log_entry import LogEntryOperation +from google.cloud.servicecontrol_v1.types.log_entry import LogEntrySourceLocation +from google.cloud.servicecontrol_v1.types.metric_value import MetricValue +from google.cloud.servicecontrol_v1.types.metric_value import MetricValueSet +from google.cloud.servicecontrol_v1.types.operation import Operation +from google.cloud.servicecontrol_v1.types.quota_controller import AllocateQuotaRequest +from google.cloud.servicecontrol_v1.types.quota_controller import AllocateQuotaResponse +from google.cloud.servicecontrol_v1.types.quota_controller import QuotaError +from google.cloud.servicecontrol_v1.types.quota_controller import QuotaOperation +from google.cloud.servicecontrol_v1.types.service_controller import CheckRequest +from google.cloud.servicecontrol_v1.types.service_controller import CheckResponse +from google.cloud.servicecontrol_v1.types.service_controller import ReportRequest +from google.cloud.servicecontrol_v1.types.service_controller import ReportResponse + +__all__ = ('QuotaControllerClient', + 'QuotaControllerAsyncClient', + 'ServiceControllerClient', + 'ServiceControllerAsyncClient', + 'CheckError', + 'Distribution', + 'HttpRequest', + 'LogEntry', + 'LogEntryOperation', + 'LogEntrySourceLocation', + 'MetricValue', + 'MetricValueSet', + 'Operation', + 'AllocateQuotaRequest', + 'AllocateQuotaResponse', + 'QuotaError', + 'QuotaOperation', + 'CheckRequest', + 'CheckResponse', + 'ReportRequest', + 'ReportResponse', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol/gapic_version.py b/owl-bot-staging/v1/google/cloud/servicecontrol/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol/py.typed b/owl-bot-staging/v1/google/cloud/servicecontrol/py.typed new file mode 100644 index 0000000..3971a5d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-service-control package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/__init__.py new file mode 100644 index 0000000..918ad3a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/__init__.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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.servicecontrol_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.quota_controller import QuotaControllerClient +from .services.quota_controller import QuotaControllerAsyncClient +from .services.service_controller import ServiceControllerClient +from .services.service_controller import ServiceControllerAsyncClient + +from .types.check_error import CheckError +from .types.distribution import Distribution +from .types.http_request import HttpRequest +from .types.log_entry import LogEntry +from .types.log_entry import LogEntryOperation +from .types.log_entry import LogEntrySourceLocation +from .types.metric_value import MetricValue +from .types.metric_value import MetricValueSet +from .types.operation import Operation +from .types.quota_controller import AllocateQuotaRequest +from .types.quota_controller import AllocateQuotaResponse +from .types.quota_controller import QuotaError +from .types.quota_controller import QuotaOperation +from .types.service_controller import CheckRequest +from .types.service_controller import CheckResponse +from .types.service_controller import ReportRequest +from .types.service_controller import ReportResponse + +__all__ = ( + 'QuotaControllerAsyncClient', + 'ServiceControllerAsyncClient', +'AllocateQuotaRequest', +'AllocateQuotaResponse', +'CheckError', +'CheckRequest', +'CheckResponse', +'Distribution', +'HttpRequest', +'LogEntry', +'LogEntryOperation', +'LogEntrySourceLocation', +'MetricValue', +'MetricValueSet', +'Operation', +'QuotaControllerClient', +'QuotaError', +'QuotaOperation', +'ReportRequest', +'ReportResponse', +'ServiceControllerClient', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_metadata.json new file mode 100644 index 0000000..d275a5b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_metadata.json @@ -0,0 +1,92 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.servicecontrol_v1", + "protoPackage": "google.api.servicecontrol.v1", + "schema": "1.0", + "services": { + "QuotaController": { + "clients": { + "grpc": { + "libraryClient": "QuotaControllerClient", + "rpcs": { + "AllocateQuota": { + "methods": [ + "allocate_quota" + ] + } + } + }, + "grpc-async": { + "libraryClient": "QuotaControllerAsyncClient", + "rpcs": { + "AllocateQuota": { + "methods": [ + "allocate_quota" + ] + } + } + }, + "rest": { + "libraryClient": "QuotaControllerClient", + "rpcs": { + "AllocateQuota": { + "methods": [ + "allocate_quota" + ] + } + } + } + } + }, + "ServiceController": { + "clients": { + "grpc": { + "libraryClient": "ServiceControllerClient", + "rpcs": { + "Check": { + "methods": [ + "check" + ] + }, + "Report": { + "methods": [ + "report" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ServiceControllerAsyncClient", + "rpcs": { + "Check": { + "methods": [ + "check" + ] + }, + "Report": { + "methods": [ + "report" + ] + } + } + }, + "rest": { + "libraryClient": "ServiceControllerClient", + "rpcs": { + "Check": { + "methods": [ + "check" + ] + }, + "Report": { + "methods": [ + "report" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/py.typed b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/py.typed new file mode 100644 index 0000000..3971a5d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-service-control package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/__init__.py new file mode 100644 index 0000000..609d0e7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 .client import QuotaControllerClient +from .async_client import QuotaControllerAsyncClient + +__all__ = ( + 'QuotaControllerClient', + 'QuotaControllerAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/async_client.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/async_client.py new file mode 100644 index 0000000..e89c7ec --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/async_client.py @@ -0,0 +1,291 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.servicecontrol_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.servicecontrol_v1.types import metric_value +from google.cloud.servicecontrol_v1.types import quota_controller +from .transports.base import QuotaControllerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import QuotaControllerGrpcAsyncIOTransport +from .client import QuotaControllerClient + + +class QuotaControllerAsyncClient: + """`Google Quota Control API `__ + + Allows clients to allocate and release quota against a `managed + service `__. + """ + + _client: QuotaControllerClient + + DEFAULT_ENDPOINT = QuotaControllerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = QuotaControllerClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(QuotaControllerClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(QuotaControllerClient.parse_common_billing_account_path) + common_folder_path = staticmethod(QuotaControllerClient.common_folder_path) + parse_common_folder_path = staticmethod(QuotaControllerClient.parse_common_folder_path) + common_organization_path = staticmethod(QuotaControllerClient.common_organization_path) + parse_common_organization_path = staticmethod(QuotaControllerClient.parse_common_organization_path) + common_project_path = staticmethod(QuotaControllerClient.common_project_path) + parse_common_project_path = staticmethod(QuotaControllerClient.parse_common_project_path) + common_location_path = staticmethod(QuotaControllerClient.common_location_path) + parse_common_location_path = staticmethod(QuotaControllerClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + QuotaControllerAsyncClient: The constructed client. + """ + return QuotaControllerClient.from_service_account_info.__func__(QuotaControllerAsyncClient, info, *args, **kwargs) # type: ignore + + @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: + QuotaControllerAsyncClient: The constructed client. + """ + return QuotaControllerClient.from_service_account_file.__func__(QuotaControllerAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return QuotaControllerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> QuotaControllerTransport: + """Returns the transport used by the client instance. + + Returns: + QuotaControllerTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(QuotaControllerClient).get_transport_class, type(QuotaControllerClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, QuotaControllerTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the quota controller 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, ~.QuotaControllerTransport]): 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 = QuotaControllerClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def allocate_quota(self, + request: Optional[Union[quota_controller.AllocateQuotaRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> quota_controller.AllocateQuotaResponse: + r"""Attempts to allocate quota for the specified consumer. It should + be called before the operation is executed. + + This method requires the ``servicemanagement.services.quota`` + permission on the specified service. For more information, see + `Cloud IAM `__. + + **NOTE:** The client **must** fail-open on server errors + ``INTERNAL``, ``UNKNOWN``, ``DEADLINE_EXCEEDED``, and + ``UNAVAILABLE``. To ensure system reliability, the server may + inject these errors to prohibit any hard dependency on the quota + functionality. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import servicecontrol_v1 + + async def sample_allocate_quota(): + # Create a client + client = servicecontrol_v1.QuotaControllerAsyncClient() + + # Initialize request argument(s) + request = servicecontrol_v1.AllocateQuotaRequest( + ) + + # Make the request + response = await client.allocate_quota(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.servicecontrol_v1.types.AllocateQuotaRequest, dict]]): + The request object. Request message for the AllocateQuota + method. + 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: + google.cloud.servicecontrol_v1.types.AllocateQuotaResponse: + Response message for the + AllocateQuota method. + + """ + # Create or coerce a protobuf request object. + request = quota_controller.AllocateQuotaRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.allocate_quota, + default_timeout=None, + 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(( + ("service_name", request.service_name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "QuotaControllerAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/client.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/client.py new file mode 100644 index 0000000..33457f4 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/client.py @@ -0,0 +1,487 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.servicecontrol_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.servicecontrol_v1.types import metric_value +from google.cloud.servicecontrol_v1.types import quota_controller +from .transports.base import QuotaControllerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import QuotaControllerGrpcTransport +from .transports.grpc_asyncio import QuotaControllerGrpcAsyncIOTransport +from .transports.rest import QuotaControllerRestTransport + + +class QuotaControllerClientMeta(type): + """Metaclass for the QuotaController 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[QuotaControllerTransport]] + _transport_registry["grpc"] = QuotaControllerGrpcTransport + _transport_registry["grpc_asyncio"] = QuotaControllerGrpcAsyncIOTransport + _transport_registry["rest"] = QuotaControllerRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[QuotaControllerTransport]: + """Returns 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 QuotaControllerClient(metaclass=QuotaControllerClientMeta): + """`Google Quota Control API `__ + + Allows clients to allocate and release quota against a `managed + service `__. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + 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 = "servicecontrol.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + QuotaControllerClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @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: + QuotaControllerClient: 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) -> QuotaControllerTransport: + """Returns the transport used by the client instance. + + Returns: + QuotaControllerTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @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: + """Returns 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: + """Returns 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: + """Returns 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: + """Returns 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 {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, QuotaControllerTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the quota controller 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, QuotaControllerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, QuotaControllerTransport): + # transport is a QuotaControllerTransport instance. + if credentials or client_options.credentials_file or api_key_value: + 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: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + 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, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def allocate_quota(self, + request: Optional[Union[quota_controller.AllocateQuotaRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> quota_controller.AllocateQuotaResponse: + r"""Attempts to allocate quota for the specified consumer. It should + be called before the operation is executed. + + This method requires the ``servicemanagement.services.quota`` + permission on the specified service. For more information, see + `Cloud IAM `__. + + **NOTE:** The client **must** fail-open on server errors + ``INTERNAL``, ``UNKNOWN``, ``DEADLINE_EXCEEDED``, and + ``UNAVAILABLE``. To ensure system reliability, the server may + inject these errors to prohibit any hard dependency on the quota + functionality. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import servicecontrol_v1 + + def sample_allocate_quota(): + # Create a client + client = servicecontrol_v1.QuotaControllerClient() + + # Initialize request argument(s) + request = servicecontrol_v1.AllocateQuotaRequest( + ) + + # Make the request + response = client.allocate_quota(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.servicecontrol_v1.types.AllocateQuotaRequest, dict]): + The request object. Request message for the AllocateQuota + method. + 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: + google.cloud.servicecontrol_v1.types.AllocateQuotaResponse: + Response message for the + AllocateQuota method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a quota_controller.AllocateQuotaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, quota_controller.AllocateQuotaRequest): + request = quota_controller.AllocateQuotaRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.allocate_quota] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service_name", request.service_name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "QuotaControllerClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "QuotaControllerClient", +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/__init__.py new file mode 100644 index 0000000..f4ecf30 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 QuotaControllerTransport +from .grpc import QuotaControllerGrpcTransport +from .grpc_asyncio import QuotaControllerGrpcAsyncIOTransport +from .rest import QuotaControllerRestTransport +from .rest import QuotaControllerRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[QuotaControllerTransport]] +_transport_registry['grpc'] = QuotaControllerGrpcTransport +_transport_registry['grpc_asyncio'] = QuotaControllerGrpcAsyncIOTransport +_transport_registry['rest'] = QuotaControllerRestTransport + +__all__ = ( + 'QuotaControllerTransport', + 'QuotaControllerGrpcTransport', + 'QuotaControllerGrpcAsyncIOTransport', + 'QuotaControllerRestTransport', + 'QuotaControllerRestInterceptor', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/base.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/base.py new file mode 100644 index 0000000..b7f9b7a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/base.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.servicecontrol_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicecontrol_v1.types import quota_controller + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class QuotaControllerTransport(abc.ABC): + """Abstract transport class for QuotaController.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', + ) + + DEFAULT_HOST: str = 'servicecontrol.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **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. + scopes (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. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.allocate_quota: gapic_v1.method.wrap_method( + self.allocate_quota, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def allocate_quota(self) -> Callable[ + [quota_controller.AllocateQuotaRequest], + Union[ + quota_controller.AllocateQuotaResponse, + Awaitable[quota_controller.AllocateQuotaResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'QuotaControllerTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc.py new file mode 100644 index 0000000..4ceea00 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc.py @@ -0,0 +1,278 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.servicecontrol_v1.types import quota_controller +from .base import QuotaControllerTransport, DEFAULT_CLIENT_INFO + + +class QuotaControllerGrpcTransport(QuotaControllerTransport): + """gRPC backend transport for QuotaController. + + `Google Quota Control API `__ + + Allows clients to allocate and release quota against a `managed + service `__. + + 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 = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> 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 application 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 the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + 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._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + 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. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def allocate_quota(self) -> Callable[ + [quota_controller.AllocateQuotaRequest], + quota_controller.AllocateQuotaResponse]: + r"""Return a callable for the allocate quota method over gRPC. + + Attempts to allocate quota for the specified consumer. It should + be called before the operation is executed. + + This method requires the ``servicemanagement.services.quota`` + permission on the specified service. For more information, see + `Cloud IAM `__. + + **NOTE:** The client **must** fail-open on server errors + ``INTERNAL``, ``UNKNOWN``, ``DEADLINE_EXCEEDED``, and + ``UNAVAILABLE``. To ensure system reliability, the server may + inject these errors to prohibit any hard dependency on the quota + functionality. + + Returns: + Callable[[~.AllocateQuotaRequest], + ~.AllocateQuotaResponse]: + 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 'allocate_quota' not in self._stubs: + self._stubs['allocate_quota'] = self.grpc_channel.unary_unary( + '/google.api.servicecontrol.v1.QuotaController/AllocateQuota', + request_serializer=quota_controller.AllocateQuotaRequest.serialize, + response_deserializer=quota_controller.AllocateQuotaResponse.deserialize, + ) + return self._stubs['allocate_quota'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'QuotaControllerGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc_asyncio.py new file mode 100644 index 0000000..8a3833e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc_asyncio.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_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.servicecontrol_v1.types import quota_controller +from .base import QuotaControllerTransport, DEFAULT_CLIENT_INFO +from .grpc import QuotaControllerGrpcTransport + + +class QuotaControllerGrpcAsyncIOTransport(QuotaControllerTransport): + """gRPC AsyncIO backend transport for QuotaController. + + `Google Quota Control API `__ + + Allows clients to allocate and release quota against a `managed + service `__. + + 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 = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (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. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> 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 application 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 the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + 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._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @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 allocate_quota(self) -> Callable[ + [quota_controller.AllocateQuotaRequest], + Awaitable[quota_controller.AllocateQuotaResponse]]: + r"""Return a callable for the allocate quota method over gRPC. + + Attempts to allocate quota for the specified consumer. It should + be called before the operation is executed. + + This method requires the ``servicemanagement.services.quota`` + permission on the specified service. For more information, see + `Cloud IAM `__. + + **NOTE:** The client **must** fail-open on server errors + ``INTERNAL``, ``UNKNOWN``, ``DEADLINE_EXCEEDED``, and + ``UNAVAILABLE``. To ensure system reliability, the server may + inject these errors to prohibit any hard dependency on the quota + functionality. + + Returns: + Callable[[~.AllocateQuotaRequest], + Awaitable[~.AllocateQuotaResponse]]: + 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 'allocate_quota' not in self._stubs: + self._stubs['allocate_quota'] = self.grpc_channel.unary_unary( + '/google.api.servicecontrol.v1.QuotaController/AllocateQuota', + request_serializer=quota_controller.AllocateQuotaRequest.serialize, + response_deserializer=quota_controller.AllocateQuotaResponse.deserialize, + ) + return self._stubs['allocate_quota'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'QuotaControllerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/rest.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/rest.py new file mode 100644 index 0000000..e78a09a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/rest.py @@ -0,0 +1,295 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.servicecontrol_v1.types import quota_controller + +from .base import QuotaControllerTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class QuotaControllerRestInterceptor: + """Interceptor for QuotaController. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the QuotaControllerRestTransport. + + .. code-block:: python + class MyCustomQuotaControllerInterceptor(QuotaControllerRestInterceptor): + def pre_allocate_quota(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_allocate_quota(self, response): + logging.log(f"Received response: {response}") + return response + + transport = QuotaControllerRestTransport(interceptor=MyCustomQuotaControllerInterceptor()) + client = QuotaControllerClient(transport=transport) + + + """ + def pre_allocate_quota(self, request: quota_controller.AllocateQuotaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[quota_controller.AllocateQuotaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for allocate_quota + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuotaController server. + """ + return request, metadata + + def post_allocate_quota(self, response: quota_controller.AllocateQuotaResponse) -> quota_controller.AllocateQuotaResponse: + """Post-rpc interceptor for allocate_quota + + Override in a subclass to manipulate the response + after it is returned by the QuotaController server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class QuotaControllerRestStub: + _session: AuthorizedSession + _host: str + _interceptor: QuotaControllerRestInterceptor + + +class QuotaControllerRestTransport(QuotaControllerTransport): + """REST backend transport for QuotaController. + + `Google Quota Control API `__ + + Allows clients to allocate and release quota against a `managed + service `__. + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[QuotaControllerRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or QuotaControllerRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AllocateQuota(QuotaControllerRestStub): + def __hash__(self): + return hash("AllocateQuota") + + def __call__(self, + request: quota_controller.AllocateQuotaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> quota_controller.AllocateQuotaResponse: + r"""Call the allocate quota method over HTTP. + + Args: + request (~.quota_controller.AllocateQuotaRequest): + The request object. Request message for the AllocateQuota + method. + 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: + ~.quota_controller.AllocateQuotaResponse: + Response message for the + AllocateQuota method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/services/{service_name}:allocateQuota', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_allocate_quota(request, metadata) + pb_request = quota_controller.AllocateQuotaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quota_controller.AllocateQuotaResponse() + pb_resp = quota_controller.AllocateQuotaResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_allocate_quota(resp) + return resp + + @property + def allocate_quota(self) -> Callable[ + [quota_controller.AllocateQuotaRequest], + quota_controller.AllocateQuotaResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AllocateQuota(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'QuotaControllerRestTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/__init__.py new file mode 100644 index 0000000..187fc9e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 .client import ServiceControllerClient +from .async_client import ServiceControllerAsyncClient + +__all__ = ( + 'ServiceControllerClient', + 'ServiceControllerAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/async_client.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/async_client.py new file mode 100644 index 0000000..6f1798e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/async_client.py @@ -0,0 +1,400 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.servicecontrol_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.servicecontrol_v1.types import check_error +from google.cloud.servicecontrol_v1.types import service_controller +from .transports.base import ServiceControllerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ServiceControllerGrpcAsyncIOTransport +from .client import ServiceControllerClient + + +class ServiceControllerAsyncClient: + """`Google Service Control API `__ + + Lets clients check and report operations against a `managed + service `__. + """ + + _client: ServiceControllerClient + + DEFAULT_ENDPOINT = ServiceControllerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ServiceControllerClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(ServiceControllerClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ServiceControllerClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ServiceControllerClient.common_folder_path) + parse_common_folder_path = staticmethod(ServiceControllerClient.parse_common_folder_path) + common_organization_path = staticmethod(ServiceControllerClient.common_organization_path) + parse_common_organization_path = staticmethod(ServiceControllerClient.parse_common_organization_path) + common_project_path = staticmethod(ServiceControllerClient.common_project_path) + parse_common_project_path = staticmethod(ServiceControllerClient.parse_common_project_path) + common_location_path = staticmethod(ServiceControllerClient.common_location_path) + parse_common_location_path = staticmethod(ServiceControllerClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServiceControllerAsyncClient: The constructed client. + """ + return ServiceControllerClient.from_service_account_info.__func__(ServiceControllerAsyncClient, info, *args, **kwargs) # type: ignore + + @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: + ServiceControllerAsyncClient: The constructed client. + """ + return ServiceControllerClient.from_service_account_file.__func__(ServiceControllerAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ServiceControllerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ServiceControllerTransport: + """Returns the transport used by the client instance. + + Returns: + ServiceControllerTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ServiceControllerClient).get_transport_class, type(ServiceControllerClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ServiceControllerTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the service controller 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, ~.ServiceControllerTransport]): 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 = ServiceControllerClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def check(self, + request: Optional[Union[service_controller.CheckRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service_controller.CheckResponse: + r"""Checks whether an operation on a service should be allowed to + proceed based on the configuration of the service and related + policies. It must be called before the operation is executed. + + If feasible, the client should cache the check results and reuse + them for 60 seconds. In case of any server errors, the client + should rely on the cached results for much longer time to avoid + outage. WARNING: There is general 60s delay for the + configuration and policy propagation, therefore callers MUST NOT + depend on the ``Check`` method having the latest policy + information. + + NOTE: the + [CheckRequest][google.api.servicecontrol.v1.CheckRequest] has + the size limit (wire-format byte size) of 1MB. + + This method requires the ``servicemanagement.services.check`` + permission on the specified service. For more information, see + `Cloud IAM `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import servicecontrol_v1 + + async def sample_check(): + # Create a client + client = servicecontrol_v1.ServiceControllerAsyncClient() + + # Initialize request argument(s) + request = servicecontrol_v1.CheckRequest( + ) + + # Make the request + response = await client.check(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.servicecontrol_v1.types.CheckRequest, dict]]): + The request object. Request message for the Check method. + 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: + google.cloud.servicecontrol_v1.types.CheckResponse: + Response message for the Check + method. + + """ + # Create or coerce a protobuf request object. + request = service_controller.CheckRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.check, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=5.0, + ), + default_timeout=5.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(( + ("service_name", request.service_name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def report(self, + request: Optional[Union[service_controller.ReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service_controller.ReportResponse: + r"""Reports operation results to Google Service Control, such as + logs and metrics. It should be called after an operation is + completed. + + If feasible, the client should aggregate reporting data for up + to 5 seconds to reduce API traffic. Limiting aggregation to 5 + seconds is to reduce data loss during client crashes. Clients + should carefully choose the aggregation time window to avoid + data loss risk more than 0.01% for business and compliance + reasons. + + NOTE: the + [ReportRequest][google.api.servicecontrol.v1.ReportRequest] has + the size limit (wire-format byte size) of 1MB. + + This method requires the ``servicemanagement.services.report`` + permission on the specified service. For more information, see + `Google Cloud IAM `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import servicecontrol_v1 + + async def sample_report(): + # Create a client + client = servicecontrol_v1.ServiceControllerAsyncClient() + + # Initialize request argument(s) + request = servicecontrol_v1.ReportRequest( + ) + + # Make the request + response = await client.report(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.servicecontrol_v1.types.ReportRequest, dict]]): + The request object. Request message for the Report + method. + 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: + google.cloud.servicecontrol_v1.types.ReportResponse: + Response message for the Report + method. + + """ + # Create or coerce a protobuf request object. + request = service_controller.ReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.report, + default_timeout=16.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(( + ("service_name", request.service_name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ServiceControllerAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/client.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/client.py new file mode 100644 index 0000000..de04eb5 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/client.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.servicecontrol_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.servicecontrol_v1.types import check_error +from google.cloud.servicecontrol_v1.types import service_controller +from .transports.base import ServiceControllerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ServiceControllerGrpcTransport +from .transports.grpc_asyncio import ServiceControllerGrpcAsyncIOTransport +from .transports.rest import ServiceControllerRestTransport + + +class ServiceControllerClientMeta(type): + """Metaclass for the ServiceController 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[ServiceControllerTransport]] + _transport_registry["grpc"] = ServiceControllerGrpcTransport + _transport_registry["grpc_asyncio"] = ServiceControllerGrpcAsyncIOTransport + _transport_registry["rest"] = ServiceControllerRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ServiceControllerTransport]: + """Returns 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 ServiceControllerClient(metaclass=ServiceControllerClientMeta): + """`Google Service Control API `__ + + Lets clients check and report operations against a `managed + service `__. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + 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 = "servicecontrol.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServiceControllerClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @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: + ServiceControllerClient: 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) -> ServiceControllerTransport: + """Returns the transport used by the client instance. + + Returns: + ServiceControllerTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @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: + """Returns 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: + """Returns 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: + """Returns 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: + """Returns 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 {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ServiceControllerTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the service controller 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, ServiceControllerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ServiceControllerTransport): + # transport is a ServiceControllerTransport instance. + if credentials or client_options.credentials_file or api_key_value: + 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: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + 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, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def check(self, + request: Optional[Union[service_controller.CheckRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service_controller.CheckResponse: + r"""Checks whether an operation on a service should be allowed to + proceed based on the configuration of the service and related + policies. It must be called before the operation is executed. + + If feasible, the client should cache the check results and reuse + them for 60 seconds. In case of any server errors, the client + should rely on the cached results for much longer time to avoid + outage. WARNING: There is general 60s delay for the + configuration and policy propagation, therefore callers MUST NOT + depend on the ``Check`` method having the latest policy + information. + + NOTE: the + [CheckRequest][google.api.servicecontrol.v1.CheckRequest] has + the size limit (wire-format byte size) of 1MB. + + This method requires the ``servicemanagement.services.check`` + permission on the specified service. For more information, see + `Cloud IAM `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import servicecontrol_v1 + + def sample_check(): + # Create a client + client = servicecontrol_v1.ServiceControllerClient() + + # Initialize request argument(s) + request = servicecontrol_v1.CheckRequest( + ) + + # Make the request + response = client.check(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.servicecontrol_v1.types.CheckRequest, dict]): + The request object. Request message for the Check method. + 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: + google.cloud.servicecontrol_v1.types.CheckResponse: + Response message for the Check + method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a service_controller.CheckRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service_controller.CheckRequest): + request = service_controller.CheckRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.check] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service_name", request.service_name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def report(self, + request: Optional[Union[service_controller.ReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service_controller.ReportResponse: + r"""Reports operation results to Google Service Control, such as + logs and metrics. It should be called after an operation is + completed. + + If feasible, the client should aggregate reporting data for up + to 5 seconds to reduce API traffic. Limiting aggregation to 5 + seconds is to reduce data loss during client crashes. Clients + should carefully choose the aggregation time window to avoid + data loss risk more than 0.01% for business and compliance + reasons. + + NOTE: the + [ReportRequest][google.api.servicecontrol.v1.ReportRequest] has + the size limit (wire-format byte size) of 1MB. + + This method requires the ``servicemanagement.services.report`` + permission on the specified service. For more information, see + `Google Cloud IAM `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import servicecontrol_v1 + + def sample_report(): + # Create a client + client = servicecontrol_v1.ServiceControllerClient() + + # Initialize request argument(s) + request = servicecontrol_v1.ReportRequest( + ) + + # Make the request + response = client.report(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.servicecontrol_v1.types.ReportRequest, dict]): + The request object. Request message for the Report + method. + 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: + google.cloud.servicecontrol_v1.types.ReportResponse: + Response message for the Report + method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a service_controller.ReportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service_controller.ReportRequest): + request = service_controller.ReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.report] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service_name", request.service_name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ServiceControllerClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ServiceControllerClient", +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/__init__.py new file mode 100644 index 0000000..ad7b8b5 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 ServiceControllerTransport +from .grpc import ServiceControllerGrpcTransport +from .grpc_asyncio import ServiceControllerGrpcAsyncIOTransport +from .rest import ServiceControllerRestTransport +from .rest import ServiceControllerRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ServiceControllerTransport]] +_transport_registry['grpc'] = ServiceControllerGrpcTransport +_transport_registry['grpc_asyncio'] = ServiceControllerGrpcAsyncIOTransport +_transport_registry['rest'] = ServiceControllerRestTransport + +__all__ = ( + 'ServiceControllerTransport', + 'ServiceControllerGrpcTransport', + 'ServiceControllerGrpcAsyncIOTransport', + 'ServiceControllerRestTransport', + 'ServiceControllerRestInterceptor', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/base.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/base.py new file mode 100644 index 0000000..2706f34 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/base.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.servicecontrol_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicecontrol_v1.types import service_controller + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ServiceControllerTransport(abc.ABC): + """Abstract transport class for ServiceController.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', + ) + + DEFAULT_HOST: str = 'servicecontrol.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **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. + scopes (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. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.check: gapic_v1.method.wrap_method( + self.check, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=5.0, + ), + default_timeout=5.0, + client_info=client_info, + ), + self.report: gapic_v1.method.wrap_method( + self.report, + default_timeout=16.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def check(self) -> Callable[ + [service_controller.CheckRequest], + Union[ + service_controller.CheckResponse, + Awaitable[service_controller.CheckResponse] + ]]: + raise NotImplementedError() + + @property + def report(self) -> Callable[ + [service_controller.ReportRequest], + Union[ + service_controller.ReportResponse, + Awaitable[service_controller.ReportResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ServiceControllerTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc.py new file mode 100644 index 0000000..596f458 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc.py @@ -0,0 +1,328 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.servicecontrol_v1.types import service_controller +from .base import ServiceControllerTransport, DEFAULT_CLIENT_INFO + + +class ServiceControllerGrpcTransport(ServiceControllerTransport): + """gRPC backend transport for ServiceController. + + `Google Service Control API `__ + + Lets clients check and report operations against a `managed + service `__. + + 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 = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> 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 application 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 the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + 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._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + 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. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def check(self) -> Callable[ + [service_controller.CheckRequest], + service_controller.CheckResponse]: + r"""Return a callable for the check method over gRPC. + + Checks whether an operation on a service should be allowed to + proceed based on the configuration of the service and related + policies. It must be called before the operation is executed. + + If feasible, the client should cache the check results and reuse + them for 60 seconds. In case of any server errors, the client + should rely on the cached results for much longer time to avoid + outage. WARNING: There is general 60s delay for the + configuration and policy propagation, therefore callers MUST NOT + depend on the ``Check`` method having the latest policy + information. + + NOTE: the + [CheckRequest][google.api.servicecontrol.v1.CheckRequest] has + the size limit (wire-format byte size) of 1MB. + + This method requires the ``servicemanagement.services.check`` + permission on the specified service. For more information, see + `Cloud IAM `__. + + Returns: + Callable[[~.CheckRequest], + ~.CheckResponse]: + 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 'check' not in self._stubs: + self._stubs['check'] = self.grpc_channel.unary_unary( + '/google.api.servicecontrol.v1.ServiceController/Check', + request_serializer=service_controller.CheckRequest.serialize, + response_deserializer=service_controller.CheckResponse.deserialize, + ) + return self._stubs['check'] + + @property + def report(self) -> Callable[ + [service_controller.ReportRequest], + service_controller.ReportResponse]: + r"""Return a callable for the report method over gRPC. + + Reports operation results to Google Service Control, such as + logs and metrics. It should be called after an operation is + completed. + + If feasible, the client should aggregate reporting data for up + to 5 seconds to reduce API traffic. Limiting aggregation to 5 + seconds is to reduce data loss during client crashes. Clients + should carefully choose the aggregation time window to avoid + data loss risk more than 0.01% for business and compliance + reasons. + + NOTE: the + [ReportRequest][google.api.servicecontrol.v1.ReportRequest] has + the size limit (wire-format byte size) of 1MB. + + This method requires the ``servicemanagement.services.report`` + permission on the specified service. For more information, see + `Google Cloud IAM `__. + + Returns: + Callable[[~.ReportRequest], + ~.ReportResponse]: + 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 'report' not in self._stubs: + self._stubs['report'] = self.grpc_channel.unary_unary( + '/google.api.servicecontrol.v1.ServiceController/Report', + request_serializer=service_controller.ReportRequest.serialize, + response_deserializer=service_controller.ReportResponse.deserialize, + ) + return self._stubs['report'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ServiceControllerGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc_asyncio.py new file mode 100644 index 0000000..1fb7c1d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc_asyncio.py @@ -0,0 +1,327 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_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.servicecontrol_v1.types import service_controller +from .base import ServiceControllerTransport, DEFAULT_CLIENT_INFO +from .grpc import ServiceControllerGrpcTransport + + +class ServiceControllerGrpcAsyncIOTransport(ServiceControllerTransport): + """gRPC AsyncIO backend transport for ServiceController. + + `Google Service Control API `__ + + Lets clients check and report operations against a `managed + service `__. + + 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 = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (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. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> 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 application 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 the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + 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._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @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 check(self) -> Callable[ + [service_controller.CheckRequest], + Awaitable[service_controller.CheckResponse]]: + r"""Return a callable for the check method over gRPC. + + Checks whether an operation on a service should be allowed to + proceed based on the configuration of the service and related + policies. It must be called before the operation is executed. + + If feasible, the client should cache the check results and reuse + them for 60 seconds. In case of any server errors, the client + should rely on the cached results for much longer time to avoid + outage. WARNING: There is general 60s delay for the + configuration and policy propagation, therefore callers MUST NOT + depend on the ``Check`` method having the latest policy + information. + + NOTE: the + [CheckRequest][google.api.servicecontrol.v1.CheckRequest] has + the size limit (wire-format byte size) of 1MB. + + This method requires the ``servicemanagement.services.check`` + permission on the specified service. For more information, see + `Cloud IAM `__. + + Returns: + Callable[[~.CheckRequest], + Awaitable[~.CheckResponse]]: + 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 'check' not in self._stubs: + self._stubs['check'] = self.grpc_channel.unary_unary( + '/google.api.servicecontrol.v1.ServiceController/Check', + request_serializer=service_controller.CheckRequest.serialize, + response_deserializer=service_controller.CheckResponse.deserialize, + ) + return self._stubs['check'] + + @property + def report(self) -> Callable[ + [service_controller.ReportRequest], + Awaitable[service_controller.ReportResponse]]: + r"""Return a callable for the report method over gRPC. + + Reports operation results to Google Service Control, such as + logs and metrics. It should be called after an operation is + completed. + + If feasible, the client should aggregate reporting data for up + to 5 seconds to reduce API traffic. Limiting aggregation to 5 + seconds is to reduce data loss during client crashes. Clients + should carefully choose the aggregation time window to avoid + data loss risk more than 0.01% for business and compliance + reasons. + + NOTE: the + [ReportRequest][google.api.servicecontrol.v1.ReportRequest] has + the size limit (wire-format byte size) of 1MB. + + This method requires the ``servicemanagement.services.report`` + permission on the specified service. For more information, see + `Google Cloud IAM `__. + + Returns: + Callable[[~.ReportRequest], + Awaitable[~.ReportResponse]]: + 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 'report' not in self._stubs: + self._stubs['report'] = self.grpc_channel.unary_unary( + '/google.api.servicecontrol.v1.ServiceController/Report', + request_serializer=service_controller.ReportRequest.serialize, + response_deserializer=service_controller.ReportResponse.deserialize, + ) + return self._stubs['report'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ServiceControllerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/rest.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/rest.py new file mode 100644 index 0000000..45f50cf --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/rest.py @@ -0,0 +1,408 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.servicecontrol_v1.types import service_controller + +from .base import ServiceControllerTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ServiceControllerRestInterceptor: + """Interceptor for ServiceController. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the ServiceControllerRestTransport. + + .. code-block:: python + class MyCustomServiceControllerInterceptor(ServiceControllerRestInterceptor): + def pre_check(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_check(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_report(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_report(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ServiceControllerRestTransport(interceptor=MyCustomServiceControllerInterceptor()) + client = ServiceControllerClient(transport=transport) + + + """ + def pre_check(self, request: service_controller.CheckRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_controller.CheckRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for check + + Override in a subclass to manipulate the request or metadata + before they are sent to the ServiceController server. + """ + return request, metadata + + def post_check(self, response: service_controller.CheckResponse) -> service_controller.CheckResponse: + """Post-rpc interceptor for check + + Override in a subclass to manipulate the response + after it is returned by the ServiceController server but before + it is returned to user code. + """ + return response + def pre_report(self, request: service_controller.ReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_controller.ReportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for report + + Override in a subclass to manipulate the request or metadata + before they are sent to the ServiceController server. + """ + return request, metadata + + def post_report(self, response: service_controller.ReportResponse) -> service_controller.ReportResponse: + """Post-rpc interceptor for report + + Override in a subclass to manipulate the response + after it is returned by the ServiceController server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ServiceControllerRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ServiceControllerRestInterceptor + + +class ServiceControllerRestTransport(ServiceControllerTransport): + """REST backend transport for ServiceController. + + `Google Service Control API `__ + + Lets clients check and report operations against a `managed + service `__. + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[ServiceControllerRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ServiceControllerRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Check(ServiceControllerRestStub): + def __hash__(self): + return hash("Check") + + def __call__(self, + request: service_controller.CheckRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service_controller.CheckResponse: + r"""Call the check method over HTTP. + + Args: + request (~.service_controller.CheckRequest): + The request object. Request message for the Check method. + 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: + ~.service_controller.CheckResponse: + Response message for the Check + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/services/{service_name}:check', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_check(request, metadata) + pb_request = service_controller.CheckRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service_controller.CheckResponse() + pb_resp = service_controller.CheckResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_check(resp) + return resp + + class _Report(ServiceControllerRestStub): + def __hash__(self): + return hash("Report") + + def __call__(self, + request: service_controller.ReportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service_controller.ReportResponse: + r"""Call the report method over HTTP. + + Args: + request (~.service_controller.ReportRequest): + The request object. Request message for the Report + method. + 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: + ~.service_controller.ReportResponse: + Response message for the Report + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/services/{service_name}:report', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_report(request, metadata) + pb_request = service_controller.ReportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service_controller.ReportResponse() + pb_resp = service_controller.ReportResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_report(resp) + return resp + + @property + def check(self) -> Callable[ + [service_controller.CheckRequest], + service_controller.CheckResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Check(self._session, self._host, self._interceptor) # type: ignore + + @property + def report(self) -> Callable[ + [service_controller.ReportRequest], + service_controller.ReportResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Report(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ServiceControllerRestTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/__init__.py new file mode 100644 index 0000000..4f3ef6c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/__init__.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 .check_error import ( + CheckError, +) +from .distribution import ( + Distribution, +) +from .http_request import ( + HttpRequest, +) +from .log_entry import ( + LogEntry, + LogEntryOperation, + LogEntrySourceLocation, +) +from .metric_value import ( + MetricValue, + MetricValueSet, +) +from .operation import ( + Operation, +) +from .quota_controller import ( + AllocateQuotaRequest, + AllocateQuotaResponse, + QuotaError, + QuotaOperation, +) +from .service_controller import ( + CheckRequest, + CheckResponse, + ReportRequest, + ReportResponse, +) + +__all__ = ( + 'CheckError', + 'Distribution', + 'HttpRequest', + 'LogEntry', + 'LogEntryOperation', + 'LogEntrySourceLocation', + 'MetricValue', + 'MetricValueSet', + 'Operation', + 'AllocateQuotaRequest', + 'AllocateQuotaResponse', + 'QuotaError', + 'QuotaOperation', + 'CheckRequest', + 'CheckResponse', + 'ReportRequest', + 'ReportResponse', +) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/check_error.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/check_error.py new file mode 100644 index 0000000..fd3a7a8 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/check_error.py @@ -0,0 +1,164 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.api.servicecontrol.v1', + manifest={ + 'CheckError', + }, +) + + +class CheckError(proto.Message): + r"""Defines the errors to be returned in + [google.api.servicecontrol.v1.CheckResponse.check_errors][google.api.servicecontrol.v1.CheckResponse.check_errors]. + + Attributes: + code (google.cloud.servicecontrol_v1.types.CheckError.Code): + The error code. + subject (str): + Subject to whom this error applies. See the + specific code enum for more details on this + field. For example: + - "project:" + - "folder:" + - "organization:". + detail (str): + Free-form text providing details on the error + cause of the error. + status (google.rpc.status_pb2.Status): + Contains public information about the check error. If + available, ``status.code`` will be non zero and client can + propagate it out as public error. + """ + class Code(proto.Enum): + r"""Error codes for Check responses. + + Values: + ERROR_CODE_UNSPECIFIED (0): + This is never used in ``CheckResponse``. + NOT_FOUND (5): + The consumer's project id, network container, or resource + container was not found. Same as + [google.rpc.Code.NOT_FOUND][google.rpc.Code.NOT_FOUND]. + PERMISSION_DENIED (7): + The consumer doesn't have access to the specified resource. + Same as + [google.rpc.Code.PERMISSION_DENIED][google.rpc.Code.PERMISSION_DENIED]. + RESOURCE_EXHAUSTED (8): + Quota check failed. Same as + [google.rpc.Code.RESOURCE_EXHAUSTED][google.rpc.Code.RESOURCE_EXHAUSTED]. + SERVICE_NOT_ACTIVATED (104): + The consumer hasn't activated the service. + BILLING_DISABLED (107): + The consumer cannot access the service + because billing is disabled. + PROJECT_DELETED (108): + The consumer's project has been marked as + deleted (soft deletion). + PROJECT_INVALID (114): + The consumer's project number or id does not + represent a valid project. + CONSUMER_INVALID (125): + The input consumer info does not represent a + valid consumer folder or organization. + IP_ADDRESS_BLOCKED (109): + The IP address of the consumer is invalid for + the specific consumer project. + REFERER_BLOCKED (110): + The referer address of the consumer request + is invalid for the specific consumer project. + CLIENT_APP_BLOCKED (111): + The client application of the consumer + request is invalid for the specific consumer + project. + API_TARGET_BLOCKED (122): + The API targeted by this request is invalid + for the specified consumer project. + API_KEY_INVALID (105): + The consumer's API key is invalid. + API_KEY_EXPIRED (112): + The consumer's API Key has expired. + API_KEY_NOT_FOUND (113): + The consumer's API Key was not found in + config record. + INVALID_CREDENTIAL (123): + The credential in the request can not be + verified. + NAMESPACE_LOOKUP_UNAVAILABLE (300): + The backend server for looking up project + id/number is unavailable. + SERVICE_STATUS_UNAVAILABLE (301): + The backend server for checking service + status is unavailable. + BILLING_STATUS_UNAVAILABLE (302): + The backend server for checking billing + status is unavailable. + CLOUD_RESOURCE_MANAGER_BACKEND_UNAVAILABLE (305): + Cloud Resource Manager backend server is + unavailable. + """ + ERROR_CODE_UNSPECIFIED = 0 + NOT_FOUND = 5 + PERMISSION_DENIED = 7 + RESOURCE_EXHAUSTED = 8 + SERVICE_NOT_ACTIVATED = 104 + BILLING_DISABLED = 107 + PROJECT_DELETED = 108 + PROJECT_INVALID = 114 + CONSUMER_INVALID = 125 + IP_ADDRESS_BLOCKED = 109 + REFERER_BLOCKED = 110 + CLIENT_APP_BLOCKED = 111 + API_TARGET_BLOCKED = 122 + API_KEY_INVALID = 105 + API_KEY_EXPIRED = 112 + API_KEY_NOT_FOUND = 113 + INVALID_CREDENTIAL = 123 + NAMESPACE_LOOKUP_UNAVAILABLE = 300 + SERVICE_STATUS_UNAVAILABLE = 301 + BILLING_STATUS_UNAVAILABLE = 302 + CLOUD_RESOURCE_MANAGER_BACKEND_UNAVAILABLE = 305 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + subject: str = proto.Field( + proto.STRING, + number=4, + ) + detail: str = proto.Field( + proto.STRING, + number=2, + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/distribution.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/distribution.py new file mode 100644 index 0000000..321b27f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/distribution.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.api import distribution_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.api.servicecontrol.v1', + manifest={ + 'Distribution', + }, +) + + +class Distribution(proto.Message): + r"""Distribution represents a frequency distribution of double-valued + sample points. It contains the size of the population of sample + points plus additional optional information: + + - the arithmetic mean of the samples + - the minimum and maximum of the samples + - the sum-squared-deviation of the samples, used to compute + variance + - a histogram of the values of the sample points + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + count (int): + The total number of samples in the + distribution. Must be >= 0. + mean (float): + The arithmetic mean of the samples in the distribution. If + ``count`` is zero then this field must be zero. + minimum (float): + The minimum of the population of values. Ignored if + ``count`` is zero. + maximum (float): + The maximum of the population of values. Ignored if + ``count`` is zero. + sum_of_squared_deviation (float): + The sum of squared deviations from the mean: + Sum[i=1..count]((x_i - mean)^2) where each x_i is a sample + values. If ``count`` is zero then this field must be zero, + otherwise validation of the request fails. + bucket_counts (MutableSequence[int]): + The number of samples in each histogram bucket. + ``bucket_counts`` are optional. If present, they must sum to + the ``count`` value. + + The buckets are defined below in ``bucket_option``. There + are N buckets. ``bucket_counts[0]`` is the number of samples + in the underflow bucket. ``bucket_counts[1]`` to + ``bucket_counts[N-1]`` are the numbers of samples in each of + the finite buckets. And + ``bucket_counts[N] is the number of samples in the overflow bucket. See the comments of``\ bucket_option\` + below for more details. + + Any suffix of trailing zeros may be omitted. + linear_buckets (google.cloud.servicecontrol_v1.types.Distribution.LinearBuckets): + Buckets with constant width. + + This field is a member of `oneof`_ ``bucket_option``. + exponential_buckets (google.cloud.servicecontrol_v1.types.Distribution.ExponentialBuckets): + Buckets with exponentially growing width. + + This field is a member of `oneof`_ ``bucket_option``. + explicit_buckets (google.cloud.servicecontrol_v1.types.Distribution.ExplicitBuckets): + Buckets with arbitrary user-provided width. + + This field is a member of `oneof`_ ``bucket_option``. + exemplars (MutableSequence[google.api.distribution_pb2.Exemplar]): + Example points. Must be in increasing order of ``value`` + field. + """ + + class LinearBuckets(proto.Message): + r"""Describing buckets with constant width. + + Attributes: + num_finite_buckets (int): + The number of finite buckets. With the underflow and + overflow buckets, the total number of buckets is + ``num_finite_buckets`` + 2. See comments on + ``bucket_options`` for details. + width (float): + The i'th linear bucket covers the interval [offset + (i-1) + \* width, offset + i \* width) where i ranges from 1 to + num_finite_buckets, inclusive. Must be strictly positive. + offset (float): + The i'th linear bucket covers the interval [offset + (i-1) + \* width, offset + i \* width) where i ranges from 1 to + num_finite_buckets, inclusive. + """ + + num_finite_buckets: int = proto.Field( + proto.INT32, + number=1, + ) + width: float = proto.Field( + proto.DOUBLE, + number=2, + ) + offset: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + class ExponentialBuckets(proto.Message): + r"""Describing buckets with exponentially growing width. + + Attributes: + num_finite_buckets (int): + The number of finite buckets. With the underflow and + overflow buckets, the total number of buckets is + ``num_finite_buckets`` + 2. See comments on + ``bucket_options`` for details. + growth_factor (float): + The i'th exponential bucket covers the interval [scale \* + growth_factor^(i-1), scale \* growth_factor^i) where i + ranges from 1 to num_finite_buckets inclusive. Must be + larger than 1.0. + scale (float): + The i'th exponential bucket covers the interval [scale \* + growth_factor^(i-1), scale \* growth_factor^i) where i + ranges from 1 to num_finite_buckets inclusive. Must be > 0. + """ + + num_finite_buckets: int = proto.Field( + proto.INT32, + number=1, + ) + growth_factor: float = proto.Field( + proto.DOUBLE, + number=2, + ) + scale: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + class ExplicitBuckets(proto.Message): + r"""Describing buckets with arbitrary user-provided width. + + Attributes: + bounds (MutableSequence[float]): + 'bound' is a list of strictly increasing boundaries between + buckets. Note that a list of length N-1 defines N buckets + because of fenceposting. See comments on ``bucket_options`` + for details. + + The i'th finite bucket covers the interval [bound[i-1], + bound[i]) where i ranges from 1 to bound_size() - 1. Note + that there are no finite buckets at all if 'bound' only + contains a single element; in that special case the single + bound defines the boundary between the underflow and + overflow buckets. + + bucket number lower bound upper bound i == 0 (underflow) + -inf bound[i] 0 < i < bound_size() bound[i-1] bound[i] i == + bound_size() (overflow) bound[i-1] +inf + """ + + bounds: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=1, + ) + + count: int = proto.Field( + proto.INT64, + number=1, + ) + mean: float = proto.Field( + proto.DOUBLE, + number=2, + ) + minimum: float = proto.Field( + proto.DOUBLE, + number=3, + ) + maximum: float = proto.Field( + proto.DOUBLE, + number=4, + ) + sum_of_squared_deviation: float = proto.Field( + proto.DOUBLE, + number=5, + ) + bucket_counts: MutableSequence[int] = proto.RepeatedField( + proto.INT64, + number=6, + ) + linear_buckets: LinearBuckets = proto.Field( + proto.MESSAGE, + number=7, + oneof='bucket_option', + message=LinearBuckets, + ) + exponential_buckets: ExponentialBuckets = proto.Field( + proto.MESSAGE, + number=8, + oneof='bucket_option', + message=ExponentialBuckets, + ) + explicit_buckets: ExplicitBuckets = proto.Field( + proto.MESSAGE, + number=9, + oneof='bucket_option', + message=ExplicitBuckets, + ) + exemplars: MutableSequence[distribution_pb2.Distribution.Exemplar] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=distribution_pb2.Distribution.Exemplar, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/http_request.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/http_request.py new file mode 100644 index 0000000..d0dbb7d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/http_request.py @@ -0,0 +1,156 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.api.servicecontrol.v1', + manifest={ + 'HttpRequest', + }, +) + + +class HttpRequest(proto.Message): + r"""A common proto for logging HTTP requests. Only contains + semantics defined by the HTTP specification. Product-specific + logging information MUST be defined in a separate message. + + Attributes: + request_method (str): + The request method. Examples: ``"GET"``, ``"HEAD"``, + ``"PUT"``, ``"POST"``. + request_url (str): + The scheme (http, https), the host name, the path, and the + query portion of the URL that was requested. Example: + ``"http://example.com/some/info?color=red"``. + request_size (int): + The size of the HTTP request message in + bytes, including the request headers and the + request body. + status (int): + The response code indicating the status of + the response. Examples: 200, 404. + response_size (int): + The size of the HTTP response message sent + back to the client, in bytes, including the + response headers and the response body. + user_agent (str): + The user agent sent by the client. Example: + ``"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET CLR 1.0.3705)"``. + remote_ip (str): + The IP address (IPv4 or IPv6) of the client that issued the + HTTP request. Examples: ``"192.168.1.1"``, + ``"FE80::0202:B3FF:FE1E:8329"``. + server_ip (str): + The IP address (IPv4 or IPv6) of the origin + server that the request was sent to. + referer (str): + The referer URL of the request, as defined in `HTTP/1.1 + Header Field + Definitions `__. + latency (google.protobuf.duration_pb2.Duration): + The request processing latency on the server, + from the time the request was received until the + response was sent. + cache_lookup (bool): + Whether or not a cache lookup was attempted. + cache_hit (bool): + Whether or not an entity was served from + cache (with or without validation). + cache_validated_with_origin_server (bool): + Whether or not the response was validated with the origin + server before being served from cache. This field is only + meaningful if ``cache_hit`` is True. + cache_fill_bytes (int): + The number of HTTP response bytes inserted + into cache. Set only when a cache fill was + attempted. + protocol (str): + Protocol used for the request. Examples: + "HTTP/1.1", "HTTP/2", "websocket". + """ + + request_method: str = proto.Field( + proto.STRING, + number=1, + ) + request_url: str = proto.Field( + proto.STRING, + number=2, + ) + request_size: int = proto.Field( + proto.INT64, + number=3, + ) + status: int = proto.Field( + proto.INT32, + number=4, + ) + response_size: int = proto.Field( + proto.INT64, + number=5, + ) + user_agent: str = proto.Field( + proto.STRING, + number=6, + ) + remote_ip: str = proto.Field( + proto.STRING, + number=7, + ) + server_ip: str = proto.Field( + proto.STRING, + number=13, + ) + referer: str = proto.Field( + proto.STRING, + number=8, + ) + latency: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=14, + message=duration_pb2.Duration, + ) + cache_lookup: bool = proto.Field( + proto.BOOL, + number=11, + ) + cache_hit: bool = proto.Field( + proto.BOOL, + number=9, + ) + cache_validated_with_origin_server: bool = proto.Field( + proto.BOOL, + number=10, + ) + cache_fill_bytes: int = proto.Field( + proto.INT64, + number=12, + ) + protocol: str = proto.Field( + proto.STRING, + number=15, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/log_entry.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/log_entry.py new file mode 100644 index 0000000..7448655 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/log_entry.py @@ -0,0 +1,238 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.servicecontrol_v1.types import http_request as gas_http_request +from google.logging.type import log_severity_pb2 # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.api.servicecontrol.v1', + manifest={ + 'LogEntry', + 'LogEntryOperation', + 'LogEntrySourceLocation', + }, +) + + +class LogEntry(proto.Message): + r"""An individual log entry. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. The log to which this log entry belongs. Examples: + ``"syslog"``, ``"book_log"``. + timestamp (google.protobuf.timestamp_pb2.Timestamp): + The time the event described by the log entry + occurred. If omitted, defaults to operation + start time. + severity (google.logging.type.log_severity_pb2.LogSeverity): + The severity of the log entry. The default value is + ``LogSeverity.DEFAULT``. + http_request (google.cloud.servicecontrol_v1.types.HttpRequest): + Optional. Information about the HTTP request + associated with this log entry, if applicable. + trace (str): + Optional. Resource name of the trace associated with the log + entry, if any. If this field contains a relative resource + name, you can assume the name is relative to + ``//tracing.googleapis.com``. Example: + ``projects/my-projectid/traces/06796866738c859f2f19b7cfb3214824`` + insert_id (str): + A unique ID for the log entry used for deduplication. If + omitted, the implementation will generate one based on + operation_id. + labels (MutableMapping[str, str]): + A set of user-defined (key, value) data that + provides additional information about the log + entry. + proto_payload (google.protobuf.any_pb2.Any): + The log entry payload, represented as a protocol buffer that + is expressed as a JSON object. The only accepted type + currently is [AuditLog][google.cloud.audit.AuditLog]. + + This field is a member of `oneof`_ ``payload``. + text_payload (str): + The log entry payload, represented as a + Unicode string (UTF-8). + + This field is a member of `oneof`_ ``payload``. + struct_payload (google.protobuf.struct_pb2.Struct): + The log entry payload, represented as a + structure that is expressed as a JSON object. + + This field is a member of `oneof`_ ``payload``. + operation (google.cloud.servicecontrol_v1.types.LogEntryOperation): + Optional. Information about an operation + associated with the log entry, if applicable. + source_location (google.cloud.servicecontrol_v1.types.LogEntrySourceLocation): + Optional. Source code location information + associated with the log entry, if any. + """ + + name: str = proto.Field( + proto.STRING, + number=10, + ) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + severity: log_severity_pb2.LogSeverity = proto.Field( + proto.ENUM, + number=12, + enum=log_severity_pb2.LogSeverity, + ) + http_request: gas_http_request.HttpRequest = proto.Field( + proto.MESSAGE, + number=14, + message=gas_http_request.HttpRequest, + ) + trace: str = proto.Field( + proto.STRING, + number=15, + ) + insert_id: str = proto.Field( + proto.STRING, + number=4, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) + proto_payload: any_pb2.Any = proto.Field( + proto.MESSAGE, + number=2, + oneof='payload', + message=any_pb2.Any, + ) + text_payload: str = proto.Field( + proto.STRING, + number=3, + oneof='payload', + ) + struct_payload: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + oneof='payload', + message=struct_pb2.Struct, + ) + operation: 'LogEntryOperation' = proto.Field( + proto.MESSAGE, + number=16, + message='LogEntryOperation', + ) + source_location: 'LogEntrySourceLocation' = proto.Field( + proto.MESSAGE, + number=17, + message='LogEntrySourceLocation', + ) + + +class LogEntryOperation(proto.Message): + r"""Additional information about a potentially long-running + operation with which a log entry is associated. + + Attributes: + id (str): + Optional. An arbitrary operation identifier. + Log entries with the same identifier are assumed + to be part of the same operation. + producer (str): + Optional. An arbitrary producer identifier. The combination + of ``id`` and ``producer`` must be globally unique. Examples + for ``producer``: ``"MyDivision.MyBigCompany.com"``, + ``"github.com/MyProject/MyApplication"``. + first (bool): + Optional. Set this to True if this is the + first log entry in the operation. + last (bool): + Optional. Set this to True if this is the + last log entry in the operation. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + producer: str = proto.Field( + proto.STRING, + number=2, + ) + first: bool = proto.Field( + proto.BOOL, + number=3, + ) + last: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class LogEntrySourceLocation(proto.Message): + r"""Additional information about the source code location that + produced the log entry. + + Attributes: + file (str): + Optional. Source file name. Depending on the + runtime environment, this might be a simple name + or a fully-qualified name. + line (int): + Optional. Line within the source file. + 1-based; 0 indicates no line number available. + function (str): + Optional. Human-readable name of the function or method + being invoked, with optional context such as the class or + package name. This information may be used in contexts such + as the logs viewer, where a file and line number are less + meaningful. The format can vary by language. For example: + ``qual.if.ied.Class.method`` (Java), ``dir/package.func`` + (Go), ``function`` (Python). + """ + + file: str = proto.Field( + proto.STRING, + number=1, + ) + line: int = proto.Field( + proto.INT64, + number=2, + ) + function: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/metric_value.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/metric_value.py new file mode 100644 index 0000000..48d52cf --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/metric_value.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.servicecontrol_v1.types import distribution as gas_distribution +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.api.servicecontrol.v1', + manifest={ + 'MetricValue', + 'MetricValueSet', + }, +) + + +class MetricValue(proto.Message): + r"""Represents a single metric value. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + labels (MutableMapping[str, str]): + The labels describing the metric value. See comments on + [google.api.servicecontrol.v1.Operation.labels][google.api.servicecontrol.v1.Operation.labels] + for the overriding relationship. Note that this map must not + contain monitored resource labels. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The start of the time period over which this metric value's + measurement applies. The time period has different semantics + for different metric types (cumulative, delta, and gauge). + See the metric definition documentation in the service + configuration for details. If not specified, + [google.api.servicecontrol.v1.Operation.start_time][google.api.servicecontrol.v1.Operation.start_time] + will be used. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The end of the time period over which this metric value's + measurement applies. If not specified, + [google.api.servicecontrol.v1.Operation.end_time][google.api.servicecontrol.v1.Operation.end_time] + will be used. + bool_value (bool): + A boolean value. + + This field is a member of `oneof`_ ``value``. + int64_value (int): + A signed 64-bit integer value. + + This field is a member of `oneof`_ ``value``. + double_value (float): + A double precision floating point value. + + This field is a member of `oneof`_ ``value``. + string_value (str): + A text string value. + + This field is a member of `oneof`_ ``value``. + distribution_value (google.cloud.servicecontrol_v1.types.Distribution): + A distribution value. + + This field is a member of `oneof`_ ``value``. + """ + + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=1, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + bool_value: bool = proto.Field( + proto.BOOL, + number=4, + oneof='value', + ) + int64_value: int = proto.Field( + proto.INT64, + number=5, + oneof='value', + ) + double_value: float = proto.Field( + proto.DOUBLE, + number=6, + oneof='value', + ) + string_value: str = proto.Field( + proto.STRING, + number=7, + oneof='value', + ) + distribution_value: gas_distribution.Distribution = proto.Field( + proto.MESSAGE, + number=8, + oneof='value', + message=gas_distribution.Distribution, + ) + + +class MetricValueSet(proto.Message): + r"""Represents a set of metric values in the same metric. + Each metric value in the set should have a unique combination of + start time, end time, and label values. + + Attributes: + metric_name (str): + The metric name defined in the service + configuration. + metric_values (MutableSequence[google.cloud.servicecontrol_v1.types.MetricValue]): + The values in this metric. + """ + + metric_name: str = proto.Field( + proto.STRING, + number=1, + ) + metric_values: MutableSequence['MetricValue'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='MetricValue', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/operation.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/operation.py new file mode 100644 index 0000000..5db3c71 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/operation.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.servicecontrol_v1.types import log_entry +from google.cloud.servicecontrol_v1.types import metric_value +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.api.servicecontrol.v1', + manifest={ + 'Operation', + }, +) + + +class Operation(proto.Message): + r"""Represents information regarding an operation. + + Attributes: + operation_id (str): + Identity of the operation. This must be + unique within the scope of the service that + generated the operation. If the service calls + Check() and Report() on the same operation, the + two calls should carry the same id. + + UUID version 4 is recommended, though not + required. In scenarios where an operation is + computed from existing information and an + idempotent id is desirable for deduplication + purpose, UUID version 5 is recommended. See RFC + 4122 for details. + operation_name (str): + Fully qualified name of the operation. + Reserved for future use. + consumer_id (str): + Identity of the consumer who is using the service. This + field should be filled in for the operations initiated by a + consumer, but not for service-initiated operations that are + not related to a specific consumer. + + - This can be in one of the following formats: + + - project:PROJECT_ID, + - project\ ``_``\ number:PROJECT_NUMBER, + - projects/PROJECT_ID or PROJECT_NUMBER, + - folders/FOLDER_NUMBER, + - organizations/ORGANIZATION_NUMBER, + - api\ ``_``\ key:API_KEY. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Start time of the operation. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of the operation. Required when the operation is + used in + [ServiceController.Report][google.api.servicecontrol.v1.ServiceController.Report], + but optional when the operation is used in + [ServiceController.Check][google.api.servicecontrol.v1.ServiceController.Check]. + labels (MutableMapping[str, str]): + Labels describing the operation. Only the following labels + are allowed: + + - Labels describing monitored resources as defined in the + service configuration. + - Default labels of metric values. When specified, labels + defined in the metric value override these default. + - The following labels defined by Google Cloud Platform: + + - ``cloud.googleapis.com/location`` describing the + location where the operation happened, + - ``servicecontrol.googleapis.com/user_agent`` + describing the user agent of the API request, + - ``servicecontrol.googleapis.com/service_agent`` + describing the service used to handle the API request + (e.g. ESP), + - ``servicecontrol.googleapis.com/platform`` describing + the platform where the API is served, such as App + Engine, Compute Engine, or Kubernetes Engine. + metric_value_sets (MutableSequence[google.cloud.servicecontrol_v1.types.MetricValueSet]): + Represents information about this operation. + Each MetricValueSet corresponds to a metric + defined in the service configuration. The data + type used in the MetricValueSet must agree with + the data type specified in the metric + definition. + Within a single operation, it is not allowed to + have more than one MetricValue instances that + have the same metric names and identical label + value combinations. If a request has such + duplicated MetricValue instances, the entire + request is rejected with an invalid argument + error. + log_entries (MutableSequence[google.cloud.servicecontrol_v1.types.LogEntry]): + Represents information to be logged. + importance (google.cloud.servicecontrol_v1.types.Operation.Importance): + DO NOT USE. This is an experimental field. + extensions (MutableSequence[google.protobuf.any_pb2.Any]): + Unimplemented. + """ + class Importance(proto.Enum): + r"""Defines the importance of the data contained in the + operation. + + Values: + LOW (0): + Allows data caching, batching, and + aggregation. It provides higher performance with + higher data loss risk. + HIGH (1): + Disables data aggregation to minimize data + loss. It is for operations that contains + significant monetary value or audit trail. This + feature only applies to the client libraries. + """ + LOW = 0 + HIGH = 1 + + operation_id: str = proto.Field( + proto.STRING, + number=1, + ) + operation_name: str = proto.Field( + proto.STRING, + number=2, + ) + consumer_id: str = proto.Field( + proto.STRING, + number=3, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + metric_value_sets: MutableSequence[metric_value.MetricValueSet] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=metric_value.MetricValueSet, + ) + log_entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=log_entry.LogEntry, + ) + importance: Importance = proto.Field( + proto.ENUM, + number=11, + enum=Importance, + ) + extensions: MutableSequence[any_pb2.Any] = proto.RepeatedField( + proto.MESSAGE, + number=16, + message=any_pb2.Any, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/quota_controller.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/quota_controller.py new file mode 100644 index 0000000..c3f3395 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/quota_controller.py @@ -0,0 +1,328 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.servicecontrol_v1.types import metric_value +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.api.servicecontrol.v1', + manifest={ + 'AllocateQuotaRequest', + 'QuotaOperation', + 'AllocateQuotaResponse', + 'QuotaError', + }, +) + + +class AllocateQuotaRequest(proto.Message): + r"""Request message for the AllocateQuota method. + + Attributes: + service_name (str): + Name of the service as specified in the service + configuration. For example, ``"pubsub.googleapis.com"``. + + See [google.api.Service][google.api.Service] for the + definition of a service name. + allocate_operation (google.cloud.servicecontrol_v1.types.QuotaOperation): + Operation that describes the quota + allocation. + service_config_id (str): + Specifies which version of service + configuration should be used to process the + request. If unspecified or no matching version + can be found, the latest one will be used. + """ + + service_name: str = proto.Field( + proto.STRING, + number=1, + ) + allocate_operation: 'QuotaOperation' = proto.Field( + proto.MESSAGE, + number=2, + message='QuotaOperation', + ) + service_config_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class QuotaOperation(proto.Message): + r"""Represents information regarding a quota operation. + + Attributes: + operation_id (str): + Identity of the operation. This is expected to be unique + within the scope of the service that generated the + operation, and guarantees idempotency in case of retries. + + In order to ensure best performance and latency in the Quota + backends, operation_ids are optimally associated with time, + so that related operations can be accessed fast in storage. + For this reason, the recommended token for services that + intend to operate at a high QPS is Unix time in nanos + UUID + method_name (str): + Fully qualified name of the API method for which this quota + operation is requested. This name is used for matching quota + rules or metric rules and billing status rules defined in + service configuration. + + This field should not be set if any of the following is + true: (1) the quota operation is performed on non-API + resources. (2) quota_metrics is set because the caller is + doing quota override. + + Example of an RPC method name: + google.example.library.v1.LibraryService.CreateShelf + consumer_id (str): + Identity of the consumer for whom this quota operation is + being performed. + + This can be in one of the following formats: + project:, project_number:, + api_key:. + labels (MutableMapping[str, str]): + Labels describing the operation. + quota_metrics (MutableSequence[google.cloud.servicecontrol_v1.types.MetricValueSet]): + Represents information about this operation. Each + MetricValueSet corresponds to a metric defined in the + service configuration. The data type used in the + MetricValueSet must agree with the data type specified in + the metric definition. + + Within a single operation, it is not allowed to have more + than one MetricValue instances that have the same metric + names and identical label value combinations. If a request + has such duplicated MetricValue instances, the entire + request is rejected with an invalid argument error. + + This field is mutually exclusive with method_name. + quota_mode (google.cloud.servicecontrol_v1.types.QuotaOperation.QuotaMode): + Quota mode for this operation. + """ + class QuotaMode(proto.Enum): + r"""Supported quota modes. + + Values: + UNSPECIFIED (0): + Guard against implicit default. Must not be + used. + NORMAL (1): + For AllocateQuota request, allocates quota + for the amount specified in the service + configuration or specified using the quota + metrics. If the amount is higher than the + available quota, allocation error will be + returned and no quota will be allocated. + If multiple quotas are part of the request, and + one fails, none of the quotas are allocated or + released. + BEST_EFFORT (2): + The operation allocates quota for the amount specified in + the service configuration or specified using the quota + metrics. If the amount is higher than the available quota, + request does not fail but all available quota will be + allocated. For rate quota, BEST_EFFORT will continue to + deduct from other groups even if one does not have enough + quota. For allocation, it will find the minimum available + amount across all groups and deduct that amount from all the + affected groups. + CHECK_ONLY (3): + For AllocateQuota request, only checks if + there is enough quota available and does not + change the available quota. No lock is placed on + the available quota either. + QUERY_ONLY (4): + Unimplemented. When used in + AllocateQuotaRequest, this returns the effective + quota limit(s) in the response, and no quota + check will be performed. Not supported for other + requests, and even for AllocateQuotaRequest, + this is currently supported only for allowlisted + services. + ADJUST_ONLY (5): + The operation allocates quota for the amount + specified in the service configuration or + specified using the quota metrics. If the + requested amount is higher than the available + quota, request does not fail and remaining quota + would become negative (going over the limit). + Not supported for Rate Quota. + """ + UNSPECIFIED = 0 + NORMAL = 1 + BEST_EFFORT = 2 + CHECK_ONLY = 3 + QUERY_ONLY = 4 + ADJUST_ONLY = 5 + + operation_id: str = proto.Field( + proto.STRING, + number=1, + ) + method_name: str = proto.Field( + proto.STRING, + number=2, + ) + consumer_id: str = proto.Field( + proto.STRING, + number=3, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + quota_metrics: MutableSequence[metric_value.MetricValueSet] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=metric_value.MetricValueSet, + ) + quota_mode: QuotaMode = proto.Field( + proto.ENUM, + number=6, + enum=QuotaMode, + ) + + +class AllocateQuotaResponse(proto.Message): + r"""Response message for the AllocateQuota method. + + Attributes: + operation_id (str): + The same operation_id value used in the + AllocateQuotaRequest. Used for logging and diagnostics + purposes. + allocate_errors (MutableSequence[google.cloud.servicecontrol_v1.types.QuotaError]): + Indicates the decision of the allocate. + quota_metrics (MutableSequence[google.cloud.servicecontrol_v1.types.MetricValueSet]): + Quota metrics to indicate the result of allocation. + Depending on the request, one or more of the following + metrics will be included: + + 1. Per quota group or per quota metric incremental usage + will be specified using the following delta metric : + "serviceruntime.googleapis.com/api/consumer/quota_used_count" + + 2. The quota limit reached condition will be specified using + the following boolean metric : + "serviceruntime.googleapis.com/quota/exceeded". + service_config_id (str): + ID of the actual config used to process the + request. + """ + + operation_id: str = proto.Field( + proto.STRING, + number=1, + ) + allocate_errors: MutableSequence['QuotaError'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='QuotaError', + ) + quota_metrics: MutableSequence[metric_value.MetricValueSet] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=metric_value.MetricValueSet, + ) + service_config_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class QuotaError(proto.Message): + r"""Represents error information for + [QuotaOperation][google.api.servicecontrol.v1.QuotaOperation]. + + Attributes: + code (google.cloud.servicecontrol_v1.types.QuotaError.Code): + Error code. + subject (str): + Subject to whom this error applies. See the + specific enum for more details on this field. + For example, "clientip:" + or "project:". + description (str): + Free-form text that provides details on the + cause of the error. + status (google.rpc.status_pb2.Status): + Contains additional information about the quota error. If + available, ``status.code`` will be non zero. + """ + class Code(proto.Enum): + r"""Error codes related to project config validations are deprecated + since the quota controller methods do not perform these validations. + Instead services have to call the Check method, without + quota_properties field, to perform these validations before calling + the quota controller methods. These methods check only for project + deletion to be wipe out compliant. + + Values: + UNSPECIFIED (0): + This is never used. + RESOURCE_EXHAUSTED (8): + Quota allocation failed. Same as + [google.rpc.Code.RESOURCE_EXHAUSTED][google.rpc.Code.RESOURCE_EXHAUSTED]. + BILLING_NOT_ACTIVE (107): + Consumer cannot access the service because + the service requires active billing. + PROJECT_DELETED (108): + Consumer's project has been marked as deleted + (soft deletion). + API_KEY_INVALID (105): + Specified API key is invalid. + API_KEY_EXPIRED (112): + Specified API Key has expired. + """ + UNSPECIFIED = 0 + RESOURCE_EXHAUSTED = 8 + BILLING_NOT_ACTIVE = 107 + PROJECT_DELETED = 108 + API_KEY_INVALID = 105 + API_KEY_EXPIRED = 112 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + subject: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/service_controller.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/service_controller.py new file mode 100644 index 0000000..db95909 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/service_controller.py @@ -0,0 +1,322 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.servicecontrol_v1.types import check_error +from google.cloud.servicecontrol_v1.types import operation as gas_operation +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.api.servicecontrol.v1', + manifest={ + 'CheckRequest', + 'CheckResponse', + 'ReportRequest', + 'ReportResponse', + }, +) + + +class CheckRequest(proto.Message): + r"""Request message for the Check method. + + Attributes: + service_name (str): + The service name as specified in its service configuration. + For example, ``"pubsub.googleapis.com"``. + + See + `google.api.Service `__ + for the definition of a service name. + operation (google.cloud.servicecontrol_v1.types.Operation): + The operation to be checked. + service_config_id (str): + Specifies which version of service + configuration should be used to process the + request. + If unspecified or no matching version can be + found, the latest one will be used. + """ + + service_name: str = proto.Field( + proto.STRING, + number=1, + ) + operation: gas_operation.Operation = proto.Field( + proto.MESSAGE, + number=2, + message=gas_operation.Operation, + ) + service_config_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class CheckResponse(proto.Message): + r"""Response message for the Check method. + + Attributes: + operation_id (str): + The same operation_id value used in the + [CheckRequest][google.api.servicecontrol.v1.CheckRequest]. + Used for logging and diagnostics purposes. + check_errors (MutableSequence[google.cloud.servicecontrol_v1.types.CheckError]): + Indicate the decision of the check. + If no check errors are present, the service + should process the operation. Otherwise the + service should use the list of errors to + determine the appropriate action. + service_config_id (str): + The actual config id used to process the + request. + service_rollout_id (str): + The current service rollout id used to + process the request. + check_info (google.cloud.servicecontrol_v1.types.CheckResponse.CheckInfo): + Feedback data returned from the server during + processing a Check request. + """ + + class CheckInfo(proto.Message): + r"""Contains additional information about the check operation. + + Attributes: + unused_arguments (MutableSequence[str]): + A list of fields and label keys that are + ignored by the server. The client doesn't need + to send them for following requests to improve + performance and allow better aggregation. + consumer_info (google.cloud.servicecontrol_v1.types.CheckResponse.ConsumerInfo): + Consumer info of this check. + """ + + unused_arguments: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + consumer_info: 'CheckResponse.ConsumerInfo' = proto.Field( + proto.MESSAGE, + number=2, + message='CheckResponse.ConsumerInfo', + ) + + class ConsumerInfo(proto.Message): + r"""``ConsumerInfo`` provides information about the consumer. + + Attributes: + project_number (int): + The Google cloud project number, e.g. + 1234567890. A value of 0 indicates no project + number is found. + NOTE: This field is deprecated after we support + flexible consumer id. New code should not depend + on this field anymore. + type_ (google.cloud.servicecontrol_v1.types.CheckResponse.ConsumerInfo.ConsumerType): + The type of the consumer which should have been defined in + `Google Resource + Manager `__. + consumer_number (int): + The consumer identity number, can be Google + cloud project number, folder number or + organization number e.g. 1234567890. A value of + 0 indicates no consumer number is found. + """ + class ConsumerType(proto.Enum): + r"""The type of the consumer as defined in `Google Resource + Manager `__. + + Values: + CONSUMER_TYPE_UNSPECIFIED (0): + This is never used. + PROJECT (1): + The consumer is a Google Cloud Project. + FOLDER (2): + The consumer is a Google Cloud Folder. + ORGANIZATION (3): + The consumer is a Google Cloud Organization. + SERVICE_SPECIFIC (4): + Service-specific resource container which is + defined by the service producer to offer their + users the ability to manage service control + functionalities at a finer level of granularity + than the PROJECT. + """ + CONSUMER_TYPE_UNSPECIFIED = 0 + PROJECT = 1 + FOLDER = 2 + ORGANIZATION = 3 + SERVICE_SPECIFIC = 4 + + project_number: int = proto.Field( + proto.INT64, + number=1, + ) + type_: 'CheckResponse.ConsumerInfo.ConsumerType' = proto.Field( + proto.ENUM, + number=2, + enum='CheckResponse.ConsumerInfo.ConsumerType', + ) + consumer_number: int = proto.Field( + proto.INT64, + number=3, + ) + + operation_id: str = proto.Field( + proto.STRING, + number=1, + ) + check_errors: MutableSequence[check_error.CheckError] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=check_error.CheckError, + ) + service_config_id: str = proto.Field( + proto.STRING, + number=5, + ) + service_rollout_id: str = proto.Field( + proto.STRING, + number=11, + ) + check_info: CheckInfo = proto.Field( + proto.MESSAGE, + number=6, + message=CheckInfo, + ) + + +class ReportRequest(proto.Message): + r"""Request message for the Report method. + + Attributes: + service_name (str): + The service name as specified in its service configuration. + For example, ``"pubsub.googleapis.com"``. + + See + `google.api.Service `__ + for the definition of a service name. + operations (MutableSequence[google.cloud.servicecontrol_v1.types.Operation]): + Operations to be reported. + + Typically the service should report one operation per + request. Putting multiple operations into a single request + is allowed, but should be used only when multiple operations + are natually available at the time of the report. + + There is no limit on the number of operations in the same + ReportRequest, however the ReportRequest size should be no + larger than 1MB. See + [ReportResponse.report_errors][google.api.servicecontrol.v1.ReportResponse.report_errors] + for partial failure behavior. + service_config_id (str): + Specifies which version of service config + should be used to process the request. + + If unspecified or no matching version can be + found, the latest one will be used. + """ + + service_name: str = proto.Field( + proto.STRING, + number=1, + ) + operations: MutableSequence[gas_operation.Operation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gas_operation.Operation, + ) + service_config_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ReportResponse(proto.Message): + r"""Response message for the Report method. + + Attributes: + report_errors (MutableSequence[google.cloud.servicecontrol_v1.types.ReportResponse.ReportError]): + Partial failures, one for each ``Operation`` in the request + that failed processing. There are three possible + combinations of the RPC status: + + 1. The combination of a successful RPC status and an empty + ``report_errors`` list indicates a complete success where + all ``Operations`` in the request are processed + successfully. + 2. The combination of a successful RPC status and a + non-empty ``report_errors`` list indicates a partial + success where some ``Operations`` in the request + succeeded. Each ``Operation`` that failed processing has + a corresponding item in this list. + 3. A failed RPC status indicates a general non-deterministic + failure. When this happens, it's impossible to know which + of the 'Operations' in the request succeeded or failed. + service_config_id (str): + The actual config id used to process the + request. + service_rollout_id (str): + The current service rollout id used to + process the request. + """ + + class ReportError(proto.Message): + r"""Represents the processing error of one + [Operation][google.api.servicecontrol.v1.Operation] in the request. + + Attributes: + operation_id (str): + The + [Operation.operation_id][google.api.servicecontrol.v1.Operation.operation_id] + value from the request. + status (google.rpc.status_pb2.Status): + Details of the error when processing the + [Operation][google.api.servicecontrol.v1.Operation]. + """ + + operation_id: str = proto.Field( + proto.STRING, + number=1, + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + report_errors: MutableSequence[ReportError] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ReportError, + ) + service_config_id: str = proto.Field( + proto.STRING, + number=2, + ) + service_rollout_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 0000000..574c5ae --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 0000000..b494ed9 --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/servicecontrol_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_async.py b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_async.py new file mode 100644 index 0000000..f879c88 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 code. DO NOT EDIT! +# +# Snippet for AllocateQuota +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-control + + +# [START servicecontrol_v1_generated_QuotaController_AllocateQuota_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import servicecontrol_v1 + + +async def sample_allocate_quota(): + # Create a client + client = servicecontrol_v1.QuotaControllerAsyncClient() + + # Initialize request argument(s) + request = servicecontrol_v1.AllocateQuotaRequest( + ) + + # Make the request + response = await client.allocate_quota(request=request) + + # Handle the response + print(response) + +# [END servicecontrol_v1_generated_QuotaController_AllocateQuota_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_sync.py b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_sync.py new file mode 100644 index 0000000..24c544f --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 code. DO NOT EDIT! +# +# Snippet for AllocateQuota +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-control + + +# [START servicecontrol_v1_generated_QuotaController_AllocateQuota_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import servicecontrol_v1 + + +def sample_allocate_quota(): + # Create a client + client = servicecontrol_v1.QuotaControllerClient() + + # Initialize request argument(s) + request = servicecontrol_v1.AllocateQuotaRequest( + ) + + # Make the request + response = client.allocate_quota(request=request) + + # Handle the response + print(response) + +# [END servicecontrol_v1_generated_QuotaController_AllocateQuota_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_async.py b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_async.py new file mode 100644 index 0000000..15dc673 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 code. DO NOT EDIT! +# +# Snippet for Check +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-control + + +# [START servicecontrol_v1_generated_ServiceController_Check_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import servicecontrol_v1 + + +async def sample_check(): + # Create a client + client = servicecontrol_v1.ServiceControllerAsyncClient() + + # Initialize request argument(s) + request = servicecontrol_v1.CheckRequest( + ) + + # Make the request + response = await client.check(request=request) + + # Handle the response + print(response) + +# [END servicecontrol_v1_generated_ServiceController_Check_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_sync.py b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_sync.py new file mode 100644 index 0000000..4bc4b00 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 code. DO NOT EDIT! +# +# Snippet for Check +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-control + + +# [START servicecontrol_v1_generated_ServiceController_Check_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import servicecontrol_v1 + + +def sample_check(): + # Create a client + client = servicecontrol_v1.ServiceControllerClient() + + # Initialize request argument(s) + request = servicecontrol_v1.CheckRequest( + ) + + # Make the request + response = client.check(request=request) + + # Handle the response + print(response) + +# [END servicecontrol_v1_generated_ServiceController_Check_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_async.py b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_async.py new file mode 100644 index 0000000..811ea8e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 code. DO NOT EDIT! +# +# Snippet for Report +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-control + + +# [START servicecontrol_v1_generated_ServiceController_Report_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import servicecontrol_v1 + + +async def sample_report(): + # Create a client + client = servicecontrol_v1.ServiceControllerAsyncClient() + + # Initialize request argument(s) + request = servicecontrol_v1.ReportRequest( + ) + + # Make the request + response = await client.report(request=request) + + # Handle the response + print(response) + +# [END servicecontrol_v1_generated_ServiceController_Report_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_sync.py b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_sync.py new file mode 100644 index 0000000..687c7e0 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 code. DO NOT EDIT! +# +# Snippet for Report +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-control + + +# [START servicecontrol_v1_generated_ServiceController_Report_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import servicecontrol_v1 + + +def sample_report(): + # Create a client + client = servicecontrol_v1.ServiceControllerClient() + + # Initialize request argument(s) + request = servicecontrol_v1.ReportRequest( + ) + + # Make the request + response = client.report(request=request) + + # Handle the response + print(response) + +# [END servicecontrol_v1_generated_ServiceController_Report_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json new file mode 100644 index 0000000..ae2dfb3 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json @@ -0,0 +1,474 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.api.servicecontrol.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-service-control", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.servicecontrol_v1.QuotaControllerAsyncClient", + "shortName": "QuotaControllerAsyncClient" + }, + "fullName": "google.cloud.servicecontrol_v1.QuotaControllerAsyncClient.allocate_quota", + "method": { + "fullName": "google.api.servicecontrol.v1.QuotaController.AllocateQuota", + "service": { + "fullName": "google.api.servicecontrol.v1.QuotaController", + "shortName": "QuotaController" + }, + "shortName": "AllocateQuota" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.servicecontrol_v1.types.AllocateQuotaRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.servicecontrol_v1.types.AllocateQuotaResponse", + "shortName": "allocate_quota" + }, + "description": "Sample for AllocateQuota", + "file": "servicecontrol_v1_generated_quota_controller_allocate_quota_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "servicecontrol_v1_generated_QuotaController_AllocateQuota_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "servicecontrol_v1_generated_quota_controller_allocate_quota_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.servicecontrol_v1.QuotaControllerClient", + "shortName": "QuotaControllerClient" + }, + "fullName": "google.cloud.servicecontrol_v1.QuotaControllerClient.allocate_quota", + "method": { + "fullName": "google.api.servicecontrol.v1.QuotaController.AllocateQuota", + "service": { + "fullName": "google.api.servicecontrol.v1.QuotaController", + "shortName": "QuotaController" + }, + "shortName": "AllocateQuota" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.servicecontrol_v1.types.AllocateQuotaRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.servicecontrol_v1.types.AllocateQuotaResponse", + "shortName": "allocate_quota" + }, + "description": "Sample for AllocateQuota", + "file": "servicecontrol_v1_generated_quota_controller_allocate_quota_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "servicecontrol_v1_generated_QuotaController_AllocateQuota_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "servicecontrol_v1_generated_quota_controller_allocate_quota_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.servicecontrol_v1.ServiceControllerAsyncClient", + "shortName": "ServiceControllerAsyncClient" + }, + "fullName": "google.cloud.servicecontrol_v1.ServiceControllerAsyncClient.check", + "method": { + "fullName": "google.api.servicecontrol.v1.ServiceController.Check", + "service": { + "fullName": "google.api.servicecontrol.v1.ServiceController", + "shortName": "ServiceController" + }, + "shortName": "Check" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.servicecontrol_v1.types.CheckRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.servicecontrol_v1.types.CheckResponse", + "shortName": "check" + }, + "description": "Sample for Check", + "file": "servicecontrol_v1_generated_service_controller_check_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "servicecontrol_v1_generated_ServiceController_Check_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "servicecontrol_v1_generated_service_controller_check_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.servicecontrol_v1.ServiceControllerClient", + "shortName": "ServiceControllerClient" + }, + "fullName": "google.cloud.servicecontrol_v1.ServiceControllerClient.check", + "method": { + "fullName": "google.api.servicecontrol.v1.ServiceController.Check", + "service": { + "fullName": "google.api.servicecontrol.v1.ServiceController", + "shortName": "ServiceController" + }, + "shortName": "Check" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.servicecontrol_v1.types.CheckRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.servicecontrol_v1.types.CheckResponse", + "shortName": "check" + }, + "description": "Sample for Check", + "file": "servicecontrol_v1_generated_service_controller_check_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "servicecontrol_v1_generated_ServiceController_Check_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "servicecontrol_v1_generated_service_controller_check_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.servicecontrol_v1.ServiceControllerAsyncClient", + "shortName": "ServiceControllerAsyncClient" + }, + "fullName": "google.cloud.servicecontrol_v1.ServiceControllerAsyncClient.report", + "method": { + "fullName": "google.api.servicecontrol.v1.ServiceController.Report", + "service": { + "fullName": "google.api.servicecontrol.v1.ServiceController", + "shortName": "ServiceController" + }, + "shortName": "Report" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.servicecontrol_v1.types.ReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.servicecontrol_v1.types.ReportResponse", + "shortName": "report" + }, + "description": "Sample for Report", + "file": "servicecontrol_v1_generated_service_controller_report_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "servicecontrol_v1_generated_ServiceController_Report_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "servicecontrol_v1_generated_service_controller_report_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.servicecontrol_v1.ServiceControllerClient", + "shortName": "ServiceControllerClient" + }, + "fullName": "google.cloud.servicecontrol_v1.ServiceControllerClient.report", + "method": { + "fullName": "google.api.servicecontrol.v1.ServiceController.Report", + "service": { + "fullName": "google.api.servicecontrol.v1.ServiceController", + "shortName": "ServiceController" + }, + "shortName": "Report" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.servicecontrol_v1.types.ReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.servicecontrol_v1.types.ReportResponse", + "shortName": "report" + }, + "description": "Sample for Report", + "file": "servicecontrol_v1_generated_service_controller_report_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "servicecontrol_v1_generated_ServiceController_Report_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "servicecontrol_v1_generated_service_controller_report_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1/scripts/fixup_servicecontrol_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_servicecontrol_v1_keywords.py new file mode 100644 index 0000000..875c8ab --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_servicecontrol_v1_keywords.py @@ -0,0 +1,178 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 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 servicecontrolCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'allocate_quota': ('service_name', 'allocate_operation', 'service_config_id', ), + 'check': ('service_name', 'operation', 'service_config_id', ), + 'report': ('service_name', 'operations', 'service_config_id', ), + } + + 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: a.keyword.value not 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=servicecontrolCallTransformer(), +): + """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 servicecontrol 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/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 0000000..8108ffe --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-service-control' + + +description = "Google Cloud Service Control API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/servicecontrol/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-service-control" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v1/testing/constraints-3.10.txt b/owl-bot-staging/v1/testing/constraints-3.10.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1/testing/constraints-3.11.txt b/owl-bot-staging/v1/testing/constraints-3.11.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1/testing/constraints-3.12.txt b/owl-bot-staging/v1/testing/constraints-3.12.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1/testing/constraints-3.7.txt b/owl-bot-staging/v1/testing/constraints-3.7.txt new file mode 100644 index 0000000..6c44adf --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/v1/testing/constraints-3.8.txt b/owl-bot-staging/v1/testing/constraints-3.8.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1/testing/constraints-3.9.txt b/owl-bot-staging/v1/testing/constraints-3.9.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 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/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 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/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 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/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 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/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_quota_controller.py b/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_quota_controller.py new file mode 100644 index 0000000..fa2e0a6 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_quota_controller.py @@ -0,0 +1,1464 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api import distribution_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.servicecontrol_v1.services.quota_controller import QuotaControllerAsyncClient +from google.cloud.servicecontrol_v1.services.quota_controller import QuotaControllerClient +from google.cloud.servicecontrol_v1.services.quota_controller import transports +from google.cloud.servicecontrol_v1.types import distribution as gas_distribution +from google.cloud.servicecontrol_v1.types import metric_value +from google.cloud.servicecontrol_v1.types import quota_controller +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +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 QuotaControllerClient._get_default_mtls_endpoint(None) is None + assert QuotaControllerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert QuotaControllerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert QuotaControllerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert QuotaControllerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert QuotaControllerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (QuotaControllerClient, "grpc"), + (QuotaControllerAsyncClient, "grpc_asyncio"), + (QuotaControllerClient, "rest"), +]) +def test_quota_controller_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'servicecontrol.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://servicecontrol.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.QuotaControllerGrpcTransport, "grpc"), + (transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.QuotaControllerRestTransport, "rest"), +]) +def test_quota_controller_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (QuotaControllerClient, "grpc"), + (QuotaControllerAsyncClient, "grpc_asyncio"), + (QuotaControllerClient, "rest"), +]) +def test_quota_controller_client_from_service_account_file(client_class, transport_name): + creds = ga_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", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'servicecontrol.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://servicecontrol.googleapis.com' + ) + + +def test_quota_controller_client_get_transport_class(): + transport = QuotaControllerClient.get_transport_class() + available_transports = [ + transports.QuotaControllerGrpcTransport, + transports.QuotaControllerRestTransport, + ] + assert transport in available_transports + + transport = QuotaControllerClient.get_transport_class("grpc") + assert transport == transports.QuotaControllerGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (QuotaControllerClient, transports.QuotaControllerGrpcTransport, "grpc"), + (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio"), + (QuotaControllerClient, transports.QuotaControllerRestTransport, "rest"), +]) +@mock.patch.object(QuotaControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaControllerClient)) +@mock.patch.object(QuotaControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaControllerAsyncClient)) +def test_quota_controller_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(QuotaControllerClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_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(QuotaControllerClient, '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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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(transport=transport_name) + + # 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(transport=transport_name) + + # 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (QuotaControllerClient, transports.QuotaControllerGrpcTransport, "grpc", "true"), + (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (QuotaControllerClient, transports.QuotaControllerGrpcTransport, "grpc", "false"), + (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (QuotaControllerClient, transports.QuotaControllerRestTransport, "rest", "true"), + (QuotaControllerClient, transports.QuotaControllerRestTransport, "rest", "false"), +]) +@mock.patch.object(QuotaControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaControllerClient)) +@mock.patch.object(QuotaControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaControllerAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_quota_controller_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: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + QuotaControllerClient, QuotaControllerAsyncClient +]) +@mock.patch.object(QuotaControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaControllerClient)) +@mock.patch.object(QuotaControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaControllerAsyncClient)) +def test_quota_controller_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (QuotaControllerClient, transports.QuotaControllerGrpcTransport, "grpc"), + (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio"), + (QuotaControllerClient, transports.QuotaControllerRestTransport, "rest"), +]) +def test_quota_controller_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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (QuotaControllerClient, transports.QuotaControllerGrpcTransport, "grpc", grpc_helpers), + (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (QuotaControllerClient, transports.QuotaControllerRestTransport, "rest", None), +]) +def test_quota_controller_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_quota_controller_client_client_options_from_dict(): + with mock.patch('google.cloud.servicecontrol_v1.services.quota_controller.transports.QuotaControllerGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = QuotaControllerClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (QuotaControllerClient, transports.QuotaControllerGrpcTransport, "grpc", grpc_helpers), + (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_quota_controller_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "servicecontrol.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', +), + scopes=None, + default_host="servicecontrol.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + quota_controller.AllocateQuotaRequest, + dict, +]) +def test_allocate_quota(request_type, transport: str = 'grpc'): + client = QuotaControllerClient( + credentials=ga_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.allocate_quota), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = quota_controller.AllocateQuotaResponse( + operation_id='operation_id_value', + service_config_id='service_config_id_value', + ) + response = client.allocate_quota(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == quota_controller.AllocateQuotaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, quota_controller.AllocateQuotaResponse) + assert response.operation_id == 'operation_id_value' + assert response.service_config_id == 'service_config_id_value' + + +def test_allocate_quota_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = QuotaControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.allocate_quota), + '__call__') as call: + client.allocate_quota() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == quota_controller.AllocateQuotaRequest() + +@pytest.mark.asyncio +async def test_allocate_quota_async(transport: str = 'grpc_asyncio', request_type=quota_controller.AllocateQuotaRequest): + client = QuotaControllerAsyncClient( + credentials=ga_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.allocate_quota), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(quota_controller.AllocateQuotaResponse( + operation_id='operation_id_value', + service_config_id='service_config_id_value', + )) + response = await client.allocate_quota(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == quota_controller.AllocateQuotaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, quota_controller.AllocateQuotaResponse) + assert response.operation_id == 'operation_id_value' + assert response.service_config_id == 'service_config_id_value' + + +@pytest.mark.asyncio +async def test_allocate_quota_async_from_dict(): + await test_allocate_quota_async(request_type=dict) + + +def test_allocate_quota_field_headers(): + client = QuotaControllerClient( + credentials=ga_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 = quota_controller.AllocateQuotaRequest() + + request.service_name = 'service_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.allocate_quota), + '__call__') as call: + call.return_value = quota_controller.AllocateQuotaResponse() + client.allocate_quota(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', + 'service_name=service_name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_allocate_quota_field_headers_async(): + client = QuotaControllerAsyncClient( + credentials=ga_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 = quota_controller.AllocateQuotaRequest() + + request.service_name = 'service_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.allocate_quota), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(quota_controller.AllocateQuotaResponse()) + await client.allocate_quota(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', + 'service_name=service_name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + quota_controller.AllocateQuotaRequest, + dict, +]) +def test_allocate_quota_rest(request_type): + client = QuotaControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service_name': 'sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = quota_controller.AllocateQuotaResponse( + operation_id='operation_id_value', + service_config_id='service_config_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = quota_controller.AllocateQuotaResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.allocate_quota(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, quota_controller.AllocateQuotaResponse) + assert response.operation_id == 'operation_id_value' + assert response.service_config_id == 'service_config_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_allocate_quota_rest_interceptors(null_interceptor): + transport = transports.QuotaControllerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.QuotaControllerRestInterceptor(), + ) + client = QuotaControllerClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.QuotaControllerRestInterceptor, "post_allocate_quota") as post, \ + mock.patch.object(transports.QuotaControllerRestInterceptor, "pre_allocate_quota") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = quota_controller.AllocateQuotaRequest.pb(quota_controller.AllocateQuotaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = quota_controller.AllocateQuotaResponse.to_json(quota_controller.AllocateQuotaResponse()) + + request = quota_controller.AllocateQuotaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = quota_controller.AllocateQuotaResponse() + + client.allocate_quota(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_allocate_quota_rest_bad_request(transport: str = 'rest', request_type=quota_controller.AllocateQuotaRequest): + client = QuotaControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service_name': 'sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.allocate_quota(request) + + +def test_allocate_quota_rest_error(): + client = QuotaControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.QuotaControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = QuotaControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.QuotaControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = QuotaControllerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.QuotaControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = QuotaControllerClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = QuotaControllerClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.QuotaControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = QuotaControllerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.QuotaControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = QuotaControllerClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.QuotaControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.QuotaControllerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.QuotaControllerGrpcTransport, + transports.QuotaControllerGrpcAsyncIOTransport, + transports.QuotaControllerRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = QuotaControllerClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = QuotaControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.QuotaControllerGrpcTransport, + ) + +def test_quota_controller_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.QuotaControllerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_quota_controller_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.servicecontrol_v1.services.quota_controller.transports.QuotaControllerTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.QuotaControllerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'allocate_quota', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_quota_controller_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.servicecontrol_v1.services.quota_controller.transports.QuotaControllerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.QuotaControllerTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', +), + quota_project_id="octopus", + ) + + +def test_quota_controller_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.servicecontrol_v1.services.quota_controller.transports.QuotaControllerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.QuotaControllerTransport() + adc.assert_called_once() + + +def test_quota_controller_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + QuotaControllerClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.QuotaControllerGrpcTransport, + transports.QuotaControllerGrpcAsyncIOTransport, + ], +) +def test_quota_controller_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/servicecontrol',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.QuotaControllerGrpcTransport, + transports.QuotaControllerGrpcAsyncIOTransport, + transports.QuotaControllerRestTransport, + ], +) +def test_quota_controller_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.QuotaControllerGrpcTransport, grpc_helpers), + (transports.QuotaControllerGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_quota_controller_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "servicecontrol.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', +), + scopes=["1", "2"], + default_host="servicecontrol.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.QuotaControllerGrpcTransport, transports.QuotaControllerGrpcAsyncIOTransport]) +def test_quota_controller_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_quota_controller_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.QuotaControllerRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_quota_controller_host_no_port(transport_name): + client = QuotaControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicecontrol.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'servicecontrol.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://servicecontrol.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_quota_controller_host_with_port(transport_name): + client = QuotaControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicecontrol.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'servicecontrol.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://servicecontrol.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_quota_controller_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = QuotaControllerClient( + credentials=creds1, + transport=transport_name, + ) + client2 = QuotaControllerClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.allocate_quota._session + session2 = client2.transport.allocate_quota._session + assert session1 != session2 +def test_quota_controller_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.QuotaControllerGrpcTransport( + 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_quota_controller_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.QuotaControllerGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.QuotaControllerGrpcTransport, transports.QuotaControllerGrpcAsyncIOTransport]) +def test_quota_controller_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") 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 = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.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=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.QuotaControllerGrpcTransport, transports.QuotaControllerGrpcAsyncIOTransport]) +def test_quota_controller_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") 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=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = QuotaControllerClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = QuotaControllerClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = QuotaControllerClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = QuotaControllerClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = QuotaControllerClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = QuotaControllerClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = QuotaControllerClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = QuotaControllerClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = QuotaControllerClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = QuotaControllerClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = QuotaControllerClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = QuotaControllerClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = QuotaControllerClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = QuotaControllerClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = QuotaControllerClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.QuotaControllerTransport, '_prep_wrapped_messages') as prep: + client = QuotaControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.QuotaControllerTransport, '_prep_wrapped_messages') as prep: + transport_class = QuotaControllerClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = QuotaControllerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = QuotaControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = QuotaControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (QuotaControllerClient, transports.QuotaControllerGrpcTransport), + (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + 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=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_service_controller.py b/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_service_controller.py new file mode 100644 index 0000000..918b168 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_service_controller.py @@ -0,0 +1,1740 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api import distribution_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.servicecontrol_v1.services.service_controller import ServiceControllerAsyncClient +from google.cloud.servicecontrol_v1.services.service_controller import ServiceControllerClient +from google.cloud.servicecontrol_v1.services.service_controller import transports +from google.cloud.servicecontrol_v1.types import check_error +from google.cloud.servicecontrol_v1.types import distribution as gas_distribution +from google.cloud.servicecontrol_v1.types import http_request +from google.cloud.servicecontrol_v1.types import log_entry +from google.cloud.servicecontrol_v1.types import metric_value +from google.cloud.servicecontrol_v1.types import operation +from google.cloud.servicecontrol_v1.types import service_controller +from google.logging.type import log_severity_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +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 ServiceControllerClient._get_default_mtls_endpoint(None) is None + assert ServiceControllerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ServiceControllerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ServiceControllerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ServiceControllerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ServiceControllerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ServiceControllerClient, "grpc"), + (ServiceControllerAsyncClient, "grpc_asyncio"), + (ServiceControllerClient, "rest"), +]) +def test_service_controller_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'servicecontrol.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://servicecontrol.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ServiceControllerGrpcTransport, "grpc"), + (transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ServiceControllerRestTransport, "rest"), +]) +def test_service_controller_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ServiceControllerClient, "grpc"), + (ServiceControllerAsyncClient, "grpc_asyncio"), + (ServiceControllerClient, "rest"), +]) +def test_service_controller_client_from_service_account_file(client_class, transport_name): + creds = ga_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", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'servicecontrol.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://servicecontrol.googleapis.com' + ) + + +def test_service_controller_client_get_transport_class(): + transport = ServiceControllerClient.get_transport_class() + available_transports = [ + transports.ServiceControllerGrpcTransport, + transports.ServiceControllerRestTransport, + ] + assert transport in available_transports + + transport = ServiceControllerClient.get_transport_class("grpc") + assert transport == transports.ServiceControllerGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc"), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio"), + (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest"), +]) +@mock.patch.object(ServiceControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerClient)) +@mock.patch.object(ServiceControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerAsyncClient)) +def test_service_controller_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(ServiceControllerClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_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(ServiceControllerClient, '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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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(transport=transport_name) + + # 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(transport=transport_name) + + # 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", "true"), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", "false"), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest", "true"), + (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest", "false"), +]) +@mock.patch.object(ServiceControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerClient)) +@mock.patch.object(ServiceControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_service_controller_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: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ServiceControllerClient, ServiceControllerAsyncClient +]) +@mock.patch.object(ServiceControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerClient)) +@mock.patch.object(ServiceControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerAsyncClient)) +def test_service_controller_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc"), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio"), + (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest"), +]) +def test_service_controller_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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", grpc_helpers), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest", None), +]) +def test_service_controller_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_service_controller_client_client_options_from_dict(): + with mock.patch('google.cloud.servicecontrol_v1.services.service_controller.transports.ServiceControllerGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ServiceControllerClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", grpc_helpers), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_service_controller_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "servicecontrol.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', +), + scopes=None, + default_host="servicecontrol.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + service_controller.CheckRequest, + dict, +]) +def test_check(request_type, transport: str = 'grpc'): + client = ServiceControllerClient( + credentials=ga_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.check), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service_controller.CheckResponse( + operation_id='operation_id_value', + service_config_id='service_config_id_value', + service_rollout_id='service_rollout_id_value', + ) + response = client.check(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service_controller.CheckRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service_controller.CheckResponse) + assert response.operation_id == 'operation_id_value' + assert response.service_config_id == 'service_config_id_value' + assert response.service_rollout_id == 'service_rollout_id_value' + + +def test_check_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check), + '__call__') as call: + client.check() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service_controller.CheckRequest() + +@pytest.mark.asyncio +async def test_check_async(transport: str = 'grpc_asyncio', request_type=service_controller.CheckRequest): + client = ServiceControllerAsyncClient( + credentials=ga_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.check), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_controller.CheckResponse( + operation_id='operation_id_value', + service_config_id='service_config_id_value', + service_rollout_id='service_rollout_id_value', + )) + response = await client.check(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service_controller.CheckRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service_controller.CheckResponse) + assert response.operation_id == 'operation_id_value' + assert response.service_config_id == 'service_config_id_value' + assert response.service_rollout_id == 'service_rollout_id_value' + + +@pytest.mark.asyncio +async def test_check_async_from_dict(): + await test_check_async(request_type=dict) + + +def test_check_field_headers(): + client = ServiceControllerClient( + credentials=ga_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 = service_controller.CheckRequest() + + request.service_name = 'service_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check), + '__call__') as call: + call.return_value = service_controller.CheckResponse() + client.check(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', + 'service_name=service_name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_check_field_headers_async(): + client = ServiceControllerAsyncClient( + credentials=ga_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 = service_controller.CheckRequest() + + request.service_name = 'service_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_controller.CheckResponse()) + await client.check(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', + 'service_name=service_name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + service_controller.ReportRequest, + dict, +]) +def test_report(request_type, transport: str = 'grpc'): + client = ServiceControllerClient( + credentials=ga_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.report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service_controller.ReportResponse( + service_config_id='service_config_id_value', + service_rollout_id='service_rollout_id_value', + ) + response = client.report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service_controller.ReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service_controller.ReportResponse) + assert response.service_config_id == 'service_config_id_value' + assert response.service_rollout_id == 'service_rollout_id_value' + + +def test_report_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.report), + '__call__') as call: + client.report() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service_controller.ReportRequest() + +@pytest.mark.asyncio +async def test_report_async(transport: str = 'grpc_asyncio', request_type=service_controller.ReportRequest): + client = ServiceControllerAsyncClient( + credentials=ga_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.report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_controller.ReportResponse( + service_config_id='service_config_id_value', + service_rollout_id='service_rollout_id_value', + )) + response = await client.report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service_controller.ReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service_controller.ReportResponse) + assert response.service_config_id == 'service_config_id_value' + assert response.service_rollout_id == 'service_rollout_id_value' + + +@pytest.mark.asyncio +async def test_report_async_from_dict(): + await test_report_async(request_type=dict) + + +def test_report_field_headers(): + client = ServiceControllerClient( + credentials=ga_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 = service_controller.ReportRequest() + + request.service_name = 'service_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.report), + '__call__') as call: + call.return_value = service_controller.ReportResponse() + client.report(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', + 'service_name=service_name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_report_field_headers_async(): + client = ServiceControllerAsyncClient( + credentials=ga_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 = service_controller.ReportRequest() + + request.service_name = 'service_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.report), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_controller.ReportResponse()) + await client.report(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', + 'service_name=service_name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + service_controller.CheckRequest, + dict, +]) +def test_check_rest(request_type): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service_name': 'sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service_controller.CheckResponse( + operation_id='operation_id_value', + service_config_id='service_config_id_value', + service_rollout_id='service_rollout_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service_controller.CheckResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.check(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service_controller.CheckResponse) + assert response.operation_id == 'operation_id_value' + assert response.service_config_id == 'service_config_id_value' + assert response.service_rollout_id == 'service_rollout_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_check_rest_interceptors(null_interceptor): + transport = transports.ServiceControllerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServiceControllerRestInterceptor(), + ) + client = ServiceControllerClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ServiceControllerRestInterceptor, "post_check") as post, \ + mock.patch.object(transports.ServiceControllerRestInterceptor, "pre_check") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service_controller.CheckRequest.pb(service_controller.CheckRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service_controller.CheckResponse.to_json(service_controller.CheckResponse()) + + request = service_controller.CheckRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service_controller.CheckResponse() + + client.check(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_check_rest_bad_request(transport: str = 'rest', request_type=service_controller.CheckRequest): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service_name': 'sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.check(request) + + +def test_check_rest_error(): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service_controller.ReportRequest, + dict, +]) +def test_report_rest(request_type): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service_name': 'sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service_controller.ReportResponse( + service_config_id='service_config_id_value', + service_rollout_id='service_rollout_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service_controller.ReportResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.report(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service_controller.ReportResponse) + assert response.service_config_id == 'service_config_id_value' + assert response.service_rollout_id == 'service_rollout_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_report_rest_interceptors(null_interceptor): + transport = transports.ServiceControllerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServiceControllerRestInterceptor(), + ) + client = ServiceControllerClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ServiceControllerRestInterceptor, "post_report") as post, \ + mock.patch.object(transports.ServiceControllerRestInterceptor, "pre_report") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service_controller.ReportRequest.pb(service_controller.ReportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service_controller.ReportResponse.to_json(service_controller.ReportResponse()) + + request = service_controller.ReportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service_controller.ReportResponse() + + client.report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_report_rest_bad_request(transport: str = 'rest', request_type=service_controller.ReportRequest): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service_name': 'sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.report(request) + + +def test_report_rest_error(): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServiceControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServiceControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServiceControllerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServiceControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServiceControllerClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServiceControllerClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServiceControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServiceControllerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServiceControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServiceControllerClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServiceControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServiceControllerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ServiceControllerGrpcTransport, + transports.ServiceControllerGrpcAsyncIOTransport, + transports.ServiceControllerRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = ServiceControllerClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ServiceControllerGrpcTransport, + ) + +def test_service_controller_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ServiceControllerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_service_controller_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.servicecontrol_v1.services.service_controller.transports.ServiceControllerTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ServiceControllerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'check', + 'report', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_service_controller_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.servicecontrol_v1.services.service_controller.transports.ServiceControllerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServiceControllerTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', +), + quota_project_id="octopus", + ) + + +def test_service_controller_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.servicecontrol_v1.services.service_controller.transports.ServiceControllerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServiceControllerTransport() + adc.assert_called_once() + + +def test_service_controller_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ServiceControllerClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServiceControllerGrpcTransport, + transports.ServiceControllerGrpcAsyncIOTransport, + ], +) +def test_service_controller_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/servicecontrol',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServiceControllerGrpcTransport, + transports.ServiceControllerGrpcAsyncIOTransport, + transports.ServiceControllerRestTransport, + ], +) +def test_service_controller_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ServiceControllerGrpcTransport, grpc_helpers), + (transports.ServiceControllerGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_service_controller_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "servicecontrol.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', +), + scopes=["1", "2"], + default_host="servicecontrol.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ServiceControllerGrpcTransport, transports.ServiceControllerGrpcAsyncIOTransport]) +def test_service_controller_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_service_controller_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ServiceControllerRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_service_controller_host_no_port(transport_name): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicecontrol.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'servicecontrol.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://servicecontrol.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_service_controller_host_with_port(transport_name): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicecontrol.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'servicecontrol.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://servicecontrol.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_service_controller_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ServiceControllerClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ServiceControllerClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.check._session + session2 = client2.transport.check._session + assert session1 != session2 + session1 = client1.transport.report._session + session2 = client2.transport.report._session + assert session1 != session2 +def test_service_controller_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServiceControllerGrpcTransport( + 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_service_controller_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServiceControllerGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ServiceControllerGrpcTransport, transports.ServiceControllerGrpcAsyncIOTransport]) +def test_service_controller_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") 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 = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.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=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ServiceControllerGrpcTransport, transports.ServiceControllerGrpcAsyncIOTransport]) +def test_service_controller_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") 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=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ServiceControllerClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ServiceControllerClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ServiceControllerClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = ServiceControllerClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ServiceControllerClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ServiceControllerClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ServiceControllerClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ServiceControllerClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ServiceControllerClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = ServiceControllerClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ServiceControllerClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ServiceControllerClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ServiceControllerClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ServiceControllerClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ServiceControllerClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.ServiceControllerTransport, '_prep_wrapped_messages') as prep: + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ServiceControllerTransport, '_prep_wrapped_messages') as prep: + transport_class = ServiceControllerClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ServiceControllerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (ServiceControllerClient, transports.ServiceControllerGrpcTransport), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + 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=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc new file mode 100644 index 0000000..db73969 --- /dev/null +++ b/owl-bot-staging/v2/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/servicecontrol/__init__.py + google/cloud/servicecontrol/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/v2/.flake8 b/owl-bot-staging/v2/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v2/.flake8 @@ -0,0 +1,33 @@ +# -*- 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. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in new file mode 100644 index 0000000..732f0e2 --- /dev/null +++ b/owl-bot-staging/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/servicecontrol *.py +recursive-include google/cloud/servicecontrol_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst new file mode 100644 index 0000000..68e4838 --- /dev/null +++ b/owl-bot-staging/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Servicecontrol API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Servicecontrol API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2/docs/conf.py b/owl-bot-staging/v2/docs/conf.py new file mode 100644 index 0000000..4c7d6b4 --- /dev/null +++ b/owl-bot-staging/v2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +# +# google-cloud-service-control documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-service-control" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-service-control-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-service-control.tex", + u"google-cloud-service-control Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-service-control", + u"Google Cloud Servicecontrol Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-service-control", + u"google-cloud-service-control Documentation", + author, + "google-cloud-service-control", + "GAPIC library for Google Cloud Servicecontrol API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst new file mode 100644 index 0000000..d8d7f01 --- /dev/null +++ b/owl-bot-staging/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + servicecontrol_v2/services + servicecontrol_v2/types diff --git a/owl-bot-staging/v2/docs/servicecontrol_v2/service_controller.rst b/owl-bot-staging/v2/docs/servicecontrol_v2/service_controller.rst new file mode 100644 index 0000000..56ae69a --- /dev/null +++ b/owl-bot-staging/v2/docs/servicecontrol_v2/service_controller.rst @@ -0,0 +1,6 @@ +ServiceController +----------------------------------- + +.. automodule:: google.cloud.servicecontrol_v2.services.service_controller + :members: + :inherited-members: diff --git a/owl-bot-staging/v2/docs/servicecontrol_v2/services.rst b/owl-bot-staging/v2/docs/servicecontrol_v2/services.rst new file mode 100644 index 0000000..a56e496 --- /dev/null +++ b/owl-bot-staging/v2/docs/servicecontrol_v2/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Servicecontrol v2 API +=============================================== +.. toctree:: + :maxdepth: 2 + + service_controller diff --git a/owl-bot-staging/v2/docs/servicecontrol_v2/types.rst b/owl-bot-staging/v2/docs/servicecontrol_v2/types.rst new file mode 100644 index 0000000..804c27d --- /dev/null +++ b/owl-bot-staging/v2/docs/servicecontrol_v2/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Servicecontrol v2 API +============================================ + +.. automodule:: google.cloud.servicecontrol_v2.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol/__init__.py b/owl-bot-staging/v2/google/cloud/servicecontrol/__init__.py new file mode 100644 index 0000000..07eacb8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol/__init__.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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.servicecontrol import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.servicecontrol_v2.services.service_controller.client import ServiceControllerClient +from google.cloud.servicecontrol_v2.services.service_controller.async_client import ServiceControllerAsyncClient + +from google.cloud.servicecontrol_v2.types.service_controller import CheckRequest +from google.cloud.servicecontrol_v2.types.service_controller import CheckResponse +from google.cloud.servicecontrol_v2.types.service_controller import ReportRequest +from google.cloud.servicecontrol_v2.types.service_controller import ReportResponse +from google.cloud.servicecontrol_v2.types.service_controller import ResourceInfo + +__all__ = ('ServiceControllerClient', + 'ServiceControllerAsyncClient', + 'CheckRequest', + 'CheckResponse', + 'ReportRequest', + 'ReportResponse', + 'ResourceInfo', +) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol/gapic_version.py b/owl-bot-staging/v2/google/cloud/servicecontrol/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol/py.typed b/owl-bot-staging/v2/google/cloud/servicecontrol/py.typed new file mode 100644 index 0000000..3971a5d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-service-control package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/__init__.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/__init__.py new file mode 100644 index 0000000..ee69a77 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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.servicecontrol_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.service_controller import ServiceControllerClient +from .services.service_controller import ServiceControllerAsyncClient + +from .types.service_controller import CheckRequest +from .types.service_controller import CheckResponse +from .types.service_controller import ReportRequest +from .types.service_controller import ReportResponse +from .types.service_controller import ResourceInfo + +__all__ = ( + 'ServiceControllerAsyncClient', +'CheckRequest', +'CheckResponse', +'ReportRequest', +'ReportResponse', +'ResourceInfo', +'ServiceControllerClient', +) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_metadata.json new file mode 100644 index 0000000..5e12db8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_metadata.json @@ -0,0 +1,58 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.servicecontrol_v2", + "protoPackage": "google.api.servicecontrol.v2", + "schema": "1.0", + "services": { + "ServiceController": { + "clients": { + "grpc": { + "libraryClient": "ServiceControllerClient", + "rpcs": { + "Check": { + "methods": [ + "check" + ] + }, + "Report": { + "methods": [ + "report" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ServiceControllerAsyncClient", + "rpcs": { + "Check": { + "methods": [ + "check" + ] + }, + "Report": { + "methods": [ + "report" + ] + } + } + }, + "rest": { + "libraryClient": "ServiceControllerClient", + "rpcs": { + "Check": { + "methods": [ + "check" + ] + }, + "Report": { + "methods": [ + "report" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_version.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/py.typed b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/py.typed new file mode 100644 index 0000000..3971a5d --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-service-control package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/__init__.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/__init__.py new file mode 100644 index 0000000..187fc9e --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 .client import ServiceControllerClient +from .async_client import ServiceControllerAsyncClient + +__all__ = ( + 'ServiceControllerClient', + 'ServiceControllerAsyncClient', +) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/async_client.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/async_client.py new file mode 100644 index 0000000..4a682e8 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/async_client.py @@ -0,0 +1,413 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.servicecontrol_v2 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.servicecontrol_v2.types import service_controller +from google.rpc import status_pb2 # type: ignore +from .transports.base import ServiceControllerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ServiceControllerGrpcAsyncIOTransport +from .client import ServiceControllerClient + + +class ServiceControllerAsyncClient: + """`Service Control API + v2 `__ + + Private Preview. This feature is only available for approved + services. + + This API provides admission control and telemetry reporting for + services that are integrated with `Service + Infrastructure `__. + """ + + _client: ServiceControllerClient + + DEFAULT_ENDPOINT = ServiceControllerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ServiceControllerClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(ServiceControllerClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ServiceControllerClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ServiceControllerClient.common_folder_path) + parse_common_folder_path = staticmethod(ServiceControllerClient.parse_common_folder_path) + common_organization_path = staticmethod(ServiceControllerClient.common_organization_path) + parse_common_organization_path = staticmethod(ServiceControllerClient.parse_common_organization_path) + common_project_path = staticmethod(ServiceControllerClient.common_project_path) + parse_common_project_path = staticmethod(ServiceControllerClient.parse_common_project_path) + common_location_path = staticmethod(ServiceControllerClient.common_location_path) + parse_common_location_path = staticmethod(ServiceControllerClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServiceControllerAsyncClient: The constructed client. + """ + return ServiceControllerClient.from_service_account_info.__func__(ServiceControllerAsyncClient, info, *args, **kwargs) # type: ignore + + @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: + ServiceControllerAsyncClient: The constructed client. + """ + return ServiceControllerClient.from_service_account_file.__func__(ServiceControllerAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ServiceControllerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ServiceControllerTransport: + """Returns the transport used by the client instance. + + Returns: + ServiceControllerTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ServiceControllerClient).get_transport_class, type(ServiceControllerClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ServiceControllerTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the service controller 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, ~.ServiceControllerTransport]): 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 = ServiceControllerClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def check(self, + request: Optional[Union[service_controller.CheckRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service_controller.CheckResponse: + r"""Private Preview. This feature is only available for approved + services. + + This method provides admission control for services that are + integrated with `Service + Infrastructure `__. + It checks whether an operation should be allowed based on the + service configuration and relevant policies. It must be called + before the operation is executed. For more information, see + `Admission + Control `__. + + NOTE: The admission control has an expected policy propagation + delay of 60s. The caller **must** not depend on the most recent + policy changes. + + NOTE: The admission control has a hard limit of 1 referenced + resources per call. If an operation refers to more than 1 + resources, the caller must call the Check method multiple times. + + This method requires the ``servicemanagement.services.check`` + permission on the specified service. For more information, see + `Service Control API Access + Control `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import servicecontrol_v2 + + async def sample_check(): + # Create a client + client = servicecontrol_v2.ServiceControllerAsyncClient() + + # Initialize request argument(s) + request = servicecontrol_v2.CheckRequest( + ) + + # Make the request + response = await client.check(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.servicecontrol_v2.types.CheckRequest, dict]]): + The request object. Request message for the Check method. + 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: + google.cloud.servicecontrol_v2.types.CheckResponse: + Response message for the Check + method. + + """ + # Create or coerce a protobuf request object. + request = service_controller.CheckRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.check, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=5.0, + ), + default_timeout=5.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(( + ("service_name", request.service_name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def report(self, + request: Optional[Union[service_controller.ReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service_controller.ReportResponse: + r"""Private Preview. This feature is only available for approved + services. + + This method provides telemetry reporting for services that are + integrated with `Service + Infrastructure `__. + It reports a list of operations that have occurred on a service. + It must be called after the operations have been executed. For + more information, see `Telemetry + Reporting `__. + + NOTE: The telemetry reporting has a hard limit of 1000 + operations and 1MB per Report call. It is recommended to have no + more than 100 operations per call. + + This method requires the ``servicemanagement.services.report`` + permission on the specified service. For more information, see + `Service Control API Access + Control `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import servicecontrol_v2 + + async def sample_report(): + # Create a client + client = servicecontrol_v2.ServiceControllerAsyncClient() + + # Initialize request argument(s) + request = servicecontrol_v2.ReportRequest( + ) + + # Make the request + response = await client.report(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.servicecontrol_v2.types.ReportRequest, dict]]): + The request object. Request message for the Report + method. + 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: + google.cloud.servicecontrol_v2.types.ReportResponse: + Response message for the Report + method. If the request contains any + invalid data, the server returns an RPC + error. + + """ + # Create or coerce a protobuf request object. + request = service_controller.ReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.report, + default_timeout=None, + 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(( + ("service_name", request.service_name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ServiceControllerAsyncClient", +) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/client.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/client.py new file mode 100644 index 0000000..3dca0b9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/client.py @@ -0,0 +1,604 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.servicecontrol_v2 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.servicecontrol_v2.types import service_controller +from google.rpc import status_pb2 # type: ignore +from .transports.base import ServiceControllerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ServiceControllerGrpcTransport +from .transports.grpc_asyncio import ServiceControllerGrpcAsyncIOTransport +from .transports.rest import ServiceControllerRestTransport + + +class ServiceControllerClientMeta(type): + """Metaclass for the ServiceController 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[ServiceControllerTransport]] + _transport_registry["grpc"] = ServiceControllerGrpcTransport + _transport_registry["grpc_asyncio"] = ServiceControllerGrpcAsyncIOTransport + _transport_registry["rest"] = ServiceControllerRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ServiceControllerTransport]: + """Returns 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 ServiceControllerClient(metaclass=ServiceControllerClientMeta): + """`Service Control API + v2 `__ + + Private Preview. This feature is only available for approved + services. + + This API provides admission control and telemetry reporting for + services that are integrated with `Service + Infrastructure `__. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + 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 = "servicecontrol.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServiceControllerClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @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: + ServiceControllerClient: 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) -> ServiceControllerTransport: + """Returns the transport used by the client instance. + + Returns: + ServiceControllerTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @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: + """Returns 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: + """Returns 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: + """Returns 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: + """Returns 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 {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ServiceControllerTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the service controller 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, ServiceControllerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ServiceControllerTransport): + # transport is a ServiceControllerTransport instance. + if credentials or client_options.credentials_file or api_key_value: + 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: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + 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, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def check(self, + request: Optional[Union[service_controller.CheckRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service_controller.CheckResponse: + r"""Private Preview. This feature is only available for approved + services. + + This method provides admission control for services that are + integrated with `Service + Infrastructure `__. + It checks whether an operation should be allowed based on the + service configuration and relevant policies. It must be called + before the operation is executed. For more information, see + `Admission + Control `__. + + NOTE: The admission control has an expected policy propagation + delay of 60s. The caller **must** not depend on the most recent + policy changes. + + NOTE: The admission control has a hard limit of 1 referenced + resources per call. If an operation refers to more than 1 + resources, the caller must call the Check method multiple times. + + This method requires the ``servicemanagement.services.check`` + permission on the specified service. For more information, see + `Service Control API Access + Control `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import servicecontrol_v2 + + def sample_check(): + # Create a client + client = servicecontrol_v2.ServiceControllerClient() + + # Initialize request argument(s) + request = servicecontrol_v2.CheckRequest( + ) + + # Make the request + response = client.check(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.servicecontrol_v2.types.CheckRequest, dict]): + The request object. Request message for the Check method. + 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: + google.cloud.servicecontrol_v2.types.CheckResponse: + Response message for the Check + method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a service_controller.CheckRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service_controller.CheckRequest): + request = service_controller.CheckRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.check] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service_name", request.service_name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def report(self, + request: Optional[Union[service_controller.ReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service_controller.ReportResponse: + r"""Private Preview. This feature is only available for approved + services. + + This method provides telemetry reporting for services that are + integrated with `Service + Infrastructure `__. + It reports a list of operations that have occurred on a service. + It must be called after the operations have been executed. For + more information, see `Telemetry + Reporting `__. + + NOTE: The telemetry reporting has a hard limit of 1000 + operations and 1MB per Report call. It is recommended to have no + more than 100 operations per call. + + This method requires the ``servicemanagement.services.report`` + permission on the specified service. For more information, see + `Service Control API Access + Control `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import servicecontrol_v2 + + def sample_report(): + # Create a client + client = servicecontrol_v2.ServiceControllerClient() + + # Initialize request argument(s) + request = servicecontrol_v2.ReportRequest( + ) + + # Make the request + response = client.report(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.servicecontrol_v2.types.ReportRequest, dict]): + The request object. Request message for the Report + method. + 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: + google.cloud.servicecontrol_v2.types.ReportResponse: + Response message for the Report + method. If the request contains any + invalid data, the server returns an RPC + error. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a service_controller.ReportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service_controller.ReportRequest): + request = service_controller.ReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.report] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("service_name", request.service_name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ServiceControllerClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ServiceControllerClient", +) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/__init__.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/__init__.py new file mode 100644 index 0000000..ad7b8b5 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 ServiceControllerTransport +from .grpc import ServiceControllerGrpcTransport +from .grpc_asyncio import ServiceControllerGrpcAsyncIOTransport +from .rest import ServiceControllerRestTransport +from .rest import ServiceControllerRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ServiceControllerTransport]] +_transport_registry['grpc'] = ServiceControllerGrpcTransport +_transport_registry['grpc_asyncio'] = ServiceControllerGrpcAsyncIOTransport +_transport_registry['rest'] = ServiceControllerRestTransport + +__all__ = ( + 'ServiceControllerTransport', + 'ServiceControllerGrpcTransport', + 'ServiceControllerGrpcAsyncIOTransport', + 'ServiceControllerRestTransport', + 'ServiceControllerRestInterceptor', +) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/base.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/base.py new file mode 100644 index 0000000..55cd0e9 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/base.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.servicecontrol_v2 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicecontrol_v2.types import service_controller + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ServiceControllerTransport(abc.ABC): + """Abstract transport class for ServiceController.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', + ) + + DEFAULT_HOST: str = 'servicecontrol.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **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. + scopes (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. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.check: gapic_v1.method.wrap_method( + self.check, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=5.0, + ), + default_timeout=5.0, + client_info=client_info, + ), + self.report: gapic_v1.method.wrap_method( + self.report, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def check(self) -> Callable[ + [service_controller.CheckRequest], + Union[ + service_controller.CheckResponse, + Awaitable[service_controller.CheckResponse] + ]]: + raise NotImplementedError() + + @property + def report(self) -> Callable[ + [service_controller.ReportRequest], + Union[ + service_controller.ReportResponse, + Awaitable[service_controller.ReportResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ServiceControllerTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc.py new file mode 100644 index 0000000..779f374 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc.py @@ -0,0 +1,339 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.servicecontrol_v2.types import service_controller +from .base import ServiceControllerTransport, DEFAULT_CLIENT_INFO + + +class ServiceControllerGrpcTransport(ServiceControllerTransport): + """gRPC backend transport for ServiceController. + + `Service Control API + v2 `__ + + Private Preview. This feature is only available for approved + services. + + This API provides admission control and telemetry reporting for + services that are integrated with `Service + Infrastructure `__. + + 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 = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> 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 application 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 the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + 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._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + 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. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def check(self) -> Callable[ + [service_controller.CheckRequest], + service_controller.CheckResponse]: + r"""Return a callable for the check method over gRPC. + + Private Preview. This feature is only available for approved + services. + + This method provides admission control for services that are + integrated with `Service + Infrastructure `__. + It checks whether an operation should be allowed based on the + service configuration and relevant policies. It must be called + before the operation is executed. For more information, see + `Admission + Control `__. + + NOTE: The admission control has an expected policy propagation + delay of 60s. The caller **must** not depend on the most recent + policy changes. + + NOTE: The admission control has a hard limit of 1 referenced + resources per call. If an operation refers to more than 1 + resources, the caller must call the Check method multiple times. + + This method requires the ``servicemanagement.services.check`` + permission on the specified service. For more information, see + `Service Control API Access + Control `__. + + Returns: + Callable[[~.CheckRequest], + ~.CheckResponse]: + 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 'check' not in self._stubs: + self._stubs['check'] = self.grpc_channel.unary_unary( + '/google.api.servicecontrol.v2.ServiceController/Check', + request_serializer=service_controller.CheckRequest.serialize, + response_deserializer=service_controller.CheckResponse.deserialize, + ) + return self._stubs['check'] + + @property + def report(self) -> Callable[ + [service_controller.ReportRequest], + service_controller.ReportResponse]: + r"""Return a callable for the report method over gRPC. + + Private Preview. This feature is only available for approved + services. + + This method provides telemetry reporting for services that are + integrated with `Service + Infrastructure `__. + It reports a list of operations that have occurred on a service. + It must be called after the operations have been executed. For + more information, see `Telemetry + Reporting `__. + + NOTE: The telemetry reporting has a hard limit of 1000 + operations and 1MB per Report call. It is recommended to have no + more than 100 operations per call. + + This method requires the ``servicemanagement.services.report`` + permission on the specified service. For more information, see + `Service Control API Access + Control `__. + + Returns: + Callable[[~.ReportRequest], + ~.ReportResponse]: + 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 'report' not in self._stubs: + self._stubs['report'] = self.grpc_channel.unary_unary( + '/google.api.servicecontrol.v2.ServiceController/Report', + request_serializer=service_controller.ReportRequest.serialize, + response_deserializer=service_controller.ReportResponse.deserialize, + ) + return self._stubs['report'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ServiceControllerGrpcTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc_asyncio.py new file mode 100644 index 0000000..8f7a6eb --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc_asyncio.py @@ -0,0 +1,338 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_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.servicecontrol_v2.types import service_controller +from .base import ServiceControllerTransport, DEFAULT_CLIENT_INFO +from .grpc import ServiceControllerGrpcTransport + + +class ServiceControllerGrpcAsyncIOTransport(ServiceControllerTransport): + """gRPC AsyncIO backend transport for ServiceController. + + `Service Control API + v2 `__ + + Private Preview. This feature is only available for approved + services. + + This API provides admission control and telemetry reporting for + services that are integrated with `Service + Infrastructure `__. + + 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 = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (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. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> 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 application 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 the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + 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._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @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 check(self) -> Callable[ + [service_controller.CheckRequest], + Awaitable[service_controller.CheckResponse]]: + r"""Return a callable for the check method over gRPC. + + Private Preview. This feature is only available for approved + services. + + This method provides admission control for services that are + integrated with `Service + Infrastructure `__. + It checks whether an operation should be allowed based on the + service configuration and relevant policies. It must be called + before the operation is executed. For more information, see + `Admission + Control `__. + + NOTE: The admission control has an expected policy propagation + delay of 60s. The caller **must** not depend on the most recent + policy changes. + + NOTE: The admission control has a hard limit of 1 referenced + resources per call. If an operation refers to more than 1 + resources, the caller must call the Check method multiple times. + + This method requires the ``servicemanagement.services.check`` + permission on the specified service. For more information, see + `Service Control API Access + Control `__. + + Returns: + Callable[[~.CheckRequest], + Awaitable[~.CheckResponse]]: + 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 'check' not in self._stubs: + self._stubs['check'] = self.grpc_channel.unary_unary( + '/google.api.servicecontrol.v2.ServiceController/Check', + request_serializer=service_controller.CheckRequest.serialize, + response_deserializer=service_controller.CheckResponse.deserialize, + ) + return self._stubs['check'] + + @property + def report(self) -> Callable[ + [service_controller.ReportRequest], + Awaitable[service_controller.ReportResponse]]: + r"""Return a callable for the report method over gRPC. + + Private Preview. This feature is only available for approved + services. + + This method provides telemetry reporting for services that are + integrated with `Service + Infrastructure `__. + It reports a list of operations that have occurred on a service. + It must be called after the operations have been executed. For + more information, see `Telemetry + Reporting `__. + + NOTE: The telemetry reporting has a hard limit of 1000 + operations and 1MB per Report call. It is recommended to have no + more than 100 operations per call. + + This method requires the ``servicemanagement.services.report`` + permission on the specified service. For more information, see + `Service Control API Access + Control `__. + + Returns: + Callable[[~.ReportRequest], + Awaitable[~.ReportResponse]]: + 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 'report' not in self._stubs: + self._stubs['report'] = self.grpc_channel.unary_unary( + '/google.api.servicecontrol.v2.ServiceController/Report', + request_serializer=service_controller.ReportRequest.serialize, + response_deserializer=service_controller.ReportResponse.deserialize, + ) + return self._stubs['report'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ServiceControllerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/rest.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/rest.py new file mode 100644 index 0000000..ce49c01 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/rest.py @@ -0,0 +1,415 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.servicecontrol_v2.types import service_controller + +from .base import ServiceControllerTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ServiceControllerRestInterceptor: + """Interceptor for ServiceController. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the ServiceControllerRestTransport. + + .. code-block:: python + class MyCustomServiceControllerInterceptor(ServiceControllerRestInterceptor): + def pre_check(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_check(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_report(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_report(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ServiceControllerRestTransport(interceptor=MyCustomServiceControllerInterceptor()) + client = ServiceControllerClient(transport=transport) + + + """ + def pre_check(self, request: service_controller.CheckRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_controller.CheckRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for check + + Override in a subclass to manipulate the request or metadata + before they are sent to the ServiceController server. + """ + return request, metadata + + def post_check(self, response: service_controller.CheckResponse) -> service_controller.CheckResponse: + """Post-rpc interceptor for check + + Override in a subclass to manipulate the response + after it is returned by the ServiceController server but before + it is returned to user code. + """ + return response + def pre_report(self, request: service_controller.ReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_controller.ReportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for report + + Override in a subclass to manipulate the request or metadata + before they are sent to the ServiceController server. + """ + return request, metadata + + def post_report(self, response: service_controller.ReportResponse) -> service_controller.ReportResponse: + """Post-rpc interceptor for report + + Override in a subclass to manipulate the response + after it is returned by the ServiceController server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ServiceControllerRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ServiceControllerRestInterceptor + + +class ServiceControllerRestTransport(ServiceControllerTransport): + """REST backend transport for ServiceController. + + `Service Control API + v2 `__ + + Private Preview. This feature is only available for approved + services. + + This API provides admission control and telemetry reporting for + services that are integrated with `Service + Infrastructure `__. + + 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'servicecontrol.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[ServiceControllerRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> 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 ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ServiceControllerRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Check(ServiceControllerRestStub): + def __hash__(self): + return hash("Check") + + def __call__(self, + request: service_controller.CheckRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service_controller.CheckResponse: + r"""Call the check method over HTTP. + + Args: + request (~.service_controller.CheckRequest): + The request object. Request message for the Check method. + 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: + ~.service_controller.CheckResponse: + Response message for the Check + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/services/{service_name}:check', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_check(request, metadata) + pb_request = service_controller.CheckRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service_controller.CheckResponse() + pb_resp = service_controller.CheckResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_check(resp) + return resp + + class _Report(ServiceControllerRestStub): + def __hash__(self): + return hash("Report") + + def __call__(self, + request: service_controller.ReportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service_controller.ReportResponse: + r"""Call the report method over HTTP. + + Args: + request (~.service_controller.ReportRequest): + The request object. Request message for the Report + method. + 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: + ~.service_controller.ReportResponse: + Response message for the Report + method. If the request contains any + invalid data, the server returns an RPC + error. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/services/{service_name}:report', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_report(request, metadata) + pb_request = service_controller.ReportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service_controller.ReportResponse() + pb_resp = service_controller.ReportResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_report(resp) + return resp + + @property + def check(self) -> Callable[ + [service_controller.CheckRequest], + service_controller.CheckResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Check(self._session, self._host, self._interceptor) # type: ignore + + @property + def report(self) -> Callable[ + [service_controller.ReportRequest], + service_controller.ReportResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Report(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ServiceControllerRestTransport', +) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/__init__.py new file mode 100644 index 0000000..a81eb58 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 .service_controller import ( + CheckRequest, + CheckResponse, + ReportRequest, + ReportResponse, + ResourceInfo, +) + +__all__ = ( + 'CheckRequest', + 'CheckResponse', + 'ReportRequest', + 'ReportResponse', + 'ResourceInfo', +) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/service_controller.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/service_controller.py new file mode 100644 index 0000000..df64d66 --- /dev/null +++ b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/service_controller.py @@ -0,0 +1,216 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.rpc import status_pb2 # type: ignore +from google.rpc.context import attribute_context_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.api.servicecontrol.v2', + manifest={ + 'CheckRequest', + 'ResourceInfo', + 'CheckResponse', + 'ReportRequest', + 'ReportResponse', + }, +) + + +class CheckRequest(proto.Message): + r"""Request message for the Check method. + + Attributes: + service_name (str): + The service name as specified in its service configuration. + For example, ``"pubsub.googleapis.com"``. + + See + `google.api.Service `__ + for the definition of a service name. + service_config_id (str): + Specifies the version of the service + configuration that should be used to process the + request. Must not be empty. Set this field to + 'latest' to specify using the latest + configuration. + attributes (google.rpc.context.attribute_context_pb2.AttributeContext): + Describes attributes about the operation + being executed by the service. + resources (MutableSequence[google.cloud.servicecontrol_v2.types.ResourceInfo]): + Describes the resources and the policies + applied to each resource. + flags (str): + Optional. Contains a comma-separated list of + flags. + """ + + service_name: str = proto.Field( + proto.STRING, + number=1, + ) + service_config_id: str = proto.Field( + proto.STRING, + number=2, + ) + attributes: attribute_context_pb2.AttributeContext = proto.Field( + proto.MESSAGE, + number=3, + message=attribute_context_pb2.AttributeContext, + ) + resources: MutableSequence['ResourceInfo'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='ResourceInfo', + ) + flags: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ResourceInfo(proto.Message): + r"""Describes a resource referenced in the request. + + Attributes: + name (str): + The name of the resource referenced in the + request. + type_ (str): + The resource type in the format of + "{service}/{kind}". + permission (str): + The resource permission needed for this + request. The format must be + "{service}/{plural}.{verb}". + container (str): + Optional. The identifier of the container of this resource. + For Google Cloud APIs, the resource container must be one of + the following formats: - + ``projects/`` - + ``folders/`` - + ``organizations/`` For the policy + enforcement on the container level (VPCSC and Location + Policy check), this field takes precedence on the container + extracted from name when presents. + location (str): + Optional. The location of the resource. The + value must be a valid zone, region or + multiregion. For example: "europe-west4" or + "northamerica-northeast1-a". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + permission: str = proto.Field( + proto.STRING, + number=3, + ) + container: str = proto.Field( + proto.STRING, + number=4, + ) + location: str = proto.Field( + proto.STRING, + number=5, + ) + + +class CheckResponse(proto.Message): + r"""Response message for the Check method. + + Attributes: + status (google.rpc.status_pb2.Status): + Operation is allowed when this field is not set. Any + non-'OK' status indicates a denial; + [google.rpc.Status.details][google.rpc.Status.details] would + contain additional details about the denial. + headers (MutableMapping[str, str]): + Returns a set of request contexts generated from the + ``CheckRequest``. + """ + + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + headers: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + +class ReportRequest(proto.Message): + r"""Request message for the Report method. + + Attributes: + service_name (str): + The service name as specified in its service configuration. + For example, ``"pubsub.googleapis.com"``. + + See + `google.api.Service `__ + for the definition of a service name. + service_config_id (str): + Specifies the version of the service + configuration that should be used to process the + request. Must not be empty. Set this field to + 'latest' to specify using the latest + configuration. + operations (MutableSequence[google.rpc.context.attribute_context_pb2.AttributeContext]): + Describes the list of operations to be + reported. Each operation is represented as an + AttributeContext, and contains all attributes + around an API access. + """ + + service_name: str = proto.Field( + proto.STRING, + number=1, + ) + service_config_id: str = proto.Field( + proto.STRING, + number=2, + ) + operations: MutableSequence[attribute_context_pb2.AttributeContext] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=attribute_context_pb2.AttributeContext, + ) + + +class ReportResponse(proto.Message): + r"""Response message for the Report method. + If the request contains any invalid data, the server returns an + RPC error. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini new file mode 100644 index 0000000..574c5ae --- /dev/null +++ b/owl-bot-staging/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py new file mode 100644 index 0000000..f213da3 --- /dev/null +++ b/owl-bot-staging/v2/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/servicecontrol_v2/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_async.py b/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_async.py new file mode 100644 index 0000000..e735fb7 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 code. DO NOT EDIT! +# +# Snippet for Check +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-control + + +# [START servicecontrol_v2_generated_ServiceController_Check_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import servicecontrol_v2 + + +async def sample_check(): + # Create a client + client = servicecontrol_v2.ServiceControllerAsyncClient() + + # Initialize request argument(s) + request = servicecontrol_v2.CheckRequest( + ) + + # Make the request + response = await client.check(request=request) + + # Handle the response + print(response) + +# [END servicecontrol_v2_generated_ServiceController_Check_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_sync.py b/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_sync.py new file mode 100644 index 0000000..99e85b9 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 code. DO NOT EDIT! +# +# Snippet for Check +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-control + + +# [START servicecontrol_v2_generated_ServiceController_Check_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import servicecontrol_v2 + + +def sample_check(): + # Create a client + client = servicecontrol_v2.ServiceControllerClient() + + # Initialize request argument(s) + request = servicecontrol_v2.CheckRequest( + ) + + # Make the request + response = client.check(request=request) + + # Handle the response + print(response) + +# [END servicecontrol_v2_generated_ServiceController_Check_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_async.py b/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_async.py new file mode 100644 index 0000000..78ee2e1 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 code. DO NOT EDIT! +# +# Snippet for Report +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-control + + +# [START servicecontrol_v2_generated_ServiceController_Report_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import servicecontrol_v2 + + +async def sample_report(): + # Create a client + client = servicecontrol_v2.ServiceControllerAsyncClient() + + # Initialize request argument(s) + request = servicecontrol_v2.ReportRequest( + ) + + # Make the request + response = await client.report(request=request) + + # Handle the response + print(response) + +# [END servicecontrol_v2_generated_ServiceController_Report_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_sync.py b/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_sync.py new file mode 100644 index 0000000..6065f65 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 code. DO NOT EDIT! +# +# Snippet for Report +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-control + + +# [START servicecontrol_v2_generated_ServiceController_Report_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import servicecontrol_v2 + + +def sample_report(): + # Create a client + client = servicecontrol_v2.ServiceControllerClient() + + # Initialize request argument(s) + request = servicecontrol_v2.ReportRequest( + ) + + # Make the request + response = client.report(request=request) + + # Handle the response + print(response) + +# [END servicecontrol_v2_generated_ServiceController_Report_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json new file mode 100644 index 0000000..2b78179 --- /dev/null +++ b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json @@ -0,0 +1,321 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.api.servicecontrol.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-cloud-service-control", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.servicecontrol_v2.ServiceControllerAsyncClient", + "shortName": "ServiceControllerAsyncClient" + }, + "fullName": "google.cloud.servicecontrol_v2.ServiceControllerAsyncClient.check", + "method": { + "fullName": "google.api.servicecontrol.v2.ServiceController.Check", + "service": { + "fullName": "google.api.servicecontrol.v2.ServiceController", + "shortName": "ServiceController" + }, + "shortName": "Check" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.servicecontrol_v2.types.CheckRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.servicecontrol_v2.types.CheckResponse", + "shortName": "check" + }, + "description": "Sample for Check", + "file": "servicecontrol_v2_generated_service_controller_check_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "servicecontrol_v2_generated_ServiceController_Check_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "servicecontrol_v2_generated_service_controller_check_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.servicecontrol_v2.ServiceControllerClient", + "shortName": "ServiceControllerClient" + }, + "fullName": "google.cloud.servicecontrol_v2.ServiceControllerClient.check", + "method": { + "fullName": "google.api.servicecontrol.v2.ServiceController.Check", + "service": { + "fullName": "google.api.servicecontrol.v2.ServiceController", + "shortName": "ServiceController" + }, + "shortName": "Check" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.servicecontrol_v2.types.CheckRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.servicecontrol_v2.types.CheckResponse", + "shortName": "check" + }, + "description": "Sample for Check", + "file": "servicecontrol_v2_generated_service_controller_check_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "servicecontrol_v2_generated_ServiceController_Check_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "servicecontrol_v2_generated_service_controller_check_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.servicecontrol_v2.ServiceControllerAsyncClient", + "shortName": "ServiceControllerAsyncClient" + }, + "fullName": "google.cloud.servicecontrol_v2.ServiceControllerAsyncClient.report", + "method": { + "fullName": "google.api.servicecontrol.v2.ServiceController.Report", + "service": { + "fullName": "google.api.servicecontrol.v2.ServiceController", + "shortName": "ServiceController" + }, + "shortName": "Report" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.servicecontrol_v2.types.ReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.servicecontrol_v2.types.ReportResponse", + "shortName": "report" + }, + "description": "Sample for Report", + "file": "servicecontrol_v2_generated_service_controller_report_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "servicecontrol_v2_generated_ServiceController_Report_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "servicecontrol_v2_generated_service_controller_report_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.servicecontrol_v2.ServiceControllerClient", + "shortName": "ServiceControllerClient" + }, + "fullName": "google.cloud.servicecontrol_v2.ServiceControllerClient.report", + "method": { + "fullName": "google.api.servicecontrol.v2.ServiceController.Report", + "service": { + "fullName": "google.api.servicecontrol.v2.ServiceController", + "shortName": "ServiceController" + }, + "shortName": "Report" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.servicecontrol_v2.types.ReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.servicecontrol_v2.types.ReportResponse", + "shortName": "report" + }, + "description": "Sample for Report", + "file": "servicecontrol_v2_generated_service_controller_report_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "servicecontrol_v2_generated_ServiceController_Report_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "servicecontrol_v2_generated_service_controller_report_sync.py" + } + ] +} diff --git a/owl-bot-staging/v2/scripts/fixup_servicecontrol_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_servicecontrol_v2_keywords.py new file mode 100644 index 0000000..f15a780 --- /dev/null +++ b/owl-bot-staging/v2/scripts/fixup_servicecontrol_v2_keywords.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 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 servicecontrolCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'check': ('service_name', 'service_config_id', 'attributes', 'resources', 'flags', ), + 'report': ('service_name', 'service_config_id', 'operations', ), + } + + 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: a.keyword.value not 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=servicecontrolCallTransformer(), +): + """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 servicecontrol 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/owl-bot-staging/v2/setup.py b/owl-bot-staging/v2/setup.py new file mode 100644 index 0000000..8108ffe --- /dev/null +++ b/owl-bot-staging/v2/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-service-control' + + +description = "Google Cloud Service Control API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/servicecontrol/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-service-control" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v2/testing/constraints-3.10.txt b/owl-bot-staging/v2/testing/constraints-3.10.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v2/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v2/testing/constraints-3.11.txt b/owl-bot-staging/v2/testing/constraints-3.11.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v2/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v2/testing/constraints-3.12.txt b/owl-bot-staging/v2/testing/constraints-3.12.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v2/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v2/testing/constraints-3.7.txt b/owl-bot-staging/v2/testing/constraints-3.7.txt new file mode 100644 index 0000000..6c44adf --- /dev/null +++ b/owl-bot-staging/v2/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/v2/testing/constraints-3.8.txt b/owl-bot-staging/v2/testing/constraints-3.8.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v2/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v2/testing/constraints-3.9.txt b/owl-bot-staging/v2/testing/constraints-3.9.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v2/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 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/owl-bot-staging/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 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/owl-bot-staging/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 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/owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 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/owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/test_service_controller.py b/owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/test_service_controller.py new file mode 100644 index 0000000..e8436dc --- /dev/null +++ b/owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/test_service_controller.py @@ -0,0 +1,1704 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_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.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.servicecontrol_v2.services.service_controller import ServiceControllerAsyncClient +from google.cloud.servicecontrol_v2.services.service_controller import ServiceControllerClient +from google.cloud.servicecontrol_v2.services.service_controller import transports +from google.cloud.servicecontrol_v2.types import service_controller +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.rpc.context import attribute_context_pb2 # type: ignore +import google.auth + + +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 ServiceControllerClient._get_default_mtls_endpoint(None) is None + assert ServiceControllerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ServiceControllerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ServiceControllerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ServiceControllerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ServiceControllerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ServiceControllerClient, "grpc"), + (ServiceControllerAsyncClient, "grpc_asyncio"), + (ServiceControllerClient, "rest"), +]) +def test_service_controller_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'servicecontrol.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://servicecontrol.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ServiceControllerGrpcTransport, "grpc"), + (transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ServiceControllerRestTransport, "rest"), +]) +def test_service_controller_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ServiceControllerClient, "grpc"), + (ServiceControllerAsyncClient, "grpc_asyncio"), + (ServiceControllerClient, "rest"), +]) +def test_service_controller_client_from_service_account_file(client_class, transport_name): + creds = ga_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", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'servicecontrol.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://servicecontrol.googleapis.com' + ) + + +def test_service_controller_client_get_transport_class(): + transport = ServiceControllerClient.get_transport_class() + available_transports = [ + transports.ServiceControllerGrpcTransport, + transports.ServiceControllerRestTransport, + ] + assert transport in available_transports + + transport = ServiceControllerClient.get_transport_class("grpc") + assert transport == transports.ServiceControllerGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc"), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio"), + (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest"), +]) +@mock.patch.object(ServiceControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerClient)) +@mock.patch.object(ServiceControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerAsyncClient)) +def test_service_controller_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(ServiceControllerClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_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(ServiceControllerClient, '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(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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(transport=transport_name) + + # 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(transport=transport_name) + + # 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", "true"), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", "false"), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest", "true"), + (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest", "false"), +]) +@mock.patch.object(ServiceControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerClient)) +@mock.patch.object(ServiceControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_service_controller_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: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # 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.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ServiceControllerClient, ServiceControllerAsyncClient +]) +@mock.patch.object(ServiceControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerClient)) +@mock.patch.object(ServiceControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerAsyncClient)) +def test_service_controller_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc"), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio"), + (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest"), +]) +def test_service_controller_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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", grpc_helpers), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest", None), +]) +def test_service_controller_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_service_controller_client_client_options_from_dict(): + with mock.patch('google.cloud.servicecontrol_v2.services.service_controller.transports.ServiceControllerGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ServiceControllerClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", grpc_helpers), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_service_controller_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "servicecontrol.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', +), + scopes=None, + default_host="servicecontrol.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + service_controller.CheckRequest, + dict, +]) +def test_check(request_type, transport: str = 'grpc'): + client = ServiceControllerClient( + credentials=ga_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.check), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service_controller.CheckResponse( + ) + response = client.check(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service_controller.CheckRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service_controller.CheckResponse) + + +def test_check_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check), + '__call__') as call: + client.check() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service_controller.CheckRequest() + +@pytest.mark.asyncio +async def test_check_async(transport: str = 'grpc_asyncio', request_type=service_controller.CheckRequest): + client = ServiceControllerAsyncClient( + credentials=ga_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.check), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_controller.CheckResponse( + )) + response = await client.check(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service_controller.CheckRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service_controller.CheckResponse) + + +@pytest.mark.asyncio +async def test_check_async_from_dict(): + await test_check_async(request_type=dict) + + +def test_check_field_headers(): + client = ServiceControllerClient( + credentials=ga_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 = service_controller.CheckRequest() + + request.service_name = 'service_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check), + '__call__') as call: + call.return_value = service_controller.CheckResponse() + client.check(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', + 'service_name=service_name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_check_field_headers_async(): + client = ServiceControllerAsyncClient( + credentials=ga_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 = service_controller.CheckRequest() + + request.service_name = 'service_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_controller.CheckResponse()) + await client.check(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', + 'service_name=service_name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + service_controller.ReportRequest, + dict, +]) +def test_report(request_type, transport: str = 'grpc'): + client = ServiceControllerClient( + credentials=ga_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.report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service_controller.ReportResponse( + ) + response = client.report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service_controller.ReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service_controller.ReportResponse) + + +def test_report_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.report), + '__call__') as call: + client.report() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service_controller.ReportRequest() + +@pytest.mark.asyncio +async def test_report_async(transport: str = 'grpc_asyncio', request_type=service_controller.ReportRequest): + client = ServiceControllerAsyncClient( + credentials=ga_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.report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_controller.ReportResponse( + )) + response = await client.report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service_controller.ReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service_controller.ReportResponse) + + +@pytest.mark.asyncio +async def test_report_async_from_dict(): + await test_report_async(request_type=dict) + + +def test_report_field_headers(): + client = ServiceControllerClient( + credentials=ga_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 = service_controller.ReportRequest() + + request.service_name = 'service_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.report), + '__call__') as call: + call.return_value = service_controller.ReportResponse() + client.report(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', + 'service_name=service_name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_report_field_headers_async(): + client = ServiceControllerAsyncClient( + credentials=ga_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 = service_controller.ReportRequest() + + request.service_name = 'service_name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.report), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_controller.ReportResponse()) + await client.report(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', + 'service_name=service_name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + service_controller.CheckRequest, + dict, +]) +def test_check_rest(request_type): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service_name': 'sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service_controller.CheckResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service_controller.CheckResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.check(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service_controller.CheckResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_check_rest_interceptors(null_interceptor): + transport = transports.ServiceControllerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServiceControllerRestInterceptor(), + ) + client = ServiceControllerClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ServiceControllerRestInterceptor, "post_check") as post, \ + mock.patch.object(transports.ServiceControllerRestInterceptor, "pre_check") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service_controller.CheckRequest.pb(service_controller.CheckRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service_controller.CheckResponse.to_json(service_controller.CheckResponse()) + + request = service_controller.CheckRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service_controller.CheckResponse() + + client.check(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_check_rest_bad_request(transport: str = 'rest', request_type=service_controller.CheckRequest): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service_name': 'sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.check(request) + + +def test_check_rest_error(): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service_controller.ReportRequest, + dict, +]) +def test_report_rest(request_type): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'service_name': 'sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service_controller.ReportResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service_controller.ReportResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.report(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service_controller.ReportResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_report_rest_interceptors(null_interceptor): + transport = transports.ServiceControllerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServiceControllerRestInterceptor(), + ) + client = ServiceControllerClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ServiceControllerRestInterceptor, "post_report") as post, \ + mock.patch.object(transports.ServiceControllerRestInterceptor, "pre_report") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service_controller.ReportRequest.pb(service_controller.ReportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service_controller.ReportResponse.to_json(service_controller.ReportResponse()) + + request = service_controller.ReportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service_controller.ReportResponse() + + client.report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_report_rest_bad_request(transport: str = 'rest', request_type=service_controller.ReportRequest): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'service_name': 'sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.report(request) + + +def test_report_rest_error(): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServiceControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServiceControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServiceControllerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServiceControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServiceControllerClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServiceControllerClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServiceControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServiceControllerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServiceControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServiceControllerClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServiceControllerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServiceControllerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ServiceControllerGrpcTransport, + transports.ServiceControllerGrpcAsyncIOTransport, + transports.ServiceControllerRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = ServiceControllerClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ServiceControllerGrpcTransport, + ) + +def test_service_controller_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ServiceControllerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_service_controller_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.servicecontrol_v2.services.service_controller.transports.ServiceControllerTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ServiceControllerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'check', + 'report', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_service_controller_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.servicecontrol_v2.services.service_controller.transports.ServiceControllerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServiceControllerTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', +), + quota_project_id="octopus", + ) + + +def test_service_controller_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.servicecontrol_v2.services.service_controller.transports.ServiceControllerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServiceControllerTransport() + adc.assert_called_once() + + +def test_service_controller_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ServiceControllerClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServiceControllerGrpcTransport, + transports.ServiceControllerGrpcAsyncIOTransport, + ], +) +def test_service_controller_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/servicecontrol',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServiceControllerGrpcTransport, + transports.ServiceControllerGrpcAsyncIOTransport, + transports.ServiceControllerRestTransport, + ], +) +def test_service_controller_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ServiceControllerGrpcTransport, grpc_helpers), + (transports.ServiceControllerGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_service_controller_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "servicecontrol.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/servicecontrol', +), + scopes=["1", "2"], + default_host="servicecontrol.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ServiceControllerGrpcTransport, transports.ServiceControllerGrpcAsyncIOTransport]) +def test_service_controller_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_service_controller_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ServiceControllerRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_service_controller_host_no_port(transport_name): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicecontrol.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'servicecontrol.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://servicecontrol.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_service_controller_host_with_port(transport_name): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='servicecontrol.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'servicecontrol.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://servicecontrol.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_service_controller_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ServiceControllerClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ServiceControllerClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.check._session + session2 = client2.transport.check._session + assert session1 != session2 + session1 = client1.transport.report._session + session2 = client2.transport.report._session + assert session1 != session2 +def test_service_controller_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServiceControllerGrpcTransport( + 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_service_controller_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServiceControllerGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ServiceControllerGrpcTransport, transports.ServiceControllerGrpcAsyncIOTransport]) +def test_service_controller_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") 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 = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.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=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ServiceControllerGrpcTransport, transports.ServiceControllerGrpcAsyncIOTransport]) +def test_service_controller_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") 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=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ServiceControllerClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ServiceControllerClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ServiceControllerClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = ServiceControllerClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ServiceControllerClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ServiceControllerClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ServiceControllerClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ServiceControllerClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ServiceControllerClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = ServiceControllerClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ServiceControllerClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ServiceControllerClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ServiceControllerClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ServiceControllerClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ServiceControllerClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.ServiceControllerTransport, '_prep_wrapped_messages') as prep: + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ServiceControllerTransport, '_prep_wrapped_messages') as prep: + transport_class = ServiceControllerClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ServiceControllerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = ServiceControllerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (ServiceControllerClient, transports.ServiceControllerGrpcTransport), + (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + 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=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From e34291ed7e14315b072f67d27e5707b457678c90 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 22 Mar 2023 20:00:06 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../services/quota_controller/async_client.py | 4 +- .../services/quota_controller/client.py | 4 +- .../quota_controller/transports/rest.py | 1 - .../service_controller/async_client.py | 3 +- .../services/service_controller/client.py | 3 +- .../service_controller/transports/rest.py | 1 - .../service_controller/async_client.py | 3 +- .../services/service_controller/client.py | 3 +- .../service_controller/transports/rest.py | 1 - owl-bot-staging/v1/.coveragerc | 13 - owl-bot-staging/v1/.flake8 | 33 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 376 ---- owl-bot-staging/v1/docs/index.rst | 7 - .../servicecontrol_v1/quota_controller.rst | 6 - .../servicecontrol_v1/service_controller.rst | 6 - .../v1/docs/servicecontrol_v1/services.rst | 7 - .../v1/docs/servicecontrol_v1/types.rst | 6 - .../google/cloud/servicecontrol/__init__.py | 65 - .../cloud/servicecontrol/gapic_version.py | 16 - .../v1/google/cloud/servicecontrol/py.typed | 2 - .../cloud/servicecontrol_v1/__init__.py | 66 - .../servicecontrol_v1/gapic_metadata.json | 92 - .../cloud/servicecontrol_v1/gapic_version.py | 16 - .../google/cloud/servicecontrol_v1/py.typed | 2 - .../servicecontrol_v1/services/__init__.py | 15 - .../services/quota_controller/__init__.py | 22 - .../services/quota_controller/async_client.py | 291 --- .../services/quota_controller/client.py | 487 ----- .../quota_controller/transports/__init__.py | 38 - .../quota_controller/transports/base.py | 149 -- .../quota_controller/transports/grpc.py | 278 --- .../transports/grpc_asyncio.py | 277 --- .../quota_controller/transports/rest.py | 295 --- .../services/service_controller/__init__.py | 22 - .../service_controller/async_client.py | 400 ---- .../services/service_controller/client.py | 591 ------ .../service_controller/transports/__init__.py | 38 - .../service_controller/transports/base.py | 169 -- .../service_controller/transports/grpc.py | 328 ---- .../transports/grpc_asyncio.py | 327 ---- .../service_controller/transports/rest.py | 408 ---- .../cloud/servicecontrol_v1/types/__init__.py | 68 - .../servicecontrol_v1/types/check_error.py | 164 -- .../servicecontrol_v1/types/distribution.py | 241 --- .../servicecontrol_v1/types/http_request.py | 156 -- .../servicecontrol_v1/types/log_entry.py | 238 --- .../servicecontrol_v1/types/metric_value.py | 153 -- .../servicecontrol_v1/types/operation.py | 186 -- .../types/quota_controller.py | 328 ---- .../types/service_controller.py | 322 --- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 184 -- ...d_quota_controller_allocate_quota_async.py | 51 - ...ed_quota_controller_allocate_quota_sync.py | 51 - ...enerated_service_controller_check_async.py | 51 - ...generated_service_controller_check_sync.py | 51 - ...nerated_service_controller_report_async.py | 51 - ...enerated_service_controller_report_sync.py | 51 - ...metadata_google.api.servicecontrol.v1.json | 474 ----- .../fixup_servicecontrol_v1_keywords.py | 178 -- owl-bot-staging/v1/setup.py | 90 - .../v1/testing/constraints-3.10.txt | 6 - .../v1/testing/constraints-3.11.txt | 6 - .../v1/testing/constraints-3.12.txt | 6 - .../v1/testing/constraints-3.7.txt | 9 - .../v1/testing/constraints-3.8.txt | 6 - .../v1/testing/constraints-3.9.txt | 6 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/servicecontrol_v1/__init__.py | 16 - .../test_quota_controller.py | 1464 -------------- .../test_service_controller.py | 1740 ----------------- owl-bot-staging/v2/.coveragerc | 13 - owl-bot-staging/v2/.flake8 | 33 - owl-bot-staging/v2/MANIFEST.in | 2 - owl-bot-staging/v2/README.rst | 49 - owl-bot-staging/v2/docs/conf.py | 376 ---- owl-bot-staging/v2/docs/index.rst | 7 - .../servicecontrol_v2/service_controller.rst | 6 - .../v2/docs/servicecontrol_v2/services.rst | 6 - .../v2/docs/servicecontrol_v2/types.rst | 6 - .../google/cloud/servicecontrol/__init__.py | 37 - .../cloud/servicecontrol/gapic_version.py | 16 - .../v2/google/cloud/servicecontrol/py.typed | 2 - .../cloud/servicecontrol_v2/__init__.py | 38 - .../servicecontrol_v2/gapic_metadata.json | 58 - .../cloud/servicecontrol_v2/gapic_version.py | 16 - .../google/cloud/servicecontrol_v2/py.typed | 2 - .../servicecontrol_v2/services/__init__.py | 15 - .../services/service_controller/__init__.py | 22 - .../service_controller/async_client.py | 413 ---- .../services/service_controller/client.py | 604 ------ .../service_controller/transports/__init__.py | 38 - .../service_controller/transports/base.py | 169 -- .../service_controller/transports/grpc.py | 339 ---- .../transports/grpc_asyncio.py | 338 ---- .../service_controller/transports/rest.py | 415 ---- .../cloud/servicecontrol_v2/types/__init__.py | 30 - .../types/service_controller.py | 216 -- owl-bot-staging/v2/mypy.ini | 3 - owl-bot-staging/v2/noxfile.py | 184 -- ...enerated_service_controller_check_async.py | 51 - ...generated_service_controller_check_sync.py | 51 - ...nerated_service_controller_report_async.py | 51 - ...enerated_service_controller_report_sync.py | 51 - ...metadata_google.api.servicecontrol.v2.json | 321 --- .../fixup_servicecontrol_v2_keywords.py | 177 -- owl-bot-staging/v2/setup.py | 90 - .../v2/testing/constraints-3.10.txt | 6 - .../v2/testing/constraints-3.11.txt | 6 - .../v2/testing/constraints-3.12.txt | 6 - .../v2/testing/constraints-3.7.txt | 9 - .../v2/testing/constraints-3.8.txt | 6 - .../v2/testing/constraints-3.9.txt | 6 - owl-bot-staging/v2/tests/__init__.py | 16 - owl-bot-staging/v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/servicecontrol_v2/__init__.py | 16 - .../test_service_controller.py | 1704 ---------------- ...metadata_google.api.servicecontrol.v1.json | 2 +- ...metadata_google.api.servicecontrol.v2.json | 2 +- 124 files changed, 10 insertions(+), 17366 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/.flake8 delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/docs/servicecontrol_v1/quota_controller.rst delete mode 100644 owl-bot-staging/v1/docs/servicecontrol_v1/service_controller.rst delete mode 100644 owl-bot-staging/v1/docs/servicecontrol_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/servicecontrol_v1/types.rst delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/rest.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/rest.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/check_error.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/distribution.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/http_request.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/log_entry.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/metric_value.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/operation.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/quota_controller.py delete mode 100644 owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/service_controller.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json delete mode 100644 owl-bot-staging/v1/scripts/fixup_servicecontrol_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_quota_controller.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_service_controller.py delete mode 100644 owl-bot-staging/v2/.coveragerc delete mode 100644 owl-bot-staging/v2/.flake8 delete mode 100644 owl-bot-staging/v2/MANIFEST.in delete mode 100644 owl-bot-staging/v2/README.rst delete mode 100644 owl-bot-staging/v2/docs/conf.py delete mode 100644 owl-bot-staging/v2/docs/index.rst delete mode 100644 owl-bot-staging/v2/docs/servicecontrol_v2/service_controller.rst delete mode 100644 owl-bot-staging/v2/docs/servicecontrol_v2/services.rst delete mode 100644 owl-bot-staging/v2/docs/servicecontrol_v2/types.rst delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol/gapic_version.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol/py.typed delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_version.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/py.typed delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/service_controller.py delete mode 100644 owl-bot-staging/v2/mypy.ini delete mode 100644 owl-bot-staging/v2/noxfile.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json delete mode 100644 owl-bot-staging/v2/scripts/fixup_servicecontrol_v2_keywords.py delete mode 100644 owl-bot-staging/v2/setup.py delete mode 100644 owl-bot-staging/v2/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v2/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v2/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v2/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v2/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v2/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v2/tests/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/test_service_controller.py diff --git a/google/cloud/servicecontrol_v1/services/quota_controller/async_client.py b/google/cloud/servicecontrol_v1/services/quota_controller/async_client.py index be6fc6d..a5a1115 100644 --- a/google/cloud/servicecontrol_v1/services/quota_controller/async_client.py +++ b/google/cloud/servicecontrol_v1/services/quota_controller/async_client.py @@ -263,8 +263,8 @@ async def sample_allocate_quota(): Args: request (Optional[Union[google.cloud.servicecontrol_v1.types.AllocateQuotaRequest, dict]]): - The request object. Request message for the - AllocateQuota method. + The request object. Request message for the AllocateQuota + method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/servicecontrol_v1/services/quota_controller/client.py b/google/cloud/servicecontrol_v1/services/quota_controller/client.py index f54b0ee..f8ca746 100644 --- a/google/cloud/servicecontrol_v1/services/quota_controller/client.py +++ b/google/cloud/servicecontrol_v1/services/quota_controller/client.py @@ -472,8 +472,8 @@ def sample_allocate_quota(): Args: request (Union[google.cloud.servicecontrol_v1.types.AllocateQuotaRequest, dict]): - The request object. Request message for the - AllocateQuota method. + The request object. Request message for the AllocateQuota + method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/servicecontrol_v1/services/quota_controller/transports/rest.py b/google/cloud/servicecontrol_v1/services/quota_controller/transports/rest.py index 44c6b3e..ec897fa 100644 --- a/google/cloud/servicecontrol_v1/services/quota_controller/transports/rest.py +++ b/google/cloud/servicecontrol_v1/services/quota_controller/transports/rest.py @@ -218,7 +218,6 @@ def __call__( request (~.quota_controller.AllocateQuotaRequest): The request object. Request message for the AllocateQuota method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/servicecontrol_v1/services/service_controller/async_client.py b/google/cloud/servicecontrol_v1/services/service_controller/async_client.py index ce62f68..784d0d5 100644 --- a/google/cloud/servicecontrol_v1/services/service_controller/async_client.py +++ b/google/cloud/servicecontrol_v1/services/service_controller/async_client.py @@ -270,8 +270,7 @@ async def sample_check(): Args: request (Optional[Union[google.cloud.servicecontrol_v1.types.CheckRequest, dict]]): - The request object. Request message for the Check - method. + The request object. Request message for the Check method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/servicecontrol_v1/services/service_controller/client.py b/google/cloud/servicecontrol_v1/services/service_controller/client.py index 280944f..85eb839 100644 --- a/google/cloud/servicecontrol_v1/services/service_controller/client.py +++ b/google/cloud/servicecontrol_v1/services/service_controller/client.py @@ -479,8 +479,7 @@ def sample_check(): Args: request (Union[google.cloud.servicecontrol_v1.types.CheckRequest, dict]): - The request object. Request message for the Check - method. + The request object. Request message for the Check method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/servicecontrol_v1/services/service_controller/transports/rest.py b/google/cloud/servicecontrol_v1/services/service_controller/transports/rest.py index fd174ca..e15f371 100644 --- a/google/cloud/servicecontrol_v1/services/service_controller/transports/rest.py +++ b/google/cloud/servicecontrol_v1/services/service_controller/transports/rest.py @@ -335,7 +335,6 @@ def __call__( request (~.service_controller.ReportRequest): The request object. Request message for the Report method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/servicecontrol_v2/services/service_controller/async_client.py b/google/cloud/servicecontrol_v2/services/service_controller/async_client.py index dddaa7b..268de63 100644 --- a/google/cloud/servicecontrol_v2/services/service_controller/async_client.py +++ b/google/cloud/servicecontrol_v2/services/service_controller/async_client.py @@ -282,8 +282,7 @@ async def sample_check(): Args: request (Optional[Union[google.cloud.servicecontrol_v2.types.CheckRequest, dict]]): - The request object. Request message for the Check - method. + The request object. Request message for the Check method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/servicecontrol_v2/services/service_controller/client.py b/google/cloud/servicecontrol_v2/services/service_controller/client.py index 257bad5..12349d5 100644 --- a/google/cloud/servicecontrol_v2/services/service_controller/client.py +++ b/google/cloud/servicecontrol_v2/services/service_controller/client.py @@ -491,8 +491,7 @@ def sample_check(): Args: request (Union[google.cloud.servicecontrol_v2.types.CheckRequest, dict]): - The request object. Request message for the Check - method. + The request object. Request message for the Check method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/servicecontrol_v2/services/service_controller/transports/rest.py b/google/cloud/servicecontrol_v2/services/service_controller/transports/rest.py index 4bb90b8..03d16b5 100644 --- a/google/cloud/servicecontrol_v2/services/service_controller/transports/rest.py +++ b/google/cloud/servicecontrol_v2/services/service_controller/transports/rest.py @@ -340,7 +340,6 @@ def __call__( request (~.service_controller.ReportRequest): The request object. Request message for the Report method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index db73969..0000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/servicecontrol/__init__.py - google/cloud/servicecontrol/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/v1/.flake8 b/owl-bot-staging/v1/.flake8 deleted file mode 100644 index 29227d4..0000000 --- a/owl-bot-staging/v1/.flake8 +++ /dev/null @@ -1,33 +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. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index 145db90..0000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/servicecontrol *.py -recursive-include google/cloud/servicecontrol_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 68e4838..0000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Servicecontrol API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Servicecontrol API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index 4c7d6b4..0000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# -# google-cloud-service-control documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-service-control" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-service-control-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-service-control.tex", - u"google-cloud-service-control Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-service-control", - u"Google Cloud Servicecontrol Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-service-control", - u"google-cloud-service-control Documentation", - author, - "google-cloud-service-control", - "GAPIC library for Google Cloud Servicecontrol API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index cc2d937..0000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - servicecontrol_v1/services - servicecontrol_v1/types diff --git a/owl-bot-staging/v1/docs/servicecontrol_v1/quota_controller.rst b/owl-bot-staging/v1/docs/servicecontrol_v1/quota_controller.rst deleted file mode 100644 index 7f694a1..0000000 --- a/owl-bot-staging/v1/docs/servicecontrol_v1/quota_controller.rst +++ /dev/null @@ -1,6 +0,0 @@ -QuotaController ---------------------------------- - -.. automodule:: google.cloud.servicecontrol_v1.services.quota_controller - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/servicecontrol_v1/service_controller.rst b/owl-bot-staging/v1/docs/servicecontrol_v1/service_controller.rst deleted file mode 100644 index f3d8986..0000000 --- a/owl-bot-staging/v1/docs/servicecontrol_v1/service_controller.rst +++ /dev/null @@ -1,6 +0,0 @@ -ServiceController ------------------------------------ - -.. automodule:: google.cloud.servicecontrol_v1.services.service_controller - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/servicecontrol_v1/services.rst b/owl-bot-staging/v1/docs/servicecontrol_v1/services.rst deleted file mode 100644 index 779f197..0000000 --- a/owl-bot-staging/v1/docs/servicecontrol_v1/services.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Cloud Servicecontrol v1 API -=============================================== -.. toctree:: - :maxdepth: 2 - - quota_controller - service_controller diff --git a/owl-bot-staging/v1/docs/servicecontrol_v1/types.rst b/owl-bot-staging/v1/docs/servicecontrol_v1/types.rst deleted file mode 100644 index eda22be..0000000 --- a/owl-bot-staging/v1/docs/servicecontrol_v1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Servicecontrol v1 API -============================================ - -.. automodule:: google.cloud.servicecontrol_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol/__init__.py deleted file mode 100644 index 8256c92..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol/__init__.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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.servicecontrol import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.servicecontrol_v1.services.quota_controller.client import QuotaControllerClient -from google.cloud.servicecontrol_v1.services.quota_controller.async_client import QuotaControllerAsyncClient -from google.cloud.servicecontrol_v1.services.service_controller.client import ServiceControllerClient -from google.cloud.servicecontrol_v1.services.service_controller.async_client import ServiceControllerAsyncClient - -from google.cloud.servicecontrol_v1.types.check_error import CheckError -from google.cloud.servicecontrol_v1.types.distribution import Distribution -from google.cloud.servicecontrol_v1.types.http_request import HttpRequest -from google.cloud.servicecontrol_v1.types.log_entry import LogEntry -from google.cloud.servicecontrol_v1.types.log_entry import LogEntryOperation -from google.cloud.servicecontrol_v1.types.log_entry import LogEntrySourceLocation -from google.cloud.servicecontrol_v1.types.metric_value import MetricValue -from google.cloud.servicecontrol_v1.types.metric_value import MetricValueSet -from google.cloud.servicecontrol_v1.types.operation import Operation -from google.cloud.servicecontrol_v1.types.quota_controller import AllocateQuotaRequest -from google.cloud.servicecontrol_v1.types.quota_controller import AllocateQuotaResponse -from google.cloud.servicecontrol_v1.types.quota_controller import QuotaError -from google.cloud.servicecontrol_v1.types.quota_controller import QuotaOperation -from google.cloud.servicecontrol_v1.types.service_controller import CheckRequest -from google.cloud.servicecontrol_v1.types.service_controller import CheckResponse -from google.cloud.servicecontrol_v1.types.service_controller import ReportRequest -from google.cloud.servicecontrol_v1.types.service_controller import ReportResponse - -__all__ = ('QuotaControllerClient', - 'QuotaControllerAsyncClient', - 'ServiceControllerClient', - 'ServiceControllerAsyncClient', - 'CheckError', - 'Distribution', - 'HttpRequest', - 'LogEntry', - 'LogEntryOperation', - 'LogEntrySourceLocation', - 'MetricValue', - 'MetricValueSet', - 'Operation', - 'AllocateQuotaRequest', - 'AllocateQuotaResponse', - 'QuotaError', - 'QuotaOperation', - 'CheckRequest', - 'CheckResponse', - 'ReportRequest', - 'ReportResponse', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol/gapic_version.py b/owl-bot-staging/v1/google/cloud/servicecontrol/gapic_version.py deleted file mode 100644 index 405b1ce..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol/py.typed b/owl-bot-staging/v1/google/cloud/servicecontrol/py.typed deleted file mode 100644 index 3971a5d..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-service-control package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/__init__.py deleted file mode 100644 index 918ad3a..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/__init__.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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.servicecontrol_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.quota_controller import QuotaControllerClient -from .services.quota_controller import QuotaControllerAsyncClient -from .services.service_controller import ServiceControllerClient -from .services.service_controller import ServiceControllerAsyncClient - -from .types.check_error import CheckError -from .types.distribution import Distribution -from .types.http_request import HttpRequest -from .types.log_entry import LogEntry -from .types.log_entry import LogEntryOperation -from .types.log_entry import LogEntrySourceLocation -from .types.metric_value import MetricValue -from .types.metric_value import MetricValueSet -from .types.operation import Operation -from .types.quota_controller import AllocateQuotaRequest -from .types.quota_controller import AllocateQuotaResponse -from .types.quota_controller import QuotaError -from .types.quota_controller import QuotaOperation -from .types.service_controller import CheckRequest -from .types.service_controller import CheckResponse -from .types.service_controller import ReportRequest -from .types.service_controller import ReportResponse - -__all__ = ( - 'QuotaControllerAsyncClient', - 'ServiceControllerAsyncClient', -'AllocateQuotaRequest', -'AllocateQuotaResponse', -'CheckError', -'CheckRequest', -'CheckResponse', -'Distribution', -'HttpRequest', -'LogEntry', -'LogEntryOperation', -'LogEntrySourceLocation', -'MetricValue', -'MetricValueSet', -'Operation', -'QuotaControllerClient', -'QuotaError', -'QuotaOperation', -'ReportRequest', -'ReportResponse', -'ServiceControllerClient', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_metadata.json deleted file mode 100644 index d275a5b..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_metadata.json +++ /dev/null @@ -1,92 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.servicecontrol_v1", - "protoPackage": "google.api.servicecontrol.v1", - "schema": "1.0", - "services": { - "QuotaController": { - "clients": { - "grpc": { - "libraryClient": "QuotaControllerClient", - "rpcs": { - "AllocateQuota": { - "methods": [ - "allocate_quota" - ] - } - } - }, - "grpc-async": { - "libraryClient": "QuotaControllerAsyncClient", - "rpcs": { - "AllocateQuota": { - "methods": [ - "allocate_quota" - ] - } - } - }, - "rest": { - "libraryClient": "QuotaControllerClient", - "rpcs": { - "AllocateQuota": { - "methods": [ - "allocate_quota" - ] - } - } - } - } - }, - "ServiceController": { - "clients": { - "grpc": { - "libraryClient": "ServiceControllerClient", - "rpcs": { - "Check": { - "methods": [ - "check" - ] - }, - "Report": { - "methods": [ - "report" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ServiceControllerAsyncClient", - "rpcs": { - "Check": { - "methods": [ - "check" - ] - }, - "Report": { - "methods": [ - "report" - ] - } - } - }, - "rest": { - "libraryClient": "ServiceControllerClient", - "rpcs": { - "Check": { - "methods": [ - "check" - ] - }, - "Report": { - "methods": [ - "report" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_version.py deleted file mode 100644 index 405b1ce..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/py.typed b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/py.typed deleted file mode 100644 index 3971a5d..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-service-control package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/__init__.py deleted file mode 100644 index e8e1c38..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/__init__.py deleted file mode 100644 index 609d0e7..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 .client import QuotaControllerClient -from .async_client import QuotaControllerAsyncClient - -__all__ = ( - 'QuotaControllerClient', - 'QuotaControllerAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/async_client.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/async_client.py deleted file mode 100644 index e89c7ec..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/async_client.py +++ /dev/null @@ -1,291 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.servicecontrol_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.servicecontrol_v1.types import metric_value -from google.cloud.servicecontrol_v1.types import quota_controller -from .transports.base import QuotaControllerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import QuotaControllerGrpcAsyncIOTransport -from .client import QuotaControllerClient - - -class QuotaControllerAsyncClient: - """`Google Quota Control API `__ - - Allows clients to allocate and release quota against a `managed - service `__. - """ - - _client: QuotaControllerClient - - DEFAULT_ENDPOINT = QuotaControllerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = QuotaControllerClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(QuotaControllerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(QuotaControllerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(QuotaControllerClient.common_folder_path) - parse_common_folder_path = staticmethod(QuotaControllerClient.parse_common_folder_path) - common_organization_path = staticmethod(QuotaControllerClient.common_organization_path) - parse_common_organization_path = staticmethod(QuotaControllerClient.parse_common_organization_path) - common_project_path = staticmethod(QuotaControllerClient.common_project_path) - parse_common_project_path = staticmethod(QuotaControllerClient.parse_common_project_path) - common_location_path = staticmethod(QuotaControllerClient.common_location_path) - parse_common_location_path = staticmethod(QuotaControllerClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - QuotaControllerAsyncClient: The constructed client. - """ - return QuotaControllerClient.from_service_account_info.__func__(QuotaControllerAsyncClient, info, *args, **kwargs) # type: ignore - - @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: - QuotaControllerAsyncClient: The constructed client. - """ - return QuotaControllerClient.from_service_account_file.__func__(QuotaControllerAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return QuotaControllerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> QuotaControllerTransport: - """Returns the transport used by the client instance. - - Returns: - QuotaControllerTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(QuotaControllerClient).get_transport_class, type(QuotaControllerClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, QuotaControllerTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the quota controller 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, ~.QuotaControllerTransport]): 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 = QuotaControllerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def allocate_quota(self, - request: Optional[Union[quota_controller.AllocateQuotaRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> quota_controller.AllocateQuotaResponse: - r"""Attempts to allocate quota for the specified consumer. It should - be called before the operation is executed. - - This method requires the ``servicemanagement.services.quota`` - permission on the specified service. For more information, see - `Cloud IAM `__. - - **NOTE:** The client **must** fail-open on server errors - ``INTERNAL``, ``UNKNOWN``, ``DEADLINE_EXCEEDED``, and - ``UNAVAILABLE``. To ensure system reliability, the server may - inject these errors to prohibit any hard dependency on the quota - functionality. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicecontrol_v1 - - async def sample_allocate_quota(): - # Create a client - client = servicecontrol_v1.QuotaControllerAsyncClient() - - # Initialize request argument(s) - request = servicecontrol_v1.AllocateQuotaRequest( - ) - - # Make the request - response = await client.allocate_quota(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicecontrol_v1.types.AllocateQuotaRequest, dict]]): - The request object. Request message for the AllocateQuota - method. - 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: - google.cloud.servicecontrol_v1.types.AllocateQuotaResponse: - Response message for the - AllocateQuota method. - - """ - # Create or coerce a protobuf request object. - request = quota_controller.AllocateQuotaRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.allocate_quota, - default_timeout=None, - 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(( - ("service_name", request.service_name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "QuotaControllerAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/client.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/client.py deleted file mode 100644 index 33457f4..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/client.py +++ /dev/null @@ -1,487 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.servicecontrol_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.servicecontrol_v1.types import metric_value -from google.cloud.servicecontrol_v1.types import quota_controller -from .transports.base import QuotaControllerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import QuotaControllerGrpcTransport -from .transports.grpc_asyncio import QuotaControllerGrpcAsyncIOTransport -from .transports.rest import QuotaControllerRestTransport - - -class QuotaControllerClientMeta(type): - """Metaclass for the QuotaController 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[QuotaControllerTransport]] - _transport_registry["grpc"] = QuotaControllerGrpcTransport - _transport_registry["grpc_asyncio"] = QuotaControllerGrpcAsyncIOTransport - _transport_registry["rest"] = QuotaControllerRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[QuotaControllerTransport]: - """Returns 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 QuotaControllerClient(metaclass=QuotaControllerClientMeta): - """`Google Quota Control API `__ - - Allows clients to allocate and release quota against a `managed - service `__. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - 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 = "servicecontrol.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - QuotaControllerClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @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: - QuotaControllerClient: 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) -> QuotaControllerTransport: - """Returns the transport used by the client instance. - - Returns: - QuotaControllerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @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: - """Returns 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: - """Returns 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: - """Returns 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: - """Returns 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 {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, QuotaControllerTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the quota controller 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, QuotaControllerTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, QuotaControllerTransport): - # transport is a QuotaControllerTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - 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, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def allocate_quota(self, - request: Optional[Union[quota_controller.AllocateQuotaRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> quota_controller.AllocateQuotaResponse: - r"""Attempts to allocate quota for the specified consumer. It should - be called before the operation is executed. - - This method requires the ``servicemanagement.services.quota`` - permission on the specified service. For more information, see - `Cloud IAM `__. - - **NOTE:** The client **must** fail-open on server errors - ``INTERNAL``, ``UNKNOWN``, ``DEADLINE_EXCEEDED``, and - ``UNAVAILABLE``. To ensure system reliability, the server may - inject these errors to prohibit any hard dependency on the quota - functionality. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicecontrol_v1 - - def sample_allocate_quota(): - # Create a client - client = servicecontrol_v1.QuotaControllerClient() - - # Initialize request argument(s) - request = servicecontrol_v1.AllocateQuotaRequest( - ) - - # Make the request - response = client.allocate_quota(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicecontrol_v1.types.AllocateQuotaRequest, dict]): - The request object. Request message for the AllocateQuota - method. - 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: - google.cloud.servicecontrol_v1.types.AllocateQuotaResponse: - Response message for the - AllocateQuota method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a quota_controller.AllocateQuotaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, quota_controller.AllocateQuotaRequest): - request = quota_controller.AllocateQuotaRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.allocate_quota] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "QuotaControllerClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "QuotaControllerClient", -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/__init__.py deleted file mode 100644 index f4ecf30..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 QuotaControllerTransport -from .grpc import QuotaControllerGrpcTransport -from .grpc_asyncio import QuotaControllerGrpcAsyncIOTransport -from .rest import QuotaControllerRestTransport -from .rest import QuotaControllerRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[QuotaControllerTransport]] -_transport_registry['grpc'] = QuotaControllerGrpcTransport -_transport_registry['grpc_asyncio'] = QuotaControllerGrpcAsyncIOTransport -_transport_registry['rest'] = QuotaControllerRestTransport - -__all__ = ( - 'QuotaControllerTransport', - 'QuotaControllerGrpcTransport', - 'QuotaControllerGrpcAsyncIOTransport', - 'QuotaControllerRestTransport', - 'QuotaControllerRestInterceptor', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/base.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/base.py deleted file mode 100644 index b7f9b7a..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/base.py +++ /dev/null @@ -1,149 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.servicecontrol_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.servicecontrol_v1.types import quota_controller - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class QuotaControllerTransport(abc.ABC): - """Abstract transport class for QuotaController.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', - ) - - DEFAULT_HOST: str = 'servicecontrol.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **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. - scopes (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. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.allocate_quota: gapic_v1.method.wrap_method( - self.allocate_quota, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def allocate_quota(self) -> Callable[ - [quota_controller.AllocateQuotaRequest], - Union[ - quota_controller.AllocateQuotaResponse, - Awaitable[quota_controller.AllocateQuotaResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'QuotaControllerTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc.py deleted file mode 100644 index 4ceea00..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc.py +++ /dev/null @@ -1,278 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.servicecontrol_v1.types import quota_controller -from .base import QuotaControllerTransport, DEFAULT_CLIENT_INFO - - -class QuotaControllerGrpcTransport(QuotaControllerTransport): - """gRPC backend transport for QuotaController. - - `Google Quota Control API `__ - - Allows clients to allocate and release quota against a `managed - service `__. - - 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 = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> 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 application 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 the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` 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. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - 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._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - 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. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def allocate_quota(self) -> Callable[ - [quota_controller.AllocateQuotaRequest], - quota_controller.AllocateQuotaResponse]: - r"""Return a callable for the allocate quota method over gRPC. - - Attempts to allocate quota for the specified consumer. It should - be called before the operation is executed. - - This method requires the ``servicemanagement.services.quota`` - permission on the specified service. For more information, see - `Cloud IAM `__. - - **NOTE:** The client **must** fail-open on server errors - ``INTERNAL``, ``UNKNOWN``, ``DEADLINE_EXCEEDED``, and - ``UNAVAILABLE``. To ensure system reliability, the server may - inject these errors to prohibit any hard dependency on the quota - functionality. - - Returns: - Callable[[~.AllocateQuotaRequest], - ~.AllocateQuotaResponse]: - 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 'allocate_quota' not in self._stubs: - self._stubs['allocate_quota'] = self.grpc_channel.unary_unary( - '/google.api.servicecontrol.v1.QuotaController/AllocateQuota', - request_serializer=quota_controller.AllocateQuotaRequest.serialize, - response_deserializer=quota_controller.AllocateQuotaResponse.deserialize, - ) - return self._stubs['allocate_quota'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'QuotaControllerGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc_asyncio.py deleted file mode 100644 index 8a3833e..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/grpc_asyncio.py +++ /dev/null @@ -1,277 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_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.servicecontrol_v1.types import quota_controller -from .base import QuotaControllerTransport, DEFAULT_CLIENT_INFO -from .grpc import QuotaControllerGrpcTransport - - -class QuotaControllerGrpcAsyncIOTransport(QuotaControllerTransport): - """gRPC AsyncIO backend transport for QuotaController. - - `Google Quota Control API `__ - - Allows clients to allocate and release quota against a `managed - service `__. - - 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 = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (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. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> 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 application 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 the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` 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. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - 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._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @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 allocate_quota(self) -> Callable[ - [quota_controller.AllocateQuotaRequest], - Awaitable[quota_controller.AllocateQuotaResponse]]: - r"""Return a callable for the allocate quota method over gRPC. - - Attempts to allocate quota for the specified consumer. It should - be called before the operation is executed. - - This method requires the ``servicemanagement.services.quota`` - permission on the specified service. For more information, see - `Cloud IAM `__. - - **NOTE:** The client **must** fail-open on server errors - ``INTERNAL``, ``UNKNOWN``, ``DEADLINE_EXCEEDED``, and - ``UNAVAILABLE``. To ensure system reliability, the server may - inject these errors to prohibit any hard dependency on the quota - functionality. - - Returns: - Callable[[~.AllocateQuotaRequest], - Awaitable[~.AllocateQuotaResponse]]: - 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 'allocate_quota' not in self._stubs: - self._stubs['allocate_quota'] = self.grpc_channel.unary_unary( - '/google.api.servicecontrol.v1.QuotaController/AllocateQuota', - request_serializer=quota_controller.AllocateQuotaRequest.serialize, - response_deserializer=quota_controller.AllocateQuotaResponse.deserialize, - ) - return self._stubs['allocate_quota'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'QuotaControllerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/rest.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/rest.py deleted file mode 100644 index e78a09a..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/quota_controller/transports/rest.py +++ /dev/null @@ -1,295 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.servicecontrol_v1.types import quota_controller - -from .base import QuotaControllerTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class QuotaControllerRestInterceptor: - """Interceptor for QuotaController. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the QuotaControllerRestTransport. - - .. code-block:: python - class MyCustomQuotaControllerInterceptor(QuotaControllerRestInterceptor): - def pre_allocate_quota(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_allocate_quota(self, response): - logging.log(f"Received response: {response}") - return response - - transport = QuotaControllerRestTransport(interceptor=MyCustomQuotaControllerInterceptor()) - client = QuotaControllerClient(transport=transport) - - - """ - def pre_allocate_quota(self, request: quota_controller.AllocateQuotaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[quota_controller.AllocateQuotaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for allocate_quota - - Override in a subclass to manipulate the request or metadata - before they are sent to the QuotaController server. - """ - return request, metadata - - def post_allocate_quota(self, response: quota_controller.AllocateQuotaResponse) -> quota_controller.AllocateQuotaResponse: - """Post-rpc interceptor for allocate_quota - - Override in a subclass to manipulate the response - after it is returned by the QuotaController server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class QuotaControllerRestStub: - _session: AuthorizedSession - _host: str - _interceptor: QuotaControllerRestInterceptor - - -class QuotaControllerRestTransport(QuotaControllerTransport): - """REST backend transport for QuotaController. - - `Google Quota Control API `__ - - Allows clients to allocate and release quota against a `managed - service `__. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[QuotaControllerRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP 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 are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or QuotaControllerRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _AllocateQuota(QuotaControllerRestStub): - def __hash__(self): - return hash("AllocateQuota") - - def __call__(self, - request: quota_controller.AllocateQuotaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> quota_controller.AllocateQuotaResponse: - r"""Call the allocate quota method over HTTP. - - Args: - request (~.quota_controller.AllocateQuotaRequest): - The request object. Request message for the AllocateQuota - method. - 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: - ~.quota_controller.AllocateQuotaResponse: - Response message for the - AllocateQuota method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/services/{service_name}:allocateQuota', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_allocate_quota(request, metadata) - pb_request = quota_controller.AllocateQuotaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = quota_controller.AllocateQuotaResponse() - pb_resp = quota_controller.AllocateQuotaResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_allocate_quota(resp) - return resp - - @property - def allocate_quota(self) -> Callable[ - [quota_controller.AllocateQuotaRequest], - quota_controller.AllocateQuotaResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AllocateQuota(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'QuotaControllerRestTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/__init__.py deleted file mode 100644 index 187fc9e..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 .client import ServiceControllerClient -from .async_client import ServiceControllerAsyncClient - -__all__ = ( - 'ServiceControllerClient', - 'ServiceControllerAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/async_client.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/async_client.py deleted file mode 100644 index 6f1798e..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/async_client.py +++ /dev/null @@ -1,400 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.servicecontrol_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.servicecontrol_v1.types import check_error -from google.cloud.servicecontrol_v1.types import service_controller -from .transports.base import ServiceControllerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ServiceControllerGrpcAsyncIOTransport -from .client import ServiceControllerClient - - -class ServiceControllerAsyncClient: - """`Google Service Control API `__ - - Lets clients check and report operations against a `managed - service `__. - """ - - _client: ServiceControllerClient - - DEFAULT_ENDPOINT = ServiceControllerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ServiceControllerClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(ServiceControllerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ServiceControllerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ServiceControllerClient.common_folder_path) - parse_common_folder_path = staticmethod(ServiceControllerClient.parse_common_folder_path) - common_organization_path = staticmethod(ServiceControllerClient.common_organization_path) - parse_common_organization_path = staticmethod(ServiceControllerClient.parse_common_organization_path) - common_project_path = staticmethod(ServiceControllerClient.common_project_path) - parse_common_project_path = staticmethod(ServiceControllerClient.parse_common_project_path) - common_location_path = staticmethod(ServiceControllerClient.common_location_path) - parse_common_location_path = staticmethod(ServiceControllerClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServiceControllerAsyncClient: The constructed client. - """ - return ServiceControllerClient.from_service_account_info.__func__(ServiceControllerAsyncClient, info, *args, **kwargs) # type: ignore - - @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: - ServiceControllerAsyncClient: The constructed client. - """ - return ServiceControllerClient.from_service_account_file.__func__(ServiceControllerAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ServiceControllerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ServiceControllerTransport: - """Returns the transport used by the client instance. - - Returns: - ServiceControllerTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ServiceControllerClient).get_transport_class, type(ServiceControllerClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ServiceControllerTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the service controller 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, ~.ServiceControllerTransport]): 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 = ServiceControllerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def check(self, - request: Optional[Union[service_controller.CheckRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service_controller.CheckResponse: - r"""Checks whether an operation on a service should be allowed to - proceed based on the configuration of the service and related - policies. It must be called before the operation is executed. - - If feasible, the client should cache the check results and reuse - them for 60 seconds. In case of any server errors, the client - should rely on the cached results for much longer time to avoid - outage. WARNING: There is general 60s delay for the - configuration and policy propagation, therefore callers MUST NOT - depend on the ``Check`` method having the latest policy - information. - - NOTE: the - [CheckRequest][google.api.servicecontrol.v1.CheckRequest] has - the size limit (wire-format byte size) of 1MB. - - This method requires the ``servicemanagement.services.check`` - permission on the specified service. For more information, see - `Cloud IAM `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicecontrol_v1 - - async def sample_check(): - # Create a client - client = servicecontrol_v1.ServiceControllerAsyncClient() - - # Initialize request argument(s) - request = servicecontrol_v1.CheckRequest( - ) - - # Make the request - response = await client.check(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicecontrol_v1.types.CheckRequest, dict]]): - The request object. Request message for the Check method. - 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: - google.cloud.servicecontrol_v1.types.CheckResponse: - Response message for the Check - method. - - """ - # Create or coerce a protobuf request object. - request = service_controller.CheckRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.check, - default_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=5.0, - ), - default_timeout=5.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(( - ("service_name", request.service_name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def report(self, - request: Optional[Union[service_controller.ReportRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service_controller.ReportResponse: - r"""Reports operation results to Google Service Control, such as - logs and metrics. It should be called after an operation is - completed. - - If feasible, the client should aggregate reporting data for up - to 5 seconds to reduce API traffic. Limiting aggregation to 5 - seconds is to reduce data loss during client crashes. Clients - should carefully choose the aggregation time window to avoid - data loss risk more than 0.01% for business and compliance - reasons. - - NOTE: the - [ReportRequest][google.api.servicecontrol.v1.ReportRequest] has - the size limit (wire-format byte size) of 1MB. - - This method requires the ``servicemanagement.services.report`` - permission on the specified service. For more information, see - `Google Cloud IAM `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicecontrol_v1 - - async def sample_report(): - # Create a client - client = servicecontrol_v1.ServiceControllerAsyncClient() - - # Initialize request argument(s) - request = servicecontrol_v1.ReportRequest( - ) - - # Make the request - response = await client.report(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicecontrol_v1.types.ReportRequest, dict]]): - The request object. Request message for the Report - method. - 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: - google.cloud.servicecontrol_v1.types.ReportResponse: - Response message for the Report - method. - - """ - # Create or coerce a protobuf request object. - request = service_controller.ReportRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.report, - default_timeout=16.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(( - ("service_name", request.service_name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ServiceControllerAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/client.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/client.py deleted file mode 100644 index de04eb5..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/client.py +++ /dev/null @@ -1,591 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.servicecontrol_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.servicecontrol_v1.types import check_error -from google.cloud.servicecontrol_v1.types import service_controller -from .transports.base import ServiceControllerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ServiceControllerGrpcTransport -from .transports.grpc_asyncio import ServiceControllerGrpcAsyncIOTransport -from .transports.rest import ServiceControllerRestTransport - - -class ServiceControllerClientMeta(type): - """Metaclass for the ServiceController 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[ServiceControllerTransport]] - _transport_registry["grpc"] = ServiceControllerGrpcTransport - _transport_registry["grpc_asyncio"] = ServiceControllerGrpcAsyncIOTransport - _transport_registry["rest"] = ServiceControllerRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ServiceControllerTransport]: - """Returns 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 ServiceControllerClient(metaclass=ServiceControllerClientMeta): - """`Google Service Control API `__ - - Lets clients check and report operations against a `managed - service `__. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - 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 = "servicecontrol.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServiceControllerClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @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: - ServiceControllerClient: 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) -> ServiceControllerTransport: - """Returns the transport used by the client instance. - - Returns: - ServiceControllerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @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: - """Returns 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: - """Returns 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: - """Returns 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: - """Returns 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 {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ServiceControllerTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the service controller 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, ServiceControllerTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ServiceControllerTransport): - # transport is a ServiceControllerTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - 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, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def check(self, - request: Optional[Union[service_controller.CheckRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service_controller.CheckResponse: - r"""Checks whether an operation on a service should be allowed to - proceed based on the configuration of the service and related - policies. It must be called before the operation is executed. - - If feasible, the client should cache the check results and reuse - them for 60 seconds. In case of any server errors, the client - should rely on the cached results for much longer time to avoid - outage. WARNING: There is general 60s delay for the - configuration and policy propagation, therefore callers MUST NOT - depend on the ``Check`` method having the latest policy - information. - - NOTE: the - [CheckRequest][google.api.servicecontrol.v1.CheckRequest] has - the size limit (wire-format byte size) of 1MB. - - This method requires the ``servicemanagement.services.check`` - permission on the specified service. For more information, see - `Cloud IAM `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicecontrol_v1 - - def sample_check(): - # Create a client - client = servicecontrol_v1.ServiceControllerClient() - - # Initialize request argument(s) - request = servicecontrol_v1.CheckRequest( - ) - - # Make the request - response = client.check(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicecontrol_v1.types.CheckRequest, dict]): - The request object. Request message for the Check method. - 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: - google.cloud.servicecontrol_v1.types.CheckResponse: - Response message for the Check - method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a service_controller.CheckRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service_controller.CheckRequest): - request = service_controller.CheckRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.check] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def report(self, - request: Optional[Union[service_controller.ReportRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service_controller.ReportResponse: - r"""Reports operation results to Google Service Control, such as - logs and metrics. It should be called after an operation is - completed. - - If feasible, the client should aggregate reporting data for up - to 5 seconds to reduce API traffic. Limiting aggregation to 5 - seconds is to reduce data loss during client crashes. Clients - should carefully choose the aggregation time window to avoid - data loss risk more than 0.01% for business and compliance - reasons. - - NOTE: the - [ReportRequest][google.api.servicecontrol.v1.ReportRequest] has - the size limit (wire-format byte size) of 1MB. - - This method requires the ``servicemanagement.services.report`` - permission on the specified service. For more information, see - `Google Cloud IAM `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicecontrol_v1 - - def sample_report(): - # Create a client - client = servicecontrol_v1.ServiceControllerClient() - - # Initialize request argument(s) - request = servicecontrol_v1.ReportRequest( - ) - - # Make the request - response = client.report(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicecontrol_v1.types.ReportRequest, dict]): - The request object. Request message for the Report - method. - 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: - google.cloud.servicecontrol_v1.types.ReportResponse: - Response message for the Report - method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a service_controller.ReportRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service_controller.ReportRequest): - request = service_controller.ReportRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.report] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ServiceControllerClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ServiceControllerClient", -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/__init__.py deleted file mode 100644 index ad7b8b5..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ServiceControllerTransport -from .grpc import ServiceControllerGrpcTransport -from .grpc_asyncio import ServiceControllerGrpcAsyncIOTransport -from .rest import ServiceControllerRestTransport -from .rest import ServiceControllerRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ServiceControllerTransport]] -_transport_registry['grpc'] = ServiceControllerGrpcTransport -_transport_registry['grpc_asyncio'] = ServiceControllerGrpcAsyncIOTransport -_transport_registry['rest'] = ServiceControllerRestTransport - -__all__ = ( - 'ServiceControllerTransport', - 'ServiceControllerGrpcTransport', - 'ServiceControllerGrpcAsyncIOTransport', - 'ServiceControllerRestTransport', - 'ServiceControllerRestInterceptor', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/base.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/base.py deleted file mode 100644 index 2706f34..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/base.py +++ /dev/null @@ -1,169 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.servicecontrol_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.servicecontrol_v1.types import service_controller - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ServiceControllerTransport(abc.ABC): - """Abstract transport class for ServiceController.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', - ) - - DEFAULT_HOST: str = 'servicecontrol.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **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. - scopes (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. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.check: gapic_v1.method.wrap_method( - self.check, - default_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=5.0, - ), - default_timeout=5.0, - client_info=client_info, - ), - self.report: gapic_v1.method.wrap_method( - self.report, - default_timeout=16.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def check(self) -> Callable[ - [service_controller.CheckRequest], - Union[ - service_controller.CheckResponse, - Awaitable[service_controller.CheckResponse] - ]]: - raise NotImplementedError() - - @property - def report(self) -> Callable[ - [service_controller.ReportRequest], - Union[ - service_controller.ReportResponse, - Awaitable[service_controller.ReportResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ServiceControllerTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc.py deleted file mode 100644 index 596f458..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc.py +++ /dev/null @@ -1,328 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.servicecontrol_v1.types import service_controller -from .base import ServiceControllerTransport, DEFAULT_CLIENT_INFO - - -class ServiceControllerGrpcTransport(ServiceControllerTransport): - """gRPC backend transport for ServiceController. - - `Google Service Control API `__ - - Lets clients check and report operations against a `managed - service `__. - - 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 = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> 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 application 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 the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` 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. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - 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._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - 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. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def check(self) -> Callable[ - [service_controller.CheckRequest], - service_controller.CheckResponse]: - r"""Return a callable for the check method over gRPC. - - Checks whether an operation on a service should be allowed to - proceed based on the configuration of the service and related - policies. It must be called before the operation is executed. - - If feasible, the client should cache the check results and reuse - them for 60 seconds. In case of any server errors, the client - should rely on the cached results for much longer time to avoid - outage. WARNING: There is general 60s delay for the - configuration and policy propagation, therefore callers MUST NOT - depend on the ``Check`` method having the latest policy - information. - - NOTE: the - [CheckRequest][google.api.servicecontrol.v1.CheckRequest] has - the size limit (wire-format byte size) of 1MB. - - This method requires the ``servicemanagement.services.check`` - permission on the specified service. For more information, see - `Cloud IAM `__. - - Returns: - Callable[[~.CheckRequest], - ~.CheckResponse]: - 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 'check' not in self._stubs: - self._stubs['check'] = self.grpc_channel.unary_unary( - '/google.api.servicecontrol.v1.ServiceController/Check', - request_serializer=service_controller.CheckRequest.serialize, - response_deserializer=service_controller.CheckResponse.deserialize, - ) - return self._stubs['check'] - - @property - def report(self) -> Callable[ - [service_controller.ReportRequest], - service_controller.ReportResponse]: - r"""Return a callable for the report method over gRPC. - - Reports operation results to Google Service Control, such as - logs and metrics. It should be called after an operation is - completed. - - If feasible, the client should aggregate reporting data for up - to 5 seconds to reduce API traffic. Limiting aggregation to 5 - seconds is to reduce data loss during client crashes. Clients - should carefully choose the aggregation time window to avoid - data loss risk more than 0.01% for business and compliance - reasons. - - NOTE: the - [ReportRequest][google.api.servicecontrol.v1.ReportRequest] has - the size limit (wire-format byte size) of 1MB. - - This method requires the ``servicemanagement.services.report`` - permission on the specified service. For more information, see - `Google Cloud IAM `__. - - Returns: - Callable[[~.ReportRequest], - ~.ReportResponse]: - 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 'report' not in self._stubs: - self._stubs['report'] = self.grpc_channel.unary_unary( - '/google.api.servicecontrol.v1.ServiceController/Report', - request_serializer=service_controller.ReportRequest.serialize, - response_deserializer=service_controller.ReportResponse.deserialize, - ) - return self._stubs['report'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ServiceControllerGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc_asyncio.py deleted file mode 100644 index 1fb7c1d..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/grpc_asyncio.py +++ /dev/null @@ -1,327 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_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.servicecontrol_v1.types import service_controller -from .base import ServiceControllerTransport, DEFAULT_CLIENT_INFO -from .grpc import ServiceControllerGrpcTransport - - -class ServiceControllerGrpcAsyncIOTransport(ServiceControllerTransport): - """gRPC AsyncIO backend transport for ServiceController. - - `Google Service Control API `__ - - Lets clients check and report operations against a `managed - service `__. - - 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 = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (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. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> 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 application 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 the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` 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. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - 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._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @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 check(self) -> Callable[ - [service_controller.CheckRequest], - Awaitable[service_controller.CheckResponse]]: - r"""Return a callable for the check method over gRPC. - - Checks whether an operation on a service should be allowed to - proceed based on the configuration of the service and related - policies. It must be called before the operation is executed. - - If feasible, the client should cache the check results and reuse - them for 60 seconds. In case of any server errors, the client - should rely on the cached results for much longer time to avoid - outage. WARNING: There is general 60s delay for the - configuration and policy propagation, therefore callers MUST NOT - depend on the ``Check`` method having the latest policy - information. - - NOTE: the - [CheckRequest][google.api.servicecontrol.v1.CheckRequest] has - the size limit (wire-format byte size) of 1MB. - - This method requires the ``servicemanagement.services.check`` - permission on the specified service. For more information, see - `Cloud IAM `__. - - Returns: - Callable[[~.CheckRequest], - Awaitable[~.CheckResponse]]: - 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 'check' not in self._stubs: - self._stubs['check'] = self.grpc_channel.unary_unary( - '/google.api.servicecontrol.v1.ServiceController/Check', - request_serializer=service_controller.CheckRequest.serialize, - response_deserializer=service_controller.CheckResponse.deserialize, - ) - return self._stubs['check'] - - @property - def report(self) -> Callable[ - [service_controller.ReportRequest], - Awaitable[service_controller.ReportResponse]]: - r"""Return a callable for the report method over gRPC. - - Reports operation results to Google Service Control, such as - logs and metrics. It should be called after an operation is - completed. - - If feasible, the client should aggregate reporting data for up - to 5 seconds to reduce API traffic. Limiting aggregation to 5 - seconds is to reduce data loss during client crashes. Clients - should carefully choose the aggregation time window to avoid - data loss risk more than 0.01% for business and compliance - reasons. - - NOTE: the - [ReportRequest][google.api.servicecontrol.v1.ReportRequest] has - the size limit (wire-format byte size) of 1MB. - - This method requires the ``servicemanagement.services.report`` - permission on the specified service. For more information, see - `Google Cloud IAM `__. - - Returns: - Callable[[~.ReportRequest], - Awaitable[~.ReportResponse]]: - 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 'report' not in self._stubs: - self._stubs['report'] = self.grpc_channel.unary_unary( - '/google.api.servicecontrol.v1.ServiceController/Report', - request_serializer=service_controller.ReportRequest.serialize, - response_deserializer=service_controller.ReportResponse.deserialize, - ) - return self._stubs['report'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ServiceControllerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/rest.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/rest.py deleted file mode 100644 index 45f50cf..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/services/service_controller/transports/rest.py +++ /dev/null @@ -1,408 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.servicecontrol_v1.types import service_controller - -from .base import ServiceControllerTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ServiceControllerRestInterceptor: - """Interceptor for ServiceController. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the ServiceControllerRestTransport. - - .. code-block:: python - class MyCustomServiceControllerInterceptor(ServiceControllerRestInterceptor): - def pre_check(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_check(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_report(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_report(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ServiceControllerRestTransport(interceptor=MyCustomServiceControllerInterceptor()) - client = ServiceControllerClient(transport=transport) - - - """ - def pre_check(self, request: service_controller.CheckRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_controller.CheckRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for check - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceController server. - """ - return request, metadata - - def post_check(self, response: service_controller.CheckResponse) -> service_controller.CheckResponse: - """Post-rpc interceptor for check - - Override in a subclass to manipulate the response - after it is returned by the ServiceController server but before - it is returned to user code. - """ - return response - def pre_report(self, request: service_controller.ReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_controller.ReportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for report - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceController server. - """ - return request, metadata - - def post_report(self, response: service_controller.ReportResponse) -> service_controller.ReportResponse: - """Post-rpc interceptor for report - - Override in a subclass to manipulate the response - after it is returned by the ServiceController server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ServiceControllerRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ServiceControllerRestInterceptor - - -class ServiceControllerRestTransport(ServiceControllerTransport): - """REST backend transport for ServiceController. - - `Google Service Control API `__ - - Lets clients check and report operations against a `managed - service `__. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[ServiceControllerRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP 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 are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ServiceControllerRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _Check(ServiceControllerRestStub): - def __hash__(self): - return hash("Check") - - def __call__(self, - request: service_controller.CheckRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service_controller.CheckResponse: - r"""Call the check method over HTTP. - - Args: - request (~.service_controller.CheckRequest): - The request object. Request message for the Check method. - 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: - ~.service_controller.CheckResponse: - Response message for the Check - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/services/{service_name}:check', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_check(request, metadata) - pb_request = service_controller.CheckRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service_controller.CheckResponse() - pb_resp = service_controller.CheckResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_check(resp) - return resp - - class _Report(ServiceControllerRestStub): - def __hash__(self): - return hash("Report") - - def __call__(self, - request: service_controller.ReportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service_controller.ReportResponse: - r"""Call the report method over HTTP. - - Args: - request (~.service_controller.ReportRequest): - The request object. Request message for the Report - method. - 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: - ~.service_controller.ReportResponse: - Response message for the Report - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/services/{service_name}:report', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_report(request, metadata) - pb_request = service_controller.ReportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service_controller.ReportResponse() - pb_resp = service_controller.ReportResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_report(resp) - return resp - - @property - def check(self) -> Callable[ - [service_controller.CheckRequest], - service_controller.CheckResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Check(self._session, self._host, self._interceptor) # type: ignore - - @property - def report(self) -> Callable[ - [service_controller.ReportRequest], - service_controller.ReportResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Report(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ServiceControllerRestTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/__init__.py deleted file mode 100644 index 4f3ef6c..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/__init__.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 .check_error import ( - CheckError, -) -from .distribution import ( - Distribution, -) -from .http_request import ( - HttpRequest, -) -from .log_entry import ( - LogEntry, - LogEntryOperation, - LogEntrySourceLocation, -) -from .metric_value import ( - MetricValue, - MetricValueSet, -) -from .operation import ( - Operation, -) -from .quota_controller import ( - AllocateQuotaRequest, - AllocateQuotaResponse, - QuotaError, - QuotaOperation, -) -from .service_controller import ( - CheckRequest, - CheckResponse, - ReportRequest, - ReportResponse, -) - -__all__ = ( - 'CheckError', - 'Distribution', - 'HttpRequest', - 'LogEntry', - 'LogEntryOperation', - 'LogEntrySourceLocation', - 'MetricValue', - 'MetricValueSet', - 'Operation', - 'AllocateQuotaRequest', - 'AllocateQuotaResponse', - 'QuotaError', - 'QuotaOperation', - 'CheckRequest', - 'CheckResponse', - 'ReportRequest', - 'ReportResponse', -) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/check_error.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/check_error.py deleted file mode 100644 index fd3a7a8..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/check_error.py +++ /dev/null @@ -1,164 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.api.servicecontrol.v1', - manifest={ - 'CheckError', - }, -) - - -class CheckError(proto.Message): - r"""Defines the errors to be returned in - [google.api.servicecontrol.v1.CheckResponse.check_errors][google.api.servicecontrol.v1.CheckResponse.check_errors]. - - Attributes: - code (google.cloud.servicecontrol_v1.types.CheckError.Code): - The error code. - subject (str): - Subject to whom this error applies. See the - specific code enum for more details on this - field. For example: - - "project:" - - "folder:" - - "organization:". - detail (str): - Free-form text providing details on the error - cause of the error. - status (google.rpc.status_pb2.Status): - Contains public information about the check error. If - available, ``status.code`` will be non zero and client can - propagate it out as public error. - """ - class Code(proto.Enum): - r"""Error codes for Check responses. - - Values: - ERROR_CODE_UNSPECIFIED (0): - This is never used in ``CheckResponse``. - NOT_FOUND (5): - The consumer's project id, network container, or resource - container was not found. Same as - [google.rpc.Code.NOT_FOUND][google.rpc.Code.NOT_FOUND]. - PERMISSION_DENIED (7): - The consumer doesn't have access to the specified resource. - Same as - [google.rpc.Code.PERMISSION_DENIED][google.rpc.Code.PERMISSION_DENIED]. - RESOURCE_EXHAUSTED (8): - Quota check failed. Same as - [google.rpc.Code.RESOURCE_EXHAUSTED][google.rpc.Code.RESOURCE_EXHAUSTED]. - SERVICE_NOT_ACTIVATED (104): - The consumer hasn't activated the service. - BILLING_DISABLED (107): - The consumer cannot access the service - because billing is disabled. - PROJECT_DELETED (108): - The consumer's project has been marked as - deleted (soft deletion). - PROJECT_INVALID (114): - The consumer's project number or id does not - represent a valid project. - CONSUMER_INVALID (125): - The input consumer info does not represent a - valid consumer folder or organization. - IP_ADDRESS_BLOCKED (109): - The IP address of the consumer is invalid for - the specific consumer project. - REFERER_BLOCKED (110): - The referer address of the consumer request - is invalid for the specific consumer project. - CLIENT_APP_BLOCKED (111): - The client application of the consumer - request is invalid for the specific consumer - project. - API_TARGET_BLOCKED (122): - The API targeted by this request is invalid - for the specified consumer project. - API_KEY_INVALID (105): - The consumer's API key is invalid. - API_KEY_EXPIRED (112): - The consumer's API Key has expired. - API_KEY_NOT_FOUND (113): - The consumer's API Key was not found in - config record. - INVALID_CREDENTIAL (123): - The credential in the request can not be - verified. - NAMESPACE_LOOKUP_UNAVAILABLE (300): - The backend server for looking up project - id/number is unavailable. - SERVICE_STATUS_UNAVAILABLE (301): - The backend server for checking service - status is unavailable. - BILLING_STATUS_UNAVAILABLE (302): - The backend server for checking billing - status is unavailable. - CLOUD_RESOURCE_MANAGER_BACKEND_UNAVAILABLE (305): - Cloud Resource Manager backend server is - unavailable. - """ - ERROR_CODE_UNSPECIFIED = 0 - NOT_FOUND = 5 - PERMISSION_DENIED = 7 - RESOURCE_EXHAUSTED = 8 - SERVICE_NOT_ACTIVATED = 104 - BILLING_DISABLED = 107 - PROJECT_DELETED = 108 - PROJECT_INVALID = 114 - CONSUMER_INVALID = 125 - IP_ADDRESS_BLOCKED = 109 - REFERER_BLOCKED = 110 - CLIENT_APP_BLOCKED = 111 - API_TARGET_BLOCKED = 122 - API_KEY_INVALID = 105 - API_KEY_EXPIRED = 112 - API_KEY_NOT_FOUND = 113 - INVALID_CREDENTIAL = 123 - NAMESPACE_LOOKUP_UNAVAILABLE = 300 - SERVICE_STATUS_UNAVAILABLE = 301 - BILLING_STATUS_UNAVAILABLE = 302 - CLOUD_RESOURCE_MANAGER_BACKEND_UNAVAILABLE = 305 - - code: Code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - subject: str = proto.Field( - proto.STRING, - number=4, - ) - detail: str = proto.Field( - proto.STRING, - number=2, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/distribution.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/distribution.py deleted file mode 100644 index 321b27f..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/distribution.py +++ /dev/null @@ -1,241 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.api import distribution_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.api.servicecontrol.v1', - manifest={ - 'Distribution', - }, -) - - -class Distribution(proto.Message): - r"""Distribution represents a frequency distribution of double-valued - sample points. It contains the size of the population of sample - points plus additional optional information: - - - the arithmetic mean of the samples - - the minimum and maximum of the samples - - the sum-squared-deviation of the samples, used to compute - variance - - a histogram of the values of the sample points - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - count (int): - The total number of samples in the - distribution. Must be >= 0. - mean (float): - The arithmetic mean of the samples in the distribution. If - ``count`` is zero then this field must be zero. - minimum (float): - The minimum of the population of values. Ignored if - ``count`` is zero. - maximum (float): - The maximum of the population of values. Ignored if - ``count`` is zero. - sum_of_squared_deviation (float): - The sum of squared deviations from the mean: - Sum[i=1..count]((x_i - mean)^2) where each x_i is a sample - values. If ``count`` is zero then this field must be zero, - otherwise validation of the request fails. - bucket_counts (MutableSequence[int]): - The number of samples in each histogram bucket. - ``bucket_counts`` are optional. If present, they must sum to - the ``count`` value. - - The buckets are defined below in ``bucket_option``. There - are N buckets. ``bucket_counts[0]`` is the number of samples - in the underflow bucket. ``bucket_counts[1]`` to - ``bucket_counts[N-1]`` are the numbers of samples in each of - the finite buckets. And - ``bucket_counts[N] is the number of samples in the overflow bucket. See the comments of``\ bucket_option\` - below for more details. - - Any suffix of trailing zeros may be omitted. - linear_buckets (google.cloud.servicecontrol_v1.types.Distribution.LinearBuckets): - Buckets with constant width. - - This field is a member of `oneof`_ ``bucket_option``. - exponential_buckets (google.cloud.servicecontrol_v1.types.Distribution.ExponentialBuckets): - Buckets with exponentially growing width. - - This field is a member of `oneof`_ ``bucket_option``. - explicit_buckets (google.cloud.servicecontrol_v1.types.Distribution.ExplicitBuckets): - Buckets with arbitrary user-provided width. - - This field is a member of `oneof`_ ``bucket_option``. - exemplars (MutableSequence[google.api.distribution_pb2.Exemplar]): - Example points. Must be in increasing order of ``value`` - field. - """ - - class LinearBuckets(proto.Message): - r"""Describing buckets with constant width. - - Attributes: - num_finite_buckets (int): - The number of finite buckets. With the underflow and - overflow buckets, the total number of buckets is - ``num_finite_buckets`` + 2. See comments on - ``bucket_options`` for details. - width (float): - The i'th linear bucket covers the interval [offset + (i-1) - \* width, offset + i \* width) where i ranges from 1 to - num_finite_buckets, inclusive. Must be strictly positive. - offset (float): - The i'th linear bucket covers the interval [offset + (i-1) - \* width, offset + i \* width) where i ranges from 1 to - num_finite_buckets, inclusive. - """ - - num_finite_buckets: int = proto.Field( - proto.INT32, - number=1, - ) - width: float = proto.Field( - proto.DOUBLE, - number=2, - ) - offset: float = proto.Field( - proto.DOUBLE, - number=3, - ) - - class ExponentialBuckets(proto.Message): - r"""Describing buckets with exponentially growing width. - - Attributes: - num_finite_buckets (int): - The number of finite buckets. With the underflow and - overflow buckets, the total number of buckets is - ``num_finite_buckets`` + 2. See comments on - ``bucket_options`` for details. - growth_factor (float): - The i'th exponential bucket covers the interval [scale \* - growth_factor^(i-1), scale \* growth_factor^i) where i - ranges from 1 to num_finite_buckets inclusive. Must be - larger than 1.0. - scale (float): - The i'th exponential bucket covers the interval [scale \* - growth_factor^(i-1), scale \* growth_factor^i) where i - ranges from 1 to num_finite_buckets inclusive. Must be > 0. - """ - - num_finite_buckets: int = proto.Field( - proto.INT32, - number=1, - ) - growth_factor: float = proto.Field( - proto.DOUBLE, - number=2, - ) - scale: float = proto.Field( - proto.DOUBLE, - number=3, - ) - - class ExplicitBuckets(proto.Message): - r"""Describing buckets with arbitrary user-provided width. - - Attributes: - bounds (MutableSequence[float]): - 'bound' is a list of strictly increasing boundaries between - buckets. Note that a list of length N-1 defines N buckets - because of fenceposting. See comments on ``bucket_options`` - for details. - - The i'th finite bucket covers the interval [bound[i-1], - bound[i]) where i ranges from 1 to bound_size() - 1. Note - that there are no finite buckets at all if 'bound' only - contains a single element; in that special case the single - bound defines the boundary between the underflow and - overflow buckets. - - bucket number lower bound upper bound i == 0 (underflow) - -inf bound[i] 0 < i < bound_size() bound[i-1] bound[i] i == - bound_size() (overflow) bound[i-1] +inf - """ - - bounds: MutableSequence[float] = proto.RepeatedField( - proto.DOUBLE, - number=1, - ) - - count: int = proto.Field( - proto.INT64, - number=1, - ) - mean: float = proto.Field( - proto.DOUBLE, - number=2, - ) - minimum: float = proto.Field( - proto.DOUBLE, - number=3, - ) - maximum: float = proto.Field( - proto.DOUBLE, - number=4, - ) - sum_of_squared_deviation: float = proto.Field( - proto.DOUBLE, - number=5, - ) - bucket_counts: MutableSequence[int] = proto.RepeatedField( - proto.INT64, - number=6, - ) - linear_buckets: LinearBuckets = proto.Field( - proto.MESSAGE, - number=7, - oneof='bucket_option', - message=LinearBuckets, - ) - exponential_buckets: ExponentialBuckets = proto.Field( - proto.MESSAGE, - number=8, - oneof='bucket_option', - message=ExponentialBuckets, - ) - explicit_buckets: ExplicitBuckets = proto.Field( - proto.MESSAGE, - number=9, - oneof='bucket_option', - message=ExplicitBuckets, - ) - exemplars: MutableSequence[distribution_pb2.Distribution.Exemplar] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=distribution_pb2.Distribution.Exemplar, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/http_request.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/http_request.py deleted file mode 100644 index d0dbb7d..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/http_request.py +++ /dev/null @@ -1,156 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.api.servicecontrol.v1', - manifest={ - 'HttpRequest', - }, -) - - -class HttpRequest(proto.Message): - r"""A common proto for logging HTTP requests. Only contains - semantics defined by the HTTP specification. Product-specific - logging information MUST be defined in a separate message. - - Attributes: - request_method (str): - The request method. Examples: ``"GET"``, ``"HEAD"``, - ``"PUT"``, ``"POST"``. - request_url (str): - The scheme (http, https), the host name, the path, and the - query portion of the URL that was requested. Example: - ``"http://example.com/some/info?color=red"``. - request_size (int): - The size of the HTTP request message in - bytes, including the request headers and the - request body. - status (int): - The response code indicating the status of - the response. Examples: 200, 404. - response_size (int): - The size of the HTTP response message sent - back to the client, in bytes, including the - response headers and the response body. - user_agent (str): - The user agent sent by the client. Example: - ``"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET CLR 1.0.3705)"``. - remote_ip (str): - The IP address (IPv4 or IPv6) of the client that issued the - HTTP request. Examples: ``"192.168.1.1"``, - ``"FE80::0202:B3FF:FE1E:8329"``. - server_ip (str): - The IP address (IPv4 or IPv6) of the origin - server that the request was sent to. - referer (str): - The referer URL of the request, as defined in `HTTP/1.1 - Header Field - Definitions `__. - latency (google.protobuf.duration_pb2.Duration): - The request processing latency on the server, - from the time the request was received until the - response was sent. - cache_lookup (bool): - Whether or not a cache lookup was attempted. - cache_hit (bool): - Whether or not an entity was served from - cache (with or without validation). - cache_validated_with_origin_server (bool): - Whether or not the response was validated with the origin - server before being served from cache. This field is only - meaningful if ``cache_hit`` is True. - cache_fill_bytes (int): - The number of HTTP response bytes inserted - into cache. Set only when a cache fill was - attempted. - protocol (str): - Protocol used for the request. Examples: - "HTTP/1.1", "HTTP/2", "websocket". - """ - - request_method: str = proto.Field( - proto.STRING, - number=1, - ) - request_url: str = proto.Field( - proto.STRING, - number=2, - ) - request_size: int = proto.Field( - proto.INT64, - number=3, - ) - status: int = proto.Field( - proto.INT32, - number=4, - ) - response_size: int = proto.Field( - proto.INT64, - number=5, - ) - user_agent: str = proto.Field( - proto.STRING, - number=6, - ) - remote_ip: str = proto.Field( - proto.STRING, - number=7, - ) - server_ip: str = proto.Field( - proto.STRING, - number=13, - ) - referer: str = proto.Field( - proto.STRING, - number=8, - ) - latency: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=14, - message=duration_pb2.Duration, - ) - cache_lookup: bool = proto.Field( - proto.BOOL, - number=11, - ) - cache_hit: bool = proto.Field( - proto.BOOL, - number=9, - ) - cache_validated_with_origin_server: bool = proto.Field( - proto.BOOL, - number=10, - ) - cache_fill_bytes: int = proto.Field( - proto.INT64, - number=12, - ) - protocol: str = proto.Field( - proto.STRING, - number=15, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/log_entry.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/log_entry.py deleted file mode 100644 index 7448655..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/log_entry.py +++ /dev/null @@ -1,238 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.servicecontrol_v1.types import http_request as gas_http_request -from google.logging.type import log_severity_pb2 # type: ignore -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.api.servicecontrol.v1', - manifest={ - 'LogEntry', - 'LogEntryOperation', - 'LogEntrySourceLocation', - }, -) - - -class LogEntry(proto.Message): - r"""An individual log entry. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Required. The log to which this log entry belongs. Examples: - ``"syslog"``, ``"book_log"``. - timestamp (google.protobuf.timestamp_pb2.Timestamp): - The time the event described by the log entry - occurred. If omitted, defaults to operation - start time. - severity (google.logging.type.log_severity_pb2.LogSeverity): - The severity of the log entry. The default value is - ``LogSeverity.DEFAULT``. - http_request (google.cloud.servicecontrol_v1.types.HttpRequest): - Optional. Information about the HTTP request - associated with this log entry, if applicable. - trace (str): - Optional. Resource name of the trace associated with the log - entry, if any. If this field contains a relative resource - name, you can assume the name is relative to - ``//tracing.googleapis.com``. Example: - ``projects/my-projectid/traces/06796866738c859f2f19b7cfb3214824`` - insert_id (str): - A unique ID for the log entry used for deduplication. If - omitted, the implementation will generate one based on - operation_id. - labels (MutableMapping[str, str]): - A set of user-defined (key, value) data that - provides additional information about the log - entry. - proto_payload (google.protobuf.any_pb2.Any): - The log entry payload, represented as a protocol buffer that - is expressed as a JSON object. The only accepted type - currently is [AuditLog][google.cloud.audit.AuditLog]. - - This field is a member of `oneof`_ ``payload``. - text_payload (str): - The log entry payload, represented as a - Unicode string (UTF-8). - - This field is a member of `oneof`_ ``payload``. - struct_payload (google.protobuf.struct_pb2.Struct): - The log entry payload, represented as a - structure that is expressed as a JSON object. - - This field is a member of `oneof`_ ``payload``. - operation (google.cloud.servicecontrol_v1.types.LogEntryOperation): - Optional. Information about an operation - associated with the log entry, if applicable. - source_location (google.cloud.servicecontrol_v1.types.LogEntrySourceLocation): - Optional. Source code location information - associated with the log entry, if any. - """ - - name: str = proto.Field( - proto.STRING, - number=10, - ) - timestamp: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - severity: log_severity_pb2.LogSeverity = proto.Field( - proto.ENUM, - number=12, - enum=log_severity_pb2.LogSeverity, - ) - http_request: gas_http_request.HttpRequest = proto.Field( - proto.MESSAGE, - number=14, - message=gas_http_request.HttpRequest, - ) - trace: str = proto.Field( - proto.STRING, - number=15, - ) - insert_id: str = proto.Field( - proto.STRING, - number=4, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=13, - ) - proto_payload: any_pb2.Any = proto.Field( - proto.MESSAGE, - number=2, - oneof='payload', - message=any_pb2.Any, - ) - text_payload: str = proto.Field( - proto.STRING, - number=3, - oneof='payload', - ) - struct_payload: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=6, - oneof='payload', - message=struct_pb2.Struct, - ) - operation: 'LogEntryOperation' = proto.Field( - proto.MESSAGE, - number=16, - message='LogEntryOperation', - ) - source_location: 'LogEntrySourceLocation' = proto.Field( - proto.MESSAGE, - number=17, - message='LogEntrySourceLocation', - ) - - -class LogEntryOperation(proto.Message): - r"""Additional information about a potentially long-running - operation with which a log entry is associated. - - Attributes: - id (str): - Optional. An arbitrary operation identifier. - Log entries with the same identifier are assumed - to be part of the same operation. - producer (str): - Optional. An arbitrary producer identifier. The combination - of ``id`` and ``producer`` must be globally unique. Examples - for ``producer``: ``"MyDivision.MyBigCompany.com"``, - ``"github.com/MyProject/MyApplication"``. - first (bool): - Optional. Set this to True if this is the - first log entry in the operation. - last (bool): - Optional. Set this to True if this is the - last log entry in the operation. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - producer: str = proto.Field( - proto.STRING, - number=2, - ) - first: bool = proto.Field( - proto.BOOL, - number=3, - ) - last: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class LogEntrySourceLocation(proto.Message): - r"""Additional information about the source code location that - produced the log entry. - - Attributes: - file (str): - Optional. Source file name. Depending on the - runtime environment, this might be a simple name - or a fully-qualified name. - line (int): - Optional. Line within the source file. - 1-based; 0 indicates no line number available. - function (str): - Optional. Human-readable name of the function or method - being invoked, with optional context such as the class or - package name. This information may be used in contexts such - as the logs viewer, where a file and line number are less - meaningful. The format can vary by language. For example: - ``qual.if.ied.Class.method`` (Java), ``dir/package.func`` - (Go), ``function`` (Python). - """ - - file: str = proto.Field( - proto.STRING, - number=1, - ) - line: int = proto.Field( - proto.INT64, - number=2, - ) - function: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/metric_value.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/metric_value.py deleted file mode 100644 index 48d52cf..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/metric_value.py +++ /dev/null @@ -1,153 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.servicecontrol_v1.types import distribution as gas_distribution -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.api.servicecontrol.v1', - manifest={ - 'MetricValue', - 'MetricValueSet', - }, -) - - -class MetricValue(proto.Message): - r"""Represents a single metric value. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - labels (MutableMapping[str, str]): - The labels describing the metric value. See comments on - [google.api.servicecontrol.v1.Operation.labels][google.api.servicecontrol.v1.Operation.labels] - for the overriding relationship. Note that this map must not - contain monitored resource labels. - start_time (google.protobuf.timestamp_pb2.Timestamp): - The start of the time period over which this metric value's - measurement applies. The time period has different semantics - for different metric types (cumulative, delta, and gauge). - See the metric definition documentation in the service - configuration for details. If not specified, - [google.api.servicecontrol.v1.Operation.start_time][google.api.servicecontrol.v1.Operation.start_time] - will be used. - end_time (google.protobuf.timestamp_pb2.Timestamp): - The end of the time period over which this metric value's - measurement applies. If not specified, - [google.api.servicecontrol.v1.Operation.end_time][google.api.servicecontrol.v1.Operation.end_time] - will be used. - bool_value (bool): - A boolean value. - - This field is a member of `oneof`_ ``value``. - int64_value (int): - A signed 64-bit integer value. - - This field is a member of `oneof`_ ``value``. - double_value (float): - A double precision floating point value. - - This field is a member of `oneof`_ ``value``. - string_value (str): - A text string value. - - This field is a member of `oneof`_ ``value``. - distribution_value (google.cloud.servicecontrol_v1.types.Distribution): - A distribution value. - - This field is a member of `oneof`_ ``value``. - """ - - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=1, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - bool_value: bool = proto.Field( - proto.BOOL, - number=4, - oneof='value', - ) - int64_value: int = proto.Field( - proto.INT64, - number=5, - oneof='value', - ) - double_value: float = proto.Field( - proto.DOUBLE, - number=6, - oneof='value', - ) - string_value: str = proto.Field( - proto.STRING, - number=7, - oneof='value', - ) - distribution_value: gas_distribution.Distribution = proto.Field( - proto.MESSAGE, - number=8, - oneof='value', - message=gas_distribution.Distribution, - ) - - -class MetricValueSet(proto.Message): - r"""Represents a set of metric values in the same metric. - Each metric value in the set should have a unique combination of - start time, end time, and label values. - - Attributes: - metric_name (str): - The metric name defined in the service - configuration. - metric_values (MutableSequence[google.cloud.servicecontrol_v1.types.MetricValue]): - The values in this metric. - """ - - metric_name: str = proto.Field( - proto.STRING, - number=1, - ) - metric_values: MutableSequence['MetricValue'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='MetricValue', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/operation.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/operation.py deleted file mode 100644 index 5db3c71..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/operation.py +++ /dev/null @@ -1,186 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.servicecontrol_v1.types import log_entry -from google.cloud.servicecontrol_v1.types import metric_value -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.api.servicecontrol.v1', - manifest={ - 'Operation', - }, -) - - -class Operation(proto.Message): - r"""Represents information regarding an operation. - - Attributes: - operation_id (str): - Identity of the operation. This must be - unique within the scope of the service that - generated the operation. If the service calls - Check() and Report() on the same operation, the - two calls should carry the same id. - - UUID version 4 is recommended, though not - required. In scenarios where an operation is - computed from existing information and an - idempotent id is desirable for deduplication - purpose, UUID version 5 is recommended. See RFC - 4122 for details. - operation_name (str): - Fully qualified name of the operation. - Reserved for future use. - consumer_id (str): - Identity of the consumer who is using the service. This - field should be filled in for the operations initiated by a - consumer, but not for service-initiated operations that are - not related to a specific consumer. - - - This can be in one of the following formats: - - - project:PROJECT_ID, - - project\ ``_``\ number:PROJECT_NUMBER, - - projects/PROJECT_ID or PROJECT_NUMBER, - - folders/FOLDER_NUMBER, - - organizations/ORGANIZATION_NUMBER, - - api\ ``_``\ key:API_KEY. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Start time of the operation. - end_time (google.protobuf.timestamp_pb2.Timestamp): - End time of the operation. Required when the operation is - used in - [ServiceController.Report][google.api.servicecontrol.v1.ServiceController.Report], - but optional when the operation is used in - [ServiceController.Check][google.api.servicecontrol.v1.ServiceController.Check]. - labels (MutableMapping[str, str]): - Labels describing the operation. Only the following labels - are allowed: - - - Labels describing monitored resources as defined in the - service configuration. - - Default labels of metric values. When specified, labels - defined in the metric value override these default. - - The following labels defined by Google Cloud Platform: - - - ``cloud.googleapis.com/location`` describing the - location where the operation happened, - - ``servicecontrol.googleapis.com/user_agent`` - describing the user agent of the API request, - - ``servicecontrol.googleapis.com/service_agent`` - describing the service used to handle the API request - (e.g. ESP), - - ``servicecontrol.googleapis.com/platform`` describing - the platform where the API is served, such as App - Engine, Compute Engine, or Kubernetes Engine. - metric_value_sets (MutableSequence[google.cloud.servicecontrol_v1.types.MetricValueSet]): - Represents information about this operation. - Each MetricValueSet corresponds to a metric - defined in the service configuration. The data - type used in the MetricValueSet must agree with - the data type specified in the metric - definition. - Within a single operation, it is not allowed to - have more than one MetricValue instances that - have the same metric names and identical label - value combinations. If a request has such - duplicated MetricValue instances, the entire - request is rejected with an invalid argument - error. - log_entries (MutableSequence[google.cloud.servicecontrol_v1.types.LogEntry]): - Represents information to be logged. - importance (google.cloud.servicecontrol_v1.types.Operation.Importance): - DO NOT USE. This is an experimental field. - extensions (MutableSequence[google.protobuf.any_pb2.Any]): - Unimplemented. - """ - class Importance(proto.Enum): - r"""Defines the importance of the data contained in the - operation. - - Values: - LOW (0): - Allows data caching, batching, and - aggregation. It provides higher performance with - higher data loss risk. - HIGH (1): - Disables data aggregation to minimize data - loss. It is for operations that contains - significant monetary value or audit trail. This - feature only applies to the client libraries. - """ - LOW = 0 - HIGH = 1 - - operation_id: str = proto.Field( - proto.STRING, - number=1, - ) - operation_name: str = proto.Field( - proto.STRING, - number=2, - ) - consumer_id: str = proto.Field( - proto.STRING, - number=3, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=6, - ) - metric_value_sets: MutableSequence[metric_value.MetricValueSet] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=metric_value.MetricValueSet, - ) - log_entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=log_entry.LogEntry, - ) - importance: Importance = proto.Field( - proto.ENUM, - number=11, - enum=Importance, - ) - extensions: MutableSequence[any_pb2.Any] = proto.RepeatedField( - proto.MESSAGE, - number=16, - message=any_pb2.Any, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/quota_controller.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/quota_controller.py deleted file mode 100644 index c3f3395..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/quota_controller.py +++ /dev/null @@ -1,328 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.servicecontrol_v1.types import metric_value -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.api.servicecontrol.v1', - manifest={ - 'AllocateQuotaRequest', - 'QuotaOperation', - 'AllocateQuotaResponse', - 'QuotaError', - }, -) - - -class AllocateQuotaRequest(proto.Message): - r"""Request message for the AllocateQuota method. - - Attributes: - service_name (str): - Name of the service as specified in the service - configuration. For example, ``"pubsub.googleapis.com"``. - - See [google.api.Service][google.api.Service] for the - definition of a service name. - allocate_operation (google.cloud.servicecontrol_v1.types.QuotaOperation): - Operation that describes the quota - allocation. - service_config_id (str): - Specifies which version of service - configuration should be used to process the - request. If unspecified or no matching version - can be found, the latest one will be used. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - allocate_operation: 'QuotaOperation' = proto.Field( - proto.MESSAGE, - number=2, - message='QuotaOperation', - ) - service_config_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class QuotaOperation(proto.Message): - r"""Represents information regarding a quota operation. - - Attributes: - operation_id (str): - Identity of the operation. This is expected to be unique - within the scope of the service that generated the - operation, and guarantees idempotency in case of retries. - - In order to ensure best performance and latency in the Quota - backends, operation_ids are optimally associated with time, - so that related operations can be accessed fast in storage. - For this reason, the recommended token for services that - intend to operate at a high QPS is Unix time in nanos + UUID - method_name (str): - Fully qualified name of the API method for which this quota - operation is requested. This name is used for matching quota - rules or metric rules and billing status rules defined in - service configuration. - - This field should not be set if any of the following is - true: (1) the quota operation is performed on non-API - resources. (2) quota_metrics is set because the caller is - doing quota override. - - Example of an RPC method name: - google.example.library.v1.LibraryService.CreateShelf - consumer_id (str): - Identity of the consumer for whom this quota operation is - being performed. - - This can be in one of the following formats: - project:, project_number:, - api_key:. - labels (MutableMapping[str, str]): - Labels describing the operation. - quota_metrics (MutableSequence[google.cloud.servicecontrol_v1.types.MetricValueSet]): - Represents information about this operation. Each - MetricValueSet corresponds to a metric defined in the - service configuration. The data type used in the - MetricValueSet must agree with the data type specified in - the metric definition. - - Within a single operation, it is not allowed to have more - than one MetricValue instances that have the same metric - names and identical label value combinations. If a request - has such duplicated MetricValue instances, the entire - request is rejected with an invalid argument error. - - This field is mutually exclusive with method_name. - quota_mode (google.cloud.servicecontrol_v1.types.QuotaOperation.QuotaMode): - Quota mode for this operation. - """ - class QuotaMode(proto.Enum): - r"""Supported quota modes. - - Values: - UNSPECIFIED (0): - Guard against implicit default. Must not be - used. - NORMAL (1): - For AllocateQuota request, allocates quota - for the amount specified in the service - configuration or specified using the quota - metrics. If the amount is higher than the - available quota, allocation error will be - returned and no quota will be allocated. - If multiple quotas are part of the request, and - one fails, none of the quotas are allocated or - released. - BEST_EFFORT (2): - The operation allocates quota for the amount specified in - the service configuration or specified using the quota - metrics. If the amount is higher than the available quota, - request does not fail but all available quota will be - allocated. For rate quota, BEST_EFFORT will continue to - deduct from other groups even if one does not have enough - quota. For allocation, it will find the minimum available - amount across all groups and deduct that amount from all the - affected groups. - CHECK_ONLY (3): - For AllocateQuota request, only checks if - there is enough quota available and does not - change the available quota. No lock is placed on - the available quota either. - QUERY_ONLY (4): - Unimplemented. When used in - AllocateQuotaRequest, this returns the effective - quota limit(s) in the response, and no quota - check will be performed. Not supported for other - requests, and even for AllocateQuotaRequest, - this is currently supported only for allowlisted - services. - ADJUST_ONLY (5): - The operation allocates quota for the amount - specified in the service configuration or - specified using the quota metrics. If the - requested amount is higher than the available - quota, request does not fail and remaining quota - would become negative (going over the limit). - Not supported for Rate Quota. - """ - UNSPECIFIED = 0 - NORMAL = 1 - BEST_EFFORT = 2 - CHECK_ONLY = 3 - QUERY_ONLY = 4 - ADJUST_ONLY = 5 - - operation_id: str = proto.Field( - proto.STRING, - number=1, - ) - method_name: str = proto.Field( - proto.STRING, - number=2, - ) - consumer_id: str = proto.Field( - proto.STRING, - number=3, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - quota_metrics: MutableSequence[metric_value.MetricValueSet] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=metric_value.MetricValueSet, - ) - quota_mode: QuotaMode = proto.Field( - proto.ENUM, - number=6, - enum=QuotaMode, - ) - - -class AllocateQuotaResponse(proto.Message): - r"""Response message for the AllocateQuota method. - - Attributes: - operation_id (str): - The same operation_id value used in the - AllocateQuotaRequest. Used for logging and diagnostics - purposes. - allocate_errors (MutableSequence[google.cloud.servicecontrol_v1.types.QuotaError]): - Indicates the decision of the allocate. - quota_metrics (MutableSequence[google.cloud.servicecontrol_v1.types.MetricValueSet]): - Quota metrics to indicate the result of allocation. - Depending on the request, one or more of the following - metrics will be included: - - 1. Per quota group or per quota metric incremental usage - will be specified using the following delta metric : - "serviceruntime.googleapis.com/api/consumer/quota_used_count" - - 2. The quota limit reached condition will be specified using - the following boolean metric : - "serviceruntime.googleapis.com/quota/exceeded". - service_config_id (str): - ID of the actual config used to process the - request. - """ - - operation_id: str = proto.Field( - proto.STRING, - number=1, - ) - allocate_errors: MutableSequence['QuotaError'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='QuotaError', - ) - quota_metrics: MutableSequence[metric_value.MetricValueSet] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=metric_value.MetricValueSet, - ) - service_config_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class QuotaError(proto.Message): - r"""Represents error information for - [QuotaOperation][google.api.servicecontrol.v1.QuotaOperation]. - - Attributes: - code (google.cloud.servicecontrol_v1.types.QuotaError.Code): - Error code. - subject (str): - Subject to whom this error applies. See the - specific enum for more details on this field. - For example, "clientip:" - or "project:". - description (str): - Free-form text that provides details on the - cause of the error. - status (google.rpc.status_pb2.Status): - Contains additional information about the quota error. If - available, ``status.code`` will be non zero. - """ - class Code(proto.Enum): - r"""Error codes related to project config validations are deprecated - since the quota controller methods do not perform these validations. - Instead services have to call the Check method, without - quota_properties field, to perform these validations before calling - the quota controller methods. These methods check only for project - deletion to be wipe out compliant. - - Values: - UNSPECIFIED (0): - This is never used. - RESOURCE_EXHAUSTED (8): - Quota allocation failed. Same as - [google.rpc.Code.RESOURCE_EXHAUSTED][google.rpc.Code.RESOURCE_EXHAUSTED]. - BILLING_NOT_ACTIVE (107): - Consumer cannot access the service because - the service requires active billing. - PROJECT_DELETED (108): - Consumer's project has been marked as deleted - (soft deletion). - API_KEY_INVALID (105): - Specified API key is invalid. - API_KEY_EXPIRED (112): - Specified API Key has expired. - """ - UNSPECIFIED = 0 - RESOURCE_EXHAUSTED = 8 - BILLING_NOT_ACTIVE = 107 - PROJECT_DELETED = 108 - API_KEY_INVALID = 105 - API_KEY_EXPIRED = 112 - - code: Code = proto.Field( - proto.ENUM, - number=1, - enum=Code, - ) - subject: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=4, - message=status_pb2.Status, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/service_controller.py b/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/service_controller.py deleted file mode 100644 index db95909..0000000 --- a/owl-bot-staging/v1/google/cloud/servicecontrol_v1/types/service_controller.py +++ /dev/null @@ -1,322 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.servicecontrol_v1.types import check_error -from google.cloud.servicecontrol_v1.types import operation as gas_operation -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.api.servicecontrol.v1', - manifest={ - 'CheckRequest', - 'CheckResponse', - 'ReportRequest', - 'ReportResponse', - }, -) - - -class CheckRequest(proto.Message): - r"""Request message for the Check method. - - Attributes: - service_name (str): - The service name as specified in its service configuration. - For example, ``"pubsub.googleapis.com"``. - - See - `google.api.Service `__ - for the definition of a service name. - operation (google.cloud.servicecontrol_v1.types.Operation): - The operation to be checked. - service_config_id (str): - Specifies which version of service - configuration should be used to process the - request. - If unspecified or no matching version can be - found, the latest one will be used. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - operation: gas_operation.Operation = proto.Field( - proto.MESSAGE, - number=2, - message=gas_operation.Operation, - ) - service_config_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class CheckResponse(proto.Message): - r"""Response message for the Check method. - - Attributes: - operation_id (str): - The same operation_id value used in the - [CheckRequest][google.api.servicecontrol.v1.CheckRequest]. - Used for logging and diagnostics purposes. - check_errors (MutableSequence[google.cloud.servicecontrol_v1.types.CheckError]): - Indicate the decision of the check. - If no check errors are present, the service - should process the operation. Otherwise the - service should use the list of errors to - determine the appropriate action. - service_config_id (str): - The actual config id used to process the - request. - service_rollout_id (str): - The current service rollout id used to - process the request. - check_info (google.cloud.servicecontrol_v1.types.CheckResponse.CheckInfo): - Feedback data returned from the server during - processing a Check request. - """ - - class CheckInfo(proto.Message): - r"""Contains additional information about the check operation. - - Attributes: - unused_arguments (MutableSequence[str]): - A list of fields and label keys that are - ignored by the server. The client doesn't need - to send them for following requests to improve - performance and allow better aggregation. - consumer_info (google.cloud.servicecontrol_v1.types.CheckResponse.ConsumerInfo): - Consumer info of this check. - """ - - unused_arguments: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - consumer_info: 'CheckResponse.ConsumerInfo' = proto.Field( - proto.MESSAGE, - number=2, - message='CheckResponse.ConsumerInfo', - ) - - class ConsumerInfo(proto.Message): - r"""``ConsumerInfo`` provides information about the consumer. - - Attributes: - project_number (int): - The Google cloud project number, e.g. - 1234567890. A value of 0 indicates no project - number is found. - NOTE: This field is deprecated after we support - flexible consumer id. New code should not depend - on this field anymore. - type_ (google.cloud.servicecontrol_v1.types.CheckResponse.ConsumerInfo.ConsumerType): - The type of the consumer which should have been defined in - `Google Resource - Manager `__. - consumer_number (int): - The consumer identity number, can be Google - cloud project number, folder number or - organization number e.g. 1234567890. A value of - 0 indicates no consumer number is found. - """ - class ConsumerType(proto.Enum): - r"""The type of the consumer as defined in `Google Resource - Manager `__. - - Values: - CONSUMER_TYPE_UNSPECIFIED (0): - This is never used. - PROJECT (1): - The consumer is a Google Cloud Project. - FOLDER (2): - The consumer is a Google Cloud Folder. - ORGANIZATION (3): - The consumer is a Google Cloud Organization. - SERVICE_SPECIFIC (4): - Service-specific resource container which is - defined by the service producer to offer their - users the ability to manage service control - functionalities at a finer level of granularity - than the PROJECT. - """ - CONSUMER_TYPE_UNSPECIFIED = 0 - PROJECT = 1 - FOLDER = 2 - ORGANIZATION = 3 - SERVICE_SPECIFIC = 4 - - project_number: int = proto.Field( - proto.INT64, - number=1, - ) - type_: 'CheckResponse.ConsumerInfo.ConsumerType' = proto.Field( - proto.ENUM, - number=2, - enum='CheckResponse.ConsumerInfo.ConsumerType', - ) - consumer_number: int = proto.Field( - proto.INT64, - number=3, - ) - - operation_id: str = proto.Field( - proto.STRING, - number=1, - ) - check_errors: MutableSequence[check_error.CheckError] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=check_error.CheckError, - ) - service_config_id: str = proto.Field( - proto.STRING, - number=5, - ) - service_rollout_id: str = proto.Field( - proto.STRING, - number=11, - ) - check_info: CheckInfo = proto.Field( - proto.MESSAGE, - number=6, - message=CheckInfo, - ) - - -class ReportRequest(proto.Message): - r"""Request message for the Report method. - - Attributes: - service_name (str): - The service name as specified in its service configuration. - For example, ``"pubsub.googleapis.com"``. - - See - `google.api.Service `__ - for the definition of a service name. - operations (MutableSequence[google.cloud.servicecontrol_v1.types.Operation]): - Operations to be reported. - - Typically the service should report one operation per - request. Putting multiple operations into a single request - is allowed, but should be used only when multiple operations - are natually available at the time of the report. - - There is no limit on the number of operations in the same - ReportRequest, however the ReportRequest size should be no - larger than 1MB. See - [ReportResponse.report_errors][google.api.servicecontrol.v1.ReportResponse.report_errors] - for partial failure behavior. - service_config_id (str): - Specifies which version of service config - should be used to process the request. - - If unspecified or no matching version can be - found, the latest one will be used. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - operations: MutableSequence[gas_operation.Operation] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=gas_operation.Operation, - ) - service_config_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ReportResponse(proto.Message): - r"""Response message for the Report method. - - Attributes: - report_errors (MutableSequence[google.cloud.servicecontrol_v1.types.ReportResponse.ReportError]): - Partial failures, one for each ``Operation`` in the request - that failed processing. There are three possible - combinations of the RPC status: - - 1. The combination of a successful RPC status and an empty - ``report_errors`` list indicates a complete success where - all ``Operations`` in the request are processed - successfully. - 2. The combination of a successful RPC status and a - non-empty ``report_errors`` list indicates a partial - success where some ``Operations`` in the request - succeeded. Each ``Operation`` that failed processing has - a corresponding item in this list. - 3. A failed RPC status indicates a general non-deterministic - failure. When this happens, it's impossible to know which - of the 'Operations' in the request succeeded or failed. - service_config_id (str): - The actual config id used to process the - request. - service_rollout_id (str): - The current service rollout id used to - process the request. - """ - - class ReportError(proto.Message): - r"""Represents the processing error of one - [Operation][google.api.servicecontrol.v1.Operation] in the request. - - Attributes: - operation_id (str): - The - [Operation.operation_id][google.api.servicecontrol.v1.Operation.operation_id] - value from the request. - status (google.rpc.status_pb2.Status): - Details of the error when processing the - [Operation][google.api.servicecontrol.v1.Operation]. - """ - - operation_id: str = proto.Field( - proto.STRING, - number=1, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - - report_errors: MutableSequence[ReportError] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ReportError, - ) - service_config_id: str = proto.Field( - proto.STRING, - number=2, - ) - service_rollout_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 574c5ae..0000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index b494ed9..0000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/servicecontrol_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_async.py b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_async.py deleted file mode 100644 index f879c88..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 code. DO NOT EDIT! -# -# Snippet for AllocateQuota -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-control - - -# [START servicecontrol_v1_generated_QuotaController_AllocateQuota_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import servicecontrol_v1 - - -async def sample_allocate_quota(): - # Create a client - client = servicecontrol_v1.QuotaControllerAsyncClient() - - # Initialize request argument(s) - request = servicecontrol_v1.AllocateQuotaRequest( - ) - - # Make the request - response = await client.allocate_quota(request=request) - - # Handle the response - print(response) - -# [END servicecontrol_v1_generated_QuotaController_AllocateQuota_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_sync.py b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_sync.py deleted file mode 100644 index 24c544f..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_quota_controller_allocate_quota_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 code. DO NOT EDIT! -# -# Snippet for AllocateQuota -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-control - - -# [START servicecontrol_v1_generated_QuotaController_AllocateQuota_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import servicecontrol_v1 - - -def sample_allocate_quota(): - # Create a client - client = servicecontrol_v1.QuotaControllerClient() - - # Initialize request argument(s) - request = servicecontrol_v1.AllocateQuotaRequest( - ) - - # Make the request - response = client.allocate_quota(request=request) - - # Handle the response - print(response) - -# [END servicecontrol_v1_generated_QuotaController_AllocateQuota_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_async.py b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_async.py deleted file mode 100644 index 15dc673..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 code. DO NOT EDIT! -# -# Snippet for Check -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-control - - -# [START servicecontrol_v1_generated_ServiceController_Check_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import servicecontrol_v1 - - -async def sample_check(): - # Create a client - client = servicecontrol_v1.ServiceControllerAsyncClient() - - # Initialize request argument(s) - request = servicecontrol_v1.CheckRequest( - ) - - # Make the request - response = await client.check(request=request) - - # Handle the response - print(response) - -# [END servicecontrol_v1_generated_ServiceController_Check_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_sync.py b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_sync.py deleted file mode 100644 index 4bc4b00..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_check_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 code. DO NOT EDIT! -# -# Snippet for Check -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-control - - -# [START servicecontrol_v1_generated_ServiceController_Check_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import servicecontrol_v1 - - -def sample_check(): - # Create a client - client = servicecontrol_v1.ServiceControllerClient() - - # Initialize request argument(s) - request = servicecontrol_v1.CheckRequest( - ) - - # Make the request - response = client.check(request=request) - - # Handle the response - print(response) - -# [END servicecontrol_v1_generated_ServiceController_Check_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_async.py b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_async.py deleted file mode 100644 index 811ea8e..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 code. DO NOT EDIT! -# -# Snippet for Report -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-control - - -# [START servicecontrol_v1_generated_ServiceController_Report_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import servicecontrol_v1 - - -async def sample_report(): - # Create a client - client = servicecontrol_v1.ServiceControllerAsyncClient() - - # Initialize request argument(s) - request = servicecontrol_v1.ReportRequest( - ) - - # Make the request - response = await client.report(request=request) - - # Handle the response - print(response) - -# [END servicecontrol_v1_generated_ServiceController_Report_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_sync.py b/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_sync.py deleted file mode 100644 index 687c7e0..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/servicecontrol_v1_generated_service_controller_report_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 code. DO NOT EDIT! -# -# Snippet for Report -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-control - - -# [START servicecontrol_v1_generated_ServiceController_Report_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import servicecontrol_v1 - - -def sample_report(): - # Create a client - client = servicecontrol_v1.ServiceControllerClient() - - # Initialize request argument(s) - request = servicecontrol_v1.ReportRequest( - ) - - # Make the request - response = client.report(request=request) - - # Handle the response - print(response) - -# [END servicecontrol_v1_generated_ServiceController_Report_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json deleted file mode 100644 index ae2dfb3..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json +++ /dev/null @@ -1,474 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.api.servicecontrol.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-service-control", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicecontrol_v1.QuotaControllerAsyncClient", - "shortName": "QuotaControllerAsyncClient" - }, - "fullName": "google.cloud.servicecontrol_v1.QuotaControllerAsyncClient.allocate_quota", - "method": { - "fullName": "google.api.servicecontrol.v1.QuotaController.AllocateQuota", - "service": { - "fullName": "google.api.servicecontrol.v1.QuotaController", - "shortName": "QuotaController" - }, - "shortName": "AllocateQuota" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicecontrol_v1.types.AllocateQuotaRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.servicecontrol_v1.types.AllocateQuotaResponse", - "shortName": "allocate_quota" - }, - "description": "Sample for AllocateQuota", - "file": "servicecontrol_v1_generated_quota_controller_allocate_quota_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicecontrol_v1_generated_QuotaController_AllocateQuota_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicecontrol_v1_generated_quota_controller_allocate_quota_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicecontrol_v1.QuotaControllerClient", - "shortName": "QuotaControllerClient" - }, - "fullName": "google.cloud.servicecontrol_v1.QuotaControllerClient.allocate_quota", - "method": { - "fullName": "google.api.servicecontrol.v1.QuotaController.AllocateQuota", - "service": { - "fullName": "google.api.servicecontrol.v1.QuotaController", - "shortName": "QuotaController" - }, - "shortName": "AllocateQuota" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicecontrol_v1.types.AllocateQuotaRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.servicecontrol_v1.types.AllocateQuotaResponse", - "shortName": "allocate_quota" - }, - "description": "Sample for AllocateQuota", - "file": "servicecontrol_v1_generated_quota_controller_allocate_quota_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicecontrol_v1_generated_QuotaController_AllocateQuota_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicecontrol_v1_generated_quota_controller_allocate_quota_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicecontrol_v1.ServiceControllerAsyncClient", - "shortName": "ServiceControllerAsyncClient" - }, - "fullName": "google.cloud.servicecontrol_v1.ServiceControllerAsyncClient.check", - "method": { - "fullName": "google.api.servicecontrol.v1.ServiceController.Check", - "service": { - "fullName": "google.api.servicecontrol.v1.ServiceController", - "shortName": "ServiceController" - }, - "shortName": "Check" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicecontrol_v1.types.CheckRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.servicecontrol_v1.types.CheckResponse", - "shortName": "check" - }, - "description": "Sample for Check", - "file": "servicecontrol_v1_generated_service_controller_check_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicecontrol_v1_generated_ServiceController_Check_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicecontrol_v1_generated_service_controller_check_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicecontrol_v1.ServiceControllerClient", - "shortName": "ServiceControllerClient" - }, - "fullName": "google.cloud.servicecontrol_v1.ServiceControllerClient.check", - "method": { - "fullName": "google.api.servicecontrol.v1.ServiceController.Check", - "service": { - "fullName": "google.api.servicecontrol.v1.ServiceController", - "shortName": "ServiceController" - }, - "shortName": "Check" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicecontrol_v1.types.CheckRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.servicecontrol_v1.types.CheckResponse", - "shortName": "check" - }, - "description": "Sample for Check", - "file": "servicecontrol_v1_generated_service_controller_check_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicecontrol_v1_generated_ServiceController_Check_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicecontrol_v1_generated_service_controller_check_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicecontrol_v1.ServiceControllerAsyncClient", - "shortName": "ServiceControllerAsyncClient" - }, - "fullName": "google.cloud.servicecontrol_v1.ServiceControllerAsyncClient.report", - "method": { - "fullName": "google.api.servicecontrol.v1.ServiceController.Report", - "service": { - "fullName": "google.api.servicecontrol.v1.ServiceController", - "shortName": "ServiceController" - }, - "shortName": "Report" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicecontrol_v1.types.ReportRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.servicecontrol_v1.types.ReportResponse", - "shortName": "report" - }, - "description": "Sample for Report", - "file": "servicecontrol_v1_generated_service_controller_report_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicecontrol_v1_generated_ServiceController_Report_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicecontrol_v1_generated_service_controller_report_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicecontrol_v1.ServiceControllerClient", - "shortName": "ServiceControllerClient" - }, - "fullName": "google.cloud.servicecontrol_v1.ServiceControllerClient.report", - "method": { - "fullName": "google.api.servicecontrol.v1.ServiceController.Report", - "service": { - "fullName": "google.api.servicecontrol.v1.ServiceController", - "shortName": "ServiceController" - }, - "shortName": "Report" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicecontrol_v1.types.ReportRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.servicecontrol_v1.types.ReportResponse", - "shortName": "report" - }, - "description": "Sample for Report", - "file": "servicecontrol_v1_generated_service_controller_report_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicecontrol_v1_generated_ServiceController_Report_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicecontrol_v1_generated_service_controller_report_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1/scripts/fixup_servicecontrol_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_servicecontrol_v1_keywords.py deleted file mode 100644 index 875c8ab..0000000 --- a/owl-bot-staging/v1/scripts/fixup_servicecontrol_v1_keywords.py +++ /dev/null @@ -1,178 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 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 servicecontrolCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'allocate_quota': ('service_name', 'allocate_operation', 'service_config_id', ), - 'check': ('service_name', 'operation', 'service_config_id', ), - 'report': ('service_name', 'operations', 'service_config_id', ), - } - - 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: a.keyword.value not 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=servicecontrolCallTransformer(), -): - """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 servicecontrol 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/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index 8108ffe..0000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-service-control' - - -description = "Google Cloud Service Control API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/servicecontrol/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-service-control" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/v1/testing/constraints-3.10.txt b/owl-bot-staging/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1/testing/constraints-3.11.txt b/owl-bot-staging/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1/testing/constraints-3.12.txt b/owl-bot-staging/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1/testing/constraints-3.7.txt b/owl-bot-staging/v1/testing/constraints-3.7.txt deleted file mode 100644 index 6c44adf..0000000 --- a/owl-bot-staging/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/v1/testing/constraints-3.8.txt b/owl-bot-staging/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1/testing/constraints-3.9.txt b/owl-bot-staging/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_quota_controller.py b/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_quota_controller.py deleted file mode 100644 index fa2e0a6..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_quota_controller.py +++ /dev/null @@ -1,1464 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api import distribution_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_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.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.servicecontrol_v1.services.quota_controller import QuotaControllerAsyncClient -from google.cloud.servicecontrol_v1.services.quota_controller import QuotaControllerClient -from google.cloud.servicecontrol_v1.services.quota_controller import transports -from google.cloud.servicecontrol_v1.types import distribution as gas_distribution -from google.cloud.servicecontrol_v1.types import metric_value -from google.cloud.servicecontrol_v1.types import quota_controller -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -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 QuotaControllerClient._get_default_mtls_endpoint(None) is None - assert QuotaControllerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert QuotaControllerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert QuotaControllerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert QuotaControllerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert QuotaControllerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (QuotaControllerClient, "grpc"), - (QuotaControllerAsyncClient, "grpc_asyncio"), - (QuotaControllerClient, "rest"), -]) -def test_quota_controller_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'servicecontrol.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://servicecontrol.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.QuotaControllerGrpcTransport, "grpc"), - (transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.QuotaControllerRestTransport, "rest"), -]) -def test_quota_controller_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (QuotaControllerClient, "grpc"), - (QuotaControllerAsyncClient, "grpc_asyncio"), - (QuotaControllerClient, "rest"), -]) -def test_quota_controller_client_from_service_account_file(client_class, transport_name): - creds = ga_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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'servicecontrol.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://servicecontrol.googleapis.com' - ) - - -def test_quota_controller_client_get_transport_class(): - transport = QuotaControllerClient.get_transport_class() - available_transports = [ - transports.QuotaControllerGrpcTransport, - transports.QuotaControllerRestTransport, - ] - assert transport in available_transports - - transport = QuotaControllerClient.get_transport_class("grpc") - assert transport == transports.QuotaControllerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (QuotaControllerClient, transports.QuotaControllerGrpcTransport, "grpc"), - (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio"), - (QuotaControllerClient, transports.QuotaControllerRestTransport, "rest"), -]) -@mock.patch.object(QuotaControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaControllerClient)) -@mock.patch.object(QuotaControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaControllerAsyncClient)) -def test_quota_controller_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(QuotaControllerClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_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(QuotaControllerClient, '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(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (QuotaControllerClient, transports.QuotaControllerGrpcTransport, "grpc", "true"), - (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (QuotaControllerClient, transports.QuotaControllerGrpcTransport, "grpc", "false"), - (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (QuotaControllerClient, transports.QuotaControllerRestTransport, "rest", "true"), - (QuotaControllerClient, transports.QuotaControllerRestTransport, "rest", "false"), -]) -@mock.patch.object(QuotaControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaControllerClient)) -@mock.patch.object(QuotaControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaControllerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_quota_controller_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: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - QuotaControllerClient, QuotaControllerAsyncClient -]) -@mock.patch.object(QuotaControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaControllerClient)) -@mock.patch.object(QuotaControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(QuotaControllerAsyncClient)) -def test_quota_controller_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (QuotaControllerClient, transports.QuotaControllerGrpcTransport, "grpc"), - (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio"), - (QuotaControllerClient, transports.QuotaControllerRestTransport, "rest"), -]) -def test_quota_controller_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (QuotaControllerClient, transports.QuotaControllerGrpcTransport, "grpc", grpc_helpers), - (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (QuotaControllerClient, transports.QuotaControllerRestTransport, "rest", None), -]) -def test_quota_controller_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_quota_controller_client_client_options_from_dict(): - with mock.patch('google.cloud.servicecontrol_v1.services.quota_controller.transports.QuotaControllerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = QuotaControllerClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (QuotaControllerClient, transports.QuotaControllerGrpcTransport, "grpc", grpc_helpers), - (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_quota_controller_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "servicecontrol.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', -), - scopes=None, - default_host="servicecontrol.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - quota_controller.AllocateQuotaRequest, - dict, -]) -def test_allocate_quota(request_type, transport: str = 'grpc'): - client = QuotaControllerClient( - credentials=ga_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.allocate_quota), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = quota_controller.AllocateQuotaResponse( - operation_id='operation_id_value', - service_config_id='service_config_id_value', - ) - response = client.allocate_quota(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == quota_controller.AllocateQuotaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, quota_controller.AllocateQuotaResponse) - assert response.operation_id == 'operation_id_value' - assert response.service_config_id == 'service_config_id_value' - - -def test_allocate_quota_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = QuotaControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.allocate_quota), - '__call__') as call: - client.allocate_quota() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == quota_controller.AllocateQuotaRequest() - -@pytest.mark.asyncio -async def test_allocate_quota_async(transport: str = 'grpc_asyncio', request_type=quota_controller.AllocateQuotaRequest): - client = QuotaControllerAsyncClient( - credentials=ga_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.allocate_quota), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(quota_controller.AllocateQuotaResponse( - operation_id='operation_id_value', - service_config_id='service_config_id_value', - )) - response = await client.allocate_quota(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == quota_controller.AllocateQuotaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, quota_controller.AllocateQuotaResponse) - assert response.operation_id == 'operation_id_value' - assert response.service_config_id == 'service_config_id_value' - - -@pytest.mark.asyncio -async def test_allocate_quota_async_from_dict(): - await test_allocate_quota_async(request_type=dict) - - -def test_allocate_quota_field_headers(): - client = QuotaControllerClient( - credentials=ga_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 = quota_controller.AllocateQuotaRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.allocate_quota), - '__call__') as call: - call.return_value = quota_controller.AllocateQuotaResponse() - client.allocate_quota(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', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_allocate_quota_field_headers_async(): - client = QuotaControllerAsyncClient( - credentials=ga_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 = quota_controller.AllocateQuotaRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.allocate_quota), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(quota_controller.AllocateQuotaResponse()) - await client.allocate_quota(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', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - quota_controller.AllocateQuotaRequest, - dict, -]) -def test_allocate_quota_rest(request_type): - client = QuotaControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = quota_controller.AllocateQuotaResponse( - operation_id='operation_id_value', - service_config_id='service_config_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = quota_controller.AllocateQuotaResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.allocate_quota(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, quota_controller.AllocateQuotaResponse) - assert response.operation_id == 'operation_id_value' - assert response.service_config_id == 'service_config_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_allocate_quota_rest_interceptors(null_interceptor): - transport = transports.QuotaControllerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.QuotaControllerRestInterceptor(), - ) - client = QuotaControllerClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.QuotaControllerRestInterceptor, "post_allocate_quota") as post, \ - mock.patch.object(transports.QuotaControllerRestInterceptor, "pre_allocate_quota") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = quota_controller.AllocateQuotaRequest.pb(quota_controller.AllocateQuotaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = quota_controller.AllocateQuotaResponse.to_json(quota_controller.AllocateQuotaResponse()) - - request = quota_controller.AllocateQuotaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = quota_controller.AllocateQuotaResponse() - - client.allocate_quota(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_allocate_quota_rest_bad_request(transport: str = 'rest', request_type=quota_controller.AllocateQuotaRequest): - client = QuotaControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.allocate_quota(request) - - -def test_allocate_quota_rest_error(): - client = QuotaControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.QuotaControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = QuotaControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.QuotaControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = QuotaControllerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.QuotaControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = QuotaControllerClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = QuotaControllerClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.QuotaControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = QuotaControllerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.QuotaControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = QuotaControllerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.QuotaControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.QuotaControllerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.QuotaControllerGrpcTransport, - transports.QuotaControllerGrpcAsyncIOTransport, - transports.QuotaControllerRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = QuotaControllerClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = QuotaControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.QuotaControllerGrpcTransport, - ) - -def test_quota_controller_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.QuotaControllerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_quota_controller_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.servicecontrol_v1.services.quota_controller.transports.QuotaControllerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.QuotaControllerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'allocate_quota', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_quota_controller_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.servicecontrol_v1.services.quota_controller.transports.QuotaControllerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.QuotaControllerTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', -), - quota_project_id="octopus", - ) - - -def test_quota_controller_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.servicecontrol_v1.services.quota_controller.transports.QuotaControllerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.QuotaControllerTransport() - adc.assert_called_once() - - -def test_quota_controller_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - QuotaControllerClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.QuotaControllerGrpcTransport, - transports.QuotaControllerGrpcAsyncIOTransport, - ], -) -def test_quota_controller_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/servicecontrol',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.QuotaControllerGrpcTransport, - transports.QuotaControllerGrpcAsyncIOTransport, - transports.QuotaControllerRestTransport, - ], -) -def test_quota_controller_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.QuotaControllerGrpcTransport, grpc_helpers), - (transports.QuotaControllerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_quota_controller_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "servicecontrol.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', -), - scopes=["1", "2"], - default_host="servicecontrol.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.QuotaControllerGrpcTransport, transports.QuotaControllerGrpcAsyncIOTransport]) -def test_quota_controller_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_quota_controller_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.QuotaControllerRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_quota_controller_host_no_port(transport_name): - client = QuotaControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicecontrol.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'servicecontrol.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://servicecontrol.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_quota_controller_host_with_port(transport_name): - client = QuotaControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicecontrol.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'servicecontrol.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://servicecontrol.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_quota_controller_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = QuotaControllerClient( - credentials=creds1, - transport=transport_name, - ) - client2 = QuotaControllerClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.allocate_quota._session - session2 = client2.transport.allocate_quota._session - assert session1 != session2 -def test_quota_controller_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.QuotaControllerGrpcTransport( - 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_quota_controller_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.QuotaControllerGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.QuotaControllerGrpcTransport, transports.QuotaControllerGrpcAsyncIOTransport]) -def test_quota_controller_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") 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 = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.QuotaControllerGrpcTransport, transports.QuotaControllerGrpcAsyncIOTransport]) -def test_quota_controller_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") 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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = QuotaControllerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = QuotaControllerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = QuotaControllerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = QuotaControllerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = QuotaControllerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = QuotaControllerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = QuotaControllerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = QuotaControllerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = QuotaControllerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = QuotaControllerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = QuotaControllerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = QuotaControllerClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = QuotaControllerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = QuotaControllerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = QuotaControllerClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.QuotaControllerTransport, '_prep_wrapped_messages') as prep: - client = QuotaControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.QuotaControllerTransport, '_prep_wrapped_messages') as prep: - transport_class = QuotaControllerClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = QuotaControllerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = QuotaControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = QuotaControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (QuotaControllerClient, transports.QuotaControllerGrpcTransport), - (QuotaControllerAsyncClient, transports.QuotaControllerGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_service_controller.py b/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_service_controller.py deleted file mode 100644 index 918b168..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/servicecontrol_v1/test_service_controller.py +++ /dev/null @@ -1,1740 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api import distribution_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_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.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.servicecontrol_v1.services.service_controller import ServiceControllerAsyncClient -from google.cloud.servicecontrol_v1.services.service_controller import ServiceControllerClient -from google.cloud.servicecontrol_v1.services.service_controller import transports -from google.cloud.servicecontrol_v1.types import check_error -from google.cloud.servicecontrol_v1.types import distribution as gas_distribution -from google.cloud.servicecontrol_v1.types import http_request -from google.cloud.servicecontrol_v1.types import log_entry -from google.cloud.servicecontrol_v1.types import metric_value -from google.cloud.servicecontrol_v1.types import operation -from google.cloud.servicecontrol_v1.types import service_controller -from google.logging.type import log_severity_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -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 ServiceControllerClient._get_default_mtls_endpoint(None) is None - assert ServiceControllerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ServiceControllerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ServiceControllerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ServiceControllerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ServiceControllerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ServiceControllerClient, "grpc"), - (ServiceControllerAsyncClient, "grpc_asyncio"), - (ServiceControllerClient, "rest"), -]) -def test_service_controller_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'servicecontrol.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://servicecontrol.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ServiceControllerGrpcTransport, "grpc"), - (transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ServiceControllerRestTransport, "rest"), -]) -def test_service_controller_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ServiceControllerClient, "grpc"), - (ServiceControllerAsyncClient, "grpc_asyncio"), - (ServiceControllerClient, "rest"), -]) -def test_service_controller_client_from_service_account_file(client_class, transport_name): - creds = ga_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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'servicecontrol.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://servicecontrol.googleapis.com' - ) - - -def test_service_controller_client_get_transport_class(): - transport = ServiceControllerClient.get_transport_class() - available_transports = [ - transports.ServiceControllerGrpcTransport, - transports.ServiceControllerRestTransport, - ] - assert transport in available_transports - - transport = ServiceControllerClient.get_transport_class("grpc") - assert transport == transports.ServiceControllerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc"), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio"), - (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest"), -]) -@mock.patch.object(ServiceControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerClient)) -@mock.patch.object(ServiceControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerAsyncClient)) -def test_service_controller_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(ServiceControllerClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_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(ServiceControllerClient, '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(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", "true"), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", "false"), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest", "true"), - (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest", "false"), -]) -@mock.patch.object(ServiceControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerClient)) -@mock.patch.object(ServiceControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_service_controller_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: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ServiceControllerClient, ServiceControllerAsyncClient -]) -@mock.patch.object(ServiceControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerClient)) -@mock.patch.object(ServiceControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerAsyncClient)) -def test_service_controller_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc"), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio"), - (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest"), -]) -def test_service_controller_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", grpc_helpers), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest", None), -]) -def test_service_controller_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_service_controller_client_client_options_from_dict(): - with mock.patch('google.cloud.servicecontrol_v1.services.service_controller.transports.ServiceControllerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ServiceControllerClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", grpc_helpers), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_service_controller_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "servicecontrol.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', -), - scopes=None, - default_host="servicecontrol.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - service_controller.CheckRequest, - dict, -]) -def test_check(request_type, transport: str = 'grpc'): - client = ServiceControllerClient( - credentials=ga_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.check), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_controller.CheckResponse( - operation_id='operation_id_value', - service_config_id='service_config_id_value', - service_rollout_id='service_rollout_id_value', - ) - response = client.check(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service_controller.CheckRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service_controller.CheckResponse) - assert response.operation_id == 'operation_id_value' - assert response.service_config_id == 'service_config_id_value' - assert response.service_rollout_id == 'service_rollout_id_value' - - -def test_check_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check), - '__call__') as call: - client.check() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service_controller.CheckRequest() - -@pytest.mark.asyncio -async def test_check_async(transport: str = 'grpc_asyncio', request_type=service_controller.CheckRequest): - client = ServiceControllerAsyncClient( - credentials=ga_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.check), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_controller.CheckResponse( - operation_id='operation_id_value', - service_config_id='service_config_id_value', - service_rollout_id='service_rollout_id_value', - )) - response = await client.check(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service_controller.CheckRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service_controller.CheckResponse) - assert response.operation_id == 'operation_id_value' - assert response.service_config_id == 'service_config_id_value' - assert response.service_rollout_id == 'service_rollout_id_value' - - -@pytest.mark.asyncio -async def test_check_async_from_dict(): - await test_check_async(request_type=dict) - - -def test_check_field_headers(): - client = ServiceControllerClient( - credentials=ga_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 = service_controller.CheckRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check), - '__call__') as call: - call.return_value = service_controller.CheckResponse() - client.check(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', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_check_field_headers_async(): - client = ServiceControllerAsyncClient( - credentials=ga_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 = service_controller.CheckRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_controller.CheckResponse()) - await client.check(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', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - service_controller.ReportRequest, - dict, -]) -def test_report(request_type, transport: str = 'grpc'): - client = ServiceControllerClient( - credentials=ga_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.report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_controller.ReportResponse( - service_config_id='service_config_id_value', - service_rollout_id='service_rollout_id_value', - ) - response = client.report(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service_controller.ReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service_controller.ReportResponse) - assert response.service_config_id == 'service_config_id_value' - assert response.service_rollout_id == 'service_rollout_id_value' - - -def test_report_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.report), - '__call__') as call: - client.report() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service_controller.ReportRequest() - -@pytest.mark.asyncio -async def test_report_async(transport: str = 'grpc_asyncio', request_type=service_controller.ReportRequest): - client = ServiceControllerAsyncClient( - credentials=ga_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.report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_controller.ReportResponse( - service_config_id='service_config_id_value', - service_rollout_id='service_rollout_id_value', - )) - response = await client.report(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service_controller.ReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service_controller.ReportResponse) - assert response.service_config_id == 'service_config_id_value' - assert response.service_rollout_id == 'service_rollout_id_value' - - -@pytest.mark.asyncio -async def test_report_async_from_dict(): - await test_report_async(request_type=dict) - - -def test_report_field_headers(): - client = ServiceControllerClient( - credentials=ga_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 = service_controller.ReportRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.report), - '__call__') as call: - call.return_value = service_controller.ReportResponse() - client.report(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', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_report_field_headers_async(): - client = ServiceControllerAsyncClient( - credentials=ga_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 = service_controller.ReportRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.report), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_controller.ReportResponse()) - await client.report(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', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - service_controller.CheckRequest, - dict, -]) -def test_check_rest(request_type): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service_controller.CheckResponse( - operation_id='operation_id_value', - service_config_id='service_config_id_value', - service_rollout_id='service_rollout_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = service_controller.CheckResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.check(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service_controller.CheckResponse) - assert response.operation_id == 'operation_id_value' - assert response.service_config_id == 'service_config_id_value' - assert response.service_rollout_id == 'service_rollout_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_check_rest_interceptors(null_interceptor): - transport = transports.ServiceControllerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceControllerRestInterceptor(), - ) - client = ServiceControllerClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ServiceControllerRestInterceptor, "post_check") as post, \ - mock.patch.object(transports.ServiceControllerRestInterceptor, "pre_check") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service_controller.CheckRequest.pb(service_controller.CheckRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = service_controller.CheckResponse.to_json(service_controller.CheckResponse()) - - request = service_controller.CheckRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service_controller.CheckResponse() - - client.check(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_check_rest_bad_request(transport: str = 'rest', request_type=service_controller.CheckRequest): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.check(request) - - -def test_check_rest_error(): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - service_controller.ReportRequest, - dict, -]) -def test_report_rest(request_type): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service_controller.ReportResponse( - service_config_id='service_config_id_value', - service_rollout_id='service_rollout_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = service_controller.ReportResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.report(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service_controller.ReportResponse) - assert response.service_config_id == 'service_config_id_value' - assert response.service_rollout_id == 'service_rollout_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_report_rest_interceptors(null_interceptor): - transport = transports.ServiceControllerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceControllerRestInterceptor(), - ) - client = ServiceControllerClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ServiceControllerRestInterceptor, "post_report") as post, \ - mock.patch.object(transports.ServiceControllerRestInterceptor, "pre_report") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service_controller.ReportRequest.pb(service_controller.ReportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = service_controller.ReportResponse.to_json(service_controller.ReportResponse()) - - request = service_controller.ReportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service_controller.ReportResponse() - - client.report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_report_rest_bad_request(transport: str = 'rest', request_type=service_controller.ReportRequest): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.report(request) - - -def test_report_rest_error(): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServiceControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServiceControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServiceControllerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ServiceControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServiceControllerClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServiceControllerClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ServiceControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServiceControllerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServiceControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ServiceControllerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServiceControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ServiceControllerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ServiceControllerGrpcTransport, - transports.ServiceControllerGrpcAsyncIOTransport, - transports.ServiceControllerRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ServiceControllerClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ServiceControllerGrpcTransport, - ) - -def test_service_controller_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ServiceControllerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_service_controller_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.servicecontrol_v1.services.service_controller.transports.ServiceControllerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ServiceControllerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'check', - 'report', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_service_controller_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.servicecontrol_v1.services.service_controller.transports.ServiceControllerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServiceControllerTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', -), - quota_project_id="octopus", - ) - - -def test_service_controller_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.servicecontrol_v1.services.service_controller.transports.ServiceControllerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServiceControllerTransport() - adc.assert_called_once() - - -def test_service_controller_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ServiceControllerClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServiceControllerGrpcTransport, - transports.ServiceControllerGrpcAsyncIOTransport, - ], -) -def test_service_controller_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/servicecontrol',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServiceControllerGrpcTransport, - transports.ServiceControllerGrpcAsyncIOTransport, - transports.ServiceControllerRestTransport, - ], -) -def test_service_controller_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ServiceControllerGrpcTransport, grpc_helpers), - (transports.ServiceControllerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_service_controller_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "servicecontrol.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', -), - scopes=["1", "2"], - default_host="servicecontrol.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ServiceControllerGrpcTransport, transports.ServiceControllerGrpcAsyncIOTransport]) -def test_service_controller_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_service_controller_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ServiceControllerRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_service_controller_host_no_port(transport_name): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicecontrol.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'servicecontrol.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://servicecontrol.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_service_controller_host_with_port(transport_name): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicecontrol.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'servicecontrol.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://servicecontrol.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_service_controller_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ServiceControllerClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ServiceControllerClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.check._session - session2 = client2.transport.check._session - assert session1 != session2 - session1 = client1.transport.report._session - session2 = client2.transport.report._session - assert session1 != session2 -def test_service_controller_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServiceControllerGrpcTransport( - 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_service_controller_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServiceControllerGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ServiceControllerGrpcTransport, transports.ServiceControllerGrpcAsyncIOTransport]) -def test_service_controller_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") 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 = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ServiceControllerGrpcTransport, transports.ServiceControllerGrpcAsyncIOTransport]) -def test_service_controller_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") 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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ServiceControllerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = ServiceControllerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceControllerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = ServiceControllerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = ServiceControllerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceControllerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ServiceControllerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = ServiceControllerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceControllerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = ServiceControllerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = ServiceControllerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceControllerClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ServiceControllerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = ServiceControllerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceControllerClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ServiceControllerTransport, '_prep_wrapped_messages') as prep: - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ServiceControllerTransport, '_prep_wrapped_messages') as prep: - transport_class = ServiceControllerClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ServiceControllerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc deleted file mode 100644 index db73969..0000000 --- a/owl-bot-staging/v2/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/servicecontrol/__init__.py - google/cloud/servicecontrol/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/v2/.flake8 b/owl-bot-staging/v2/.flake8 deleted file mode 100644 index 29227d4..0000000 --- a/owl-bot-staging/v2/.flake8 +++ /dev/null @@ -1,33 +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. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in deleted file mode 100644 index 732f0e2..0000000 --- a/owl-bot-staging/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/servicecontrol *.py -recursive-include google/cloud/servicecontrol_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst deleted file mode 100644 index 68e4838..0000000 --- a/owl-bot-staging/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Servicecontrol API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Servicecontrol API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2/docs/conf.py b/owl-bot-staging/v2/docs/conf.py deleted file mode 100644 index 4c7d6b4..0000000 --- a/owl-bot-staging/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# -# google-cloud-service-control documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-service-control" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-service-control-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-service-control.tex", - u"google-cloud-service-control Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-service-control", - u"Google Cloud Servicecontrol Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-service-control", - u"google-cloud-service-control Documentation", - author, - "google-cloud-service-control", - "GAPIC library for Google Cloud Servicecontrol API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst deleted file mode 100644 index d8d7f01..0000000 --- a/owl-bot-staging/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - servicecontrol_v2/services - servicecontrol_v2/types diff --git a/owl-bot-staging/v2/docs/servicecontrol_v2/service_controller.rst b/owl-bot-staging/v2/docs/servicecontrol_v2/service_controller.rst deleted file mode 100644 index 56ae69a..0000000 --- a/owl-bot-staging/v2/docs/servicecontrol_v2/service_controller.rst +++ /dev/null @@ -1,6 +0,0 @@ -ServiceController ------------------------------------ - -.. automodule:: google.cloud.servicecontrol_v2.services.service_controller - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/servicecontrol_v2/services.rst b/owl-bot-staging/v2/docs/servicecontrol_v2/services.rst deleted file mode 100644 index a56e496..0000000 --- a/owl-bot-staging/v2/docs/servicecontrol_v2/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Servicecontrol v2 API -=============================================== -.. toctree:: - :maxdepth: 2 - - service_controller diff --git a/owl-bot-staging/v2/docs/servicecontrol_v2/types.rst b/owl-bot-staging/v2/docs/servicecontrol_v2/types.rst deleted file mode 100644 index 804c27d..0000000 --- a/owl-bot-staging/v2/docs/servicecontrol_v2/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Servicecontrol v2 API -============================================ - -.. automodule:: google.cloud.servicecontrol_v2.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol/__init__.py b/owl-bot-staging/v2/google/cloud/servicecontrol/__init__.py deleted file mode 100644 index 07eacb8..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol/__init__.py +++ /dev/null @@ -1,37 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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.servicecontrol import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.servicecontrol_v2.services.service_controller.client import ServiceControllerClient -from google.cloud.servicecontrol_v2.services.service_controller.async_client import ServiceControllerAsyncClient - -from google.cloud.servicecontrol_v2.types.service_controller import CheckRequest -from google.cloud.servicecontrol_v2.types.service_controller import CheckResponse -from google.cloud.servicecontrol_v2.types.service_controller import ReportRequest -from google.cloud.servicecontrol_v2.types.service_controller import ReportResponse -from google.cloud.servicecontrol_v2.types.service_controller import ResourceInfo - -__all__ = ('ServiceControllerClient', - 'ServiceControllerAsyncClient', - 'CheckRequest', - 'CheckResponse', - 'ReportRequest', - 'ReportResponse', - 'ResourceInfo', -) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol/gapic_version.py b/owl-bot-staging/v2/google/cloud/servicecontrol/gapic_version.py deleted file mode 100644 index 405b1ce..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol/py.typed b/owl-bot-staging/v2/google/cloud/servicecontrol/py.typed deleted file mode 100644 index 3971a5d..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-service-control package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/__init__.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/__init__.py deleted file mode 100644 index ee69a77..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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.servicecontrol_v2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.service_controller import ServiceControllerClient -from .services.service_controller import ServiceControllerAsyncClient - -from .types.service_controller import CheckRequest -from .types.service_controller import CheckResponse -from .types.service_controller import ReportRequest -from .types.service_controller import ReportResponse -from .types.service_controller import ResourceInfo - -__all__ = ( - 'ServiceControllerAsyncClient', -'CheckRequest', -'CheckResponse', -'ReportRequest', -'ReportResponse', -'ResourceInfo', -'ServiceControllerClient', -) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_metadata.json deleted file mode 100644 index 5e12db8..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_metadata.json +++ /dev/null @@ -1,58 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.servicecontrol_v2", - "protoPackage": "google.api.servicecontrol.v2", - "schema": "1.0", - "services": { - "ServiceController": { - "clients": { - "grpc": { - "libraryClient": "ServiceControllerClient", - "rpcs": { - "Check": { - "methods": [ - "check" - ] - }, - "Report": { - "methods": [ - "report" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ServiceControllerAsyncClient", - "rpcs": { - "Check": { - "methods": [ - "check" - ] - }, - "Report": { - "methods": [ - "report" - ] - } - } - }, - "rest": { - "libraryClient": "ServiceControllerClient", - "rpcs": { - "Check": { - "methods": [ - "check" - ] - }, - "Report": { - "methods": [ - "report" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_version.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_version.py deleted file mode 100644 index 405b1ce..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/py.typed b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/py.typed deleted file mode 100644 index 3971a5d..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-service-control package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/__init__.py deleted file mode 100644 index e8e1c38..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/__init__.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/__init__.py deleted file mode 100644 index 187fc9e..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 .client import ServiceControllerClient -from .async_client import ServiceControllerAsyncClient - -__all__ = ( - 'ServiceControllerClient', - 'ServiceControllerAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/async_client.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/async_client.py deleted file mode 100644 index 4a682e8..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/async_client.py +++ /dev/null @@ -1,413 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.servicecontrol_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.servicecontrol_v2.types import service_controller -from google.rpc import status_pb2 # type: ignore -from .transports.base import ServiceControllerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ServiceControllerGrpcAsyncIOTransport -from .client import ServiceControllerClient - - -class ServiceControllerAsyncClient: - """`Service Control API - v2 `__ - - Private Preview. This feature is only available for approved - services. - - This API provides admission control and telemetry reporting for - services that are integrated with `Service - Infrastructure `__. - """ - - _client: ServiceControllerClient - - DEFAULT_ENDPOINT = ServiceControllerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ServiceControllerClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(ServiceControllerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ServiceControllerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ServiceControllerClient.common_folder_path) - parse_common_folder_path = staticmethod(ServiceControllerClient.parse_common_folder_path) - common_organization_path = staticmethod(ServiceControllerClient.common_organization_path) - parse_common_organization_path = staticmethod(ServiceControllerClient.parse_common_organization_path) - common_project_path = staticmethod(ServiceControllerClient.common_project_path) - parse_common_project_path = staticmethod(ServiceControllerClient.parse_common_project_path) - common_location_path = staticmethod(ServiceControllerClient.common_location_path) - parse_common_location_path = staticmethod(ServiceControllerClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServiceControllerAsyncClient: The constructed client. - """ - return ServiceControllerClient.from_service_account_info.__func__(ServiceControllerAsyncClient, info, *args, **kwargs) # type: ignore - - @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: - ServiceControllerAsyncClient: The constructed client. - """ - return ServiceControllerClient.from_service_account_file.__func__(ServiceControllerAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ServiceControllerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ServiceControllerTransport: - """Returns the transport used by the client instance. - - Returns: - ServiceControllerTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ServiceControllerClient).get_transport_class, type(ServiceControllerClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ServiceControllerTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the service controller 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, ~.ServiceControllerTransport]): 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 = ServiceControllerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def check(self, - request: Optional[Union[service_controller.CheckRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service_controller.CheckResponse: - r"""Private Preview. This feature is only available for approved - services. - - This method provides admission control for services that are - integrated with `Service - Infrastructure `__. - It checks whether an operation should be allowed based on the - service configuration and relevant policies. It must be called - before the operation is executed. For more information, see - `Admission - Control `__. - - NOTE: The admission control has an expected policy propagation - delay of 60s. The caller **must** not depend on the most recent - policy changes. - - NOTE: The admission control has a hard limit of 1 referenced - resources per call. If an operation refers to more than 1 - resources, the caller must call the Check method multiple times. - - This method requires the ``servicemanagement.services.check`` - permission on the specified service. For more information, see - `Service Control API Access - Control `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicecontrol_v2 - - async def sample_check(): - # Create a client - client = servicecontrol_v2.ServiceControllerAsyncClient() - - # Initialize request argument(s) - request = servicecontrol_v2.CheckRequest( - ) - - # Make the request - response = await client.check(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicecontrol_v2.types.CheckRequest, dict]]): - The request object. Request message for the Check method. - 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: - google.cloud.servicecontrol_v2.types.CheckResponse: - Response message for the Check - method. - - """ - # Create or coerce a protobuf request object. - request = service_controller.CheckRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.check, - default_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=5.0, - ), - default_timeout=5.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(( - ("service_name", request.service_name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def report(self, - request: Optional[Union[service_controller.ReportRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service_controller.ReportResponse: - r"""Private Preview. This feature is only available for approved - services. - - This method provides telemetry reporting for services that are - integrated with `Service - Infrastructure `__. - It reports a list of operations that have occurred on a service. - It must be called after the operations have been executed. For - more information, see `Telemetry - Reporting `__. - - NOTE: The telemetry reporting has a hard limit of 1000 - operations and 1MB per Report call. It is recommended to have no - more than 100 operations per call. - - This method requires the ``servicemanagement.services.report`` - permission on the specified service. For more information, see - `Service Control API Access - Control `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicecontrol_v2 - - async def sample_report(): - # Create a client - client = servicecontrol_v2.ServiceControllerAsyncClient() - - # Initialize request argument(s) - request = servicecontrol_v2.ReportRequest( - ) - - # Make the request - response = await client.report(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicecontrol_v2.types.ReportRequest, dict]]): - The request object. Request message for the Report - method. - 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: - google.cloud.servicecontrol_v2.types.ReportResponse: - Response message for the Report - method. If the request contains any - invalid data, the server returns an RPC - error. - - """ - # Create or coerce a protobuf request object. - request = service_controller.ReportRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.report, - default_timeout=None, - 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(( - ("service_name", request.service_name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ServiceControllerAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/client.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/client.py deleted file mode 100644 index 3dca0b9..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/client.py +++ /dev/null @@ -1,604 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.servicecontrol_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.servicecontrol_v2.types import service_controller -from google.rpc import status_pb2 # type: ignore -from .transports.base import ServiceControllerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ServiceControllerGrpcTransport -from .transports.grpc_asyncio import ServiceControllerGrpcAsyncIOTransport -from .transports.rest import ServiceControllerRestTransport - - -class ServiceControllerClientMeta(type): - """Metaclass for the ServiceController 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[ServiceControllerTransport]] - _transport_registry["grpc"] = ServiceControllerGrpcTransport - _transport_registry["grpc_asyncio"] = ServiceControllerGrpcAsyncIOTransport - _transport_registry["rest"] = ServiceControllerRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ServiceControllerTransport]: - """Returns 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 ServiceControllerClient(metaclass=ServiceControllerClientMeta): - """`Service Control API - v2 `__ - - Private Preview. This feature is only available for approved - services. - - This API provides admission control and telemetry reporting for - services that are integrated with `Service - Infrastructure `__. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - 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 = "servicecontrol.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServiceControllerClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @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: - ServiceControllerClient: 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) -> ServiceControllerTransport: - """Returns the transport used by the client instance. - - Returns: - ServiceControllerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @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: - """Returns 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: - """Returns 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: - """Returns 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: - """Returns 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 {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ServiceControllerTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the service controller 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, ServiceControllerTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ServiceControllerTransport): - # transport is a ServiceControllerTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - 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, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def check(self, - request: Optional[Union[service_controller.CheckRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service_controller.CheckResponse: - r"""Private Preview. This feature is only available for approved - services. - - This method provides admission control for services that are - integrated with `Service - Infrastructure `__. - It checks whether an operation should be allowed based on the - service configuration and relevant policies. It must be called - before the operation is executed. For more information, see - `Admission - Control `__. - - NOTE: The admission control has an expected policy propagation - delay of 60s. The caller **must** not depend on the most recent - policy changes. - - NOTE: The admission control has a hard limit of 1 referenced - resources per call. If an operation refers to more than 1 - resources, the caller must call the Check method multiple times. - - This method requires the ``servicemanagement.services.check`` - permission on the specified service. For more information, see - `Service Control API Access - Control `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicecontrol_v2 - - def sample_check(): - # Create a client - client = servicecontrol_v2.ServiceControllerClient() - - # Initialize request argument(s) - request = servicecontrol_v2.CheckRequest( - ) - - # Make the request - response = client.check(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicecontrol_v2.types.CheckRequest, dict]): - The request object. Request message for the Check method. - 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: - google.cloud.servicecontrol_v2.types.CheckResponse: - Response message for the Check - method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a service_controller.CheckRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service_controller.CheckRequest): - request = service_controller.CheckRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.check] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def report(self, - request: Optional[Union[service_controller.ReportRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service_controller.ReportResponse: - r"""Private Preview. This feature is only available for approved - services. - - This method provides telemetry reporting for services that are - integrated with `Service - Infrastructure `__. - It reports a list of operations that have occurred on a service. - It must be called after the operations have been executed. For - more information, see `Telemetry - Reporting `__. - - NOTE: The telemetry reporting has a hard limit of 1000 - operations and 1MB per Report call. It is recommended to have no - more than 100 operations per call. - - This method requires the ``servicemanagement.services.report`` - permission on the specified service. For more information, see - `Service Control API Access - Control `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicecontrol_v2 - - def sample_report(): - # Create a client - client = servicecontrol_v2.ServiceControllerClient() - - # Initialize request argument(s) - request = servicecontrol_v2.ReportRequest( - ) - - # Make the request - response = client.report(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicecontrol_v2.types.ReportRequest, dict]): - The request object. Request message for the Report - method. - 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: - google.cloud.servicecontrol_v2.types.ReportResponse: - Response message for the Report - method. If the request contains any - invalid data, the server returns an RPC - error. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a service_controller.ReportRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service_controller.ReportRequest): - request = service_controller.ReportRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.report] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ServiceControllerClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ServiceControllerClient", -) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/__init__.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/__init__.py deleted file mode 100644 index ad7b8b5..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ServiceControllerTransport -from .grpc import ServiceControllerGrpcTransport -from .grpc_asyncio import ServiceControllerGrpcAsyncIOTransport -from .rest import ServiceControllerRestTransport -from .rest import ServiceControllerRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ServiceControllerTransport]] -_transport_registry['grpc'] = ServiceControllerGrpcTransport -_transport_registry['grpc_asyncio'] = ServiceControllerGrpcAsyncIOTransport -_transport_registry['rest'] = ServiceControllerRestTransport - -__all__ = ( - 'ServiceControllerTransport', - 'ServiceControllerGrpcTransport', - 'ServiceControllerGrpcAsyncIOTransport', - 'ServiceControllerRestTransport', - 'ServiceControllerRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/base.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/base.py deleted file mode 100644 index 55cd0e9..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/base.py +++ /dev/null @@ -1,169 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.servicecontrol_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.servicecontrol_v2.types import service_controller - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ServiceControllerTransport(abc.ABC): - """Abstract transport class for ServiceController.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', - ) - - DEFAULT_HOST: str = 'servicecontrol.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **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. - scopes (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. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.check: gapic_v1.method.wrap_method( - self.check, - default_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=5.0, - ), - default_timeout=5.0, - client_info=client_info, - ), - self.report: gapic_v1.method.wrap_method( - self.report, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def check(self) -> Callable[ - [service_controller.CheckRequest], - Union[ - service_controller.CheckResponse, - Awaitable[service_controller.CheckResponse] - ]]: - raise NotImplementedError() - - @property - def report(self) -> Callable[ - [service_controller.ReportRequest], - Union[ - service_controller.ReportResponse, - Awaitable[service_controller.ReportResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ServiceControllerTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc.py deleted file mode 100644 index 779f374..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc.py +++ /dev/null @@ -1,339 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.servicecontrol_v2.types import service_controller -from .base import ServiceControllerTransport, DEFAULT_CLIENT_INFO - - -class ServiceControllerGrpcTransport(ServiceControllerTransport): - """gRPC backend transport for ServiceController. - - `Service Control API - v2 `__ - - Private Preview. This feature is only available for approved - services. - - This API provides admission control and telemetry reporting for - services that are integrated with `Service - Infrastructure `__. - - 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 = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> 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 application 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 the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` 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. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - 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._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - 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. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def check(self) -> Callable[ - [service_controller.CheckRequest], - service_controller.CheckResponse]: - r"""Return a callable for the check method over gRPC. - - Private Preview. This feature is only available for approved - services. - - This method provides admission control for services that are - integrated with `Service - Infrastructure `__. - It checks whether an operation should be allowed based on the - service configuration and relevant policies. It must be called - before the operation is executed. For more information, see - `Admission - Control `__. - - NOTE: The admission control has an expected policy propagation - delay of 60s. The caller **must** not depend on the most recent - policy changes. - - NOTE: The admission control has a hard limit of 1 referenced - resources per call. If an operation refers to more than 1 - resources, the caller must call the Check method multiple times. - - This method requires the ``servicemanagement.services.check`` - permission on the specified service. For more information, see - `Service Control API Access - Control `__. - - Returns: - Callable[[~.CheckRequest], - ~.CheckResponse]: - 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 'check' not in self._stubs: - self._stubs['check'] = self.grpc_channel.unary_unary( - '/google.api.servicecontrol.v2.ServiceController/Check', - request_serializer=service_controller.CheckRequest.serialize, - response_deserializer=service_controller.CheckResponse.deserialize, - ) - return self._stubs['check'] - - @property - def report(self) -> Callable[ - [service_controller.ReportRequest], - service_controller.ReportResponse]: - r"""Return a callable for the report method over gRPC. - - Private Preview. This feature is only available for approved - services. - - This method provides telemetry reporting for services that are - integrated with `Service - Infrastructure `__. - It reports a list of operations that have occurred on a service. - It must be called after the operations have been executed. For - more information, see `Telemetry - Reporting `__. - - NOTE: The telemetry reporting has a hard limit of 1000 - operations and 1MB per Report call. It is recommended to have no - more than 100 operations per call. - - This method requires the ``servicemanagement.services.report`` - permission on the specified service. For more information, see - `Service Control API Access - Control `__. - - Returns: - Callable[[~.ReportRequest], - ~.ReportResponse]: - 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 'report' not in self._stubs: - self._stubs['report'] = self.grpc_channel.unary_unary( - '/google.api.servicecontrol.v2.ServiceController/Report', - request_serializer=service_controller.ReportRequest.serialize, - response_deserializer=service_controller.ReportResponse.deserialize, - ) - return self._stubs['report'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ServiceControllerGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc_asyncio.py deleted file mode 100644 index 8f7a6eb..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/grpc_asyncio.py +++ /dev/null @@ -1,338 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_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.servicecontrol_v2.types import service_controller -from .base import ServiceControllerTransport, DEFAULT_CLIENT_INFO -from .grpc import ServiceControllerGrpcTransport - - -class ServiceControllerGrpcAsyncIOTransport(ServiceControllerTransport): - """gRPC AsyncIO backend transport for ServiceController. - - `Service Control API - v2 `__ - - Private Preview. This feature is only available for approved - services. - - This API provides admission control and telemetry reporting for - services that are integrated with `Service - Infrastructure `__. - - 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 = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (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. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> 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 application 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 the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` 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. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - 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._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @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 check(self) -> Callable[ - [service_controller.CheckRequest], - Awaitable[service_controller.CheckResponse]]: - r"""Return a callable for the check method over gRPC. - - Private Preview. This feature is only available for approved - services. - - This method provides admission control for services that are - integrated with `Service - Infrastructure `__. - It checks whether an operation should be allowed based on the - service configuration and relevant policies. It must be called - before the operation is executed. For more information, see - `Admission - Control `__. - - NOTE: The admission control has an expected policy propagation - delay of 60s. The caller **must** not depend on the most recent - policy changes. - - NOTE: The admission control has a hard limit of 1 referenced - resources per call. If an operation refers to more than 1 - resources, the caller must call the Check method multiple times. - - This method requires the ``servicemanagement.services.check`` - permission on the specified service. For more information, see - `Service Control API Access - Control `__. - - Returns: - Callable[[~.CheckRequest], - Awaitable[~.CheckResponse]]: - 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 'check' not in self._stubs: - self._stubs['check'] = self.grpc_channel.unary_unary( - '/google.api.servicecontrol.v2.ServiceController/Check', - request_serializer=service_controller.CheckRequest.serialize, - response_deserializer=service_controller.CheckResponse.deserialize, - ) - return self._stubs['check'] - - @property - def report(self) -> Callable[ - [service_controller.ReportRequest], - Awaitable[service_controller.ReportResponse]]: - r"""Return a callable for the report method over gRPC. - - Private Preview. This feature is only available for approved - services. - - This method provides telemetry reporting for services that are - integrated with `Service - Infrastructure `__. - It reports a list of operations that have occurred on a service. - It must be called after the operations have been executed. For - more information, see `Telemetry - Reporting `__. - - NOTE: The telemetry reporting has a hard limit of 1000 - operations and 1MB per Report call. It is recommended to have no - more than 100 operations per call. - - This method requires the ``servicemanagement.services.report`` - permission on the specified service. For more information, see - `Service Control API Access - Control `__. - - Returns: - Callable[[~.ReportRequest], - Awaitable[~.ReportResponse]]: - 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 'report' not in self._stubs: - self._stubs['report'] = self.grpc_channel.unary_unary( - '/google.api.servicecontrol.v2.ServiceController/Report', - request_serializer=service_controller.ReportRequest.serialize, - response_deserializer=service_controller.ReportResponse.deserialize, - ) - return self._stubs['report'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ServiceControllerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/rest.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/rest.py deleted file mode 100644 index ce49c01..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/services/service_controller/transports/rest.py +++ /dev/null @@ -1,415 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.servicecontrol_v2.types import service_controller - -from .base import ServiceControllerTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ServiceControllerRestInterceptor: - """Interceptor for ServiceController. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the ServiceControllerRestTransport. - - .. code-block:: python - class MyCustomServiceControllerInterceptor(ServiceControllerRestInterceptor): - def pre_check(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_check(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_report(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_report(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ServiceControllerRestTransport(interceptor=MyCustomServiceControllerInterceptor()) - client = ServiceControllerClient(transport=transport) - - - """ - def pre_check(self, request: service_controller.CheckRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_controller.CheckRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for check - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceController server. - """ - return request, metadata - - def post_check(self, response: service_controller.CheckResponse) -> service_controller.CheckResponse: - """Post-rpc interceptor for check - - Override in a subclass to manipulate the response - after it is returned by the ServiceController server but before - it is returned to user code. - """ - return response - def pre_report(self, request: service_controller.ReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service_controller.ReportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for report - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceController server. - """ - return request, metadata - - def post_report(self, response: service_controller.ReportResponse) -> service_controller.ReportResponse: - """Post-rpc interceptor for report - - Override in a subclass to manipulate the response - after it is returned by the ServiceController server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ServiceControllerRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ServiceControllerRestInterceptor - - -class ServiceControllerRestTransport(ServiceControllerTransport): - """REST backend transport for ServiceController. - - `Service Control API - v2 `__ - - Private Preview. This feature is only available for approved - services. - - This API provides admission control and telemetry reporting for - services that are integrated with `Service - Infrastructure `__. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'servicecontrol.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[ServiceControllerRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP 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 are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ServiceControllerRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _Check(ServiceControllerRestStub): - def __hash__(self): - return hash("Check") - - def __call__(self, - request: service_controller.CheckRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service_controller.CheckResponse: - r"""Call the check method over HTTP. - - Args: - request (~.service_controller.CheckRequest): - The request object. Request message for the Check method. - 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: - ~.service_controller.CheckResponse: - Response message for the Check - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/services/{service_name}:check', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_check(request, metadata) - pb_request = service_controller.CheckRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service_controller.CheckResponse() - pb_resp = service_controller.CheckResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_check(resp) - return resp - - class _Report(ServiceControllerRestStub): - def __hash__(self): - return hash("Report") - - def __call__(self, - request: service_controller.ReportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service_controller.ReportResponse: - r"""Call the report method over HTTP. - - Args: - request (~.service_controller.ReportRequest): - The request object. Request message for the Report - method. - 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: - ~.service_controller.ReportResponse: - Response message for the Report - method. If the request contains any - invalid data, the server returns an RPC - error. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/services/{service_name}:report', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_report(request, metadata) - pb_request = service_controller.ReportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service_controller.ReportResponse() - pb_resp = service_controller.ReportResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_report(resp) - return resp - - @property - def check(self) -> Callable[ - [service_controller.CheckRequest], - service_controller.CheckResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Check(self._session, self._host, self._interceptor) # type: ignore - - @property - def report(self) -> Callable[ - [service_controller.ReportRequest], - service_controller.ReportResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Report(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ServiceControllerRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/__init__.py deleted file mode 100644 index a81eb58..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 .service_controller import ( - CheckRequest, - CheckResponse, - ReportRequest, - ReportResponse, - ResourceInfo, -) - -__all__ = ( - 'CheckRequest', - 'CheckResponse', - 'ReportRequest', - 'ReportResponse', - 'ResourceInfo', -) diff --git a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/service_controller.py b/owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/service_controller.py deleted file mode 100644 index df64d66..0000000 --- a/owl-bot-staging/v2/google/cloud/servicecontrol_v2/types/service_controller.py +++ /dev/null @@ -1,216 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.rpc import status_pb2 # type: ignore -from google.rpc.context import attribute_context_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.api.servicecontrol.v2', - manifest={ - 'CheckRequest', - 'ResourceInfo', - 'CheckResponse', - 'ReportRequest', - 'ReportResponse', - }, -) - - -class CheckRequest(proto.Message): - r"""Request message for the Check method. - - Attributes: - service_name (str): - The service name as specified in its service configuration. - For example, ``"pubsub.googleapis.com"``. - - See - `google.api.Service `__ - for the definition of a service name. - service_config_id (str): - Specifies the version of the service - configuration that should be used to process the - request. Must not be empty. Set this field to - 'latest' to specify using the latest - configuration. - attributes (google.rpc.context.attribute_context_pb2.AttributeContext): - Describes attributes about the operation - being executed by the service. - resources (MutableSequence[google.cloud.servicecontrol_v2.types.ResourceInfo]): - Describes the resources and the policies - applied to each resource. - flags (str): - Optional. Contains a comma-separated list of - flags. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - service_config_id: str = proto.Field( - proto.STRING, - number=2, - ) - attributes: attribute_context_pb2.AttributeContext = proto.Field( - proto.MESSAGE, - number=3, - message=attribute_context_pb2.AttributeContext, - ) - resources: MutableSequence['ResourceInfo'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='ResourceInfo', - ) - flags: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ResourceInfo(proto.Message): - r"""Describes a resource referenced in the request. - - Attributes: - name (str): - The name of the resource referenced in the - request. - type_ (str): - The resource type in the format of - "{service}/{kind}". - permission (str): - The resource permission needed for this - request. The format must be - "{service}/{plural}.{verb}". - container (str): - Optional. The identifier of the container of this resource. - For Google Cloud APIs, the resource container must be one of - the following formats: - - ``projects/`` - - ``folders/`` - - ``organizations/`` For the policy - enforcement on the container level (VPCSC and Location - Policy check), this field takes precedence on the container - extracted from name when presents. - location (str): - Optional. The location of the resource. The - value must be a valid zone, region or - multiregion. For example: "europe-west4" or - "northamerica-northeast1-a". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - permission: str = proto.Field( - proto.STRING, - number=3, - ) - container: str = proto.Field( - proto.STRING, - number=4, - ) - location: str = proto.Field( - proto.STRING, - number=5, - ) - - -class CheckResponse(proto.Message): - r"""Response message for the Check method. - - Attributes: - status (google.rpc.status_pb2.Status): - Operation is allowed when this field is not set. Any - non-'OK' status indicates a denial; - [google.rpc.Status.details][google.rpc.Status.details] would - contain additional details about the denial. - headers (MutableMapping[str, str]): - Returns a set of request contexts generated from the - ``CheckRequest``. - """ - - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - headers: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - -class ReportRequest(proto.Message): - r"""Request message for the Report method. - - Attributes: - service_name (str): - The service name as specified in its service configuration. - For example, ``"pubsub.googleapis.com"``. - - See - `google.api.Service `__ - for the definition of a service name. - service_config_id (str): - Specifies the version of the service - configuration that should be used to process the - request. Must not be empty. Set this field to - 'latest' to specify using the latest - configuration. - operations (MutableSequence[google.rpc.context.attribute_context_pb2.AttributeContext]): - Describes the list of operations to be - reported. Each operation is represented as an - AttributeContext, and contains all attributes - around an API access. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - service_config_id: str = proto.Field( - proto.STRING, - number=2, - ) - operations: MutableSequence[attribute_context_pb2.AttributeContext] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=attribute_context_pb2.AttributeContext, - ) - - -class ReportResponse(proto.Message): - r"""Response message for the Report method. - If the request contains any invalid data, the server returns an - RPC error. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini deleted file mode 100644 index 574c5ae..0000000 --- a/owl-bot-staging/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py deleted file mode 100644 index f213da3..0000000 --- a/owl-bot-staging/v2/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/servicecontrol_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_async.py b/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_async.py deleted file mode 100644 index e735fb7..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 code. DO NOT EDIT! -# -# Snippet for Check -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-control - - -# [START servicecontrol_v2_generated_ServiceController_Check_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import servicecontrol_v2 - - -async def sample_check(): - # Create a client - client = servicecontrol_v2.ServiceControllerAsyncClient() - - # Initialize request argument(s) - request = servicecontrol_v2.CheckRequest( - ) - - # Make the request - response = await client.check(request=request) - - # Handle the response - print(response) - -# [END servicecontrol_v2_generated_ServiceController_Check_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_sync.py b/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_sync.py deleted file mode 100644 index 99e85b9..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_check_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 code. DO NOT EDIT! -# -# Snippet for Check -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-control - - -# [START servicecontrol_v2_generated_ServiceController_Check_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import servicecontrol_v2 - - -def sample_check(): - # Create a client - client = servicecontrol_v2.ServiceControllerClient() - - # Initialize request argument(s) - request = servicecontrol_v2.CheckRequest( - ) - - # Make the request - response = client.check(request=request) - - # Handle the response - print(response) - -# [END servicecontrol_v2_generated_ServiceController_Check_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_async.py b/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_async.py deleted file mode 100644 index 78ee2e1..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 code. DO NOT EDIT! -# -# Snippet for Report -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-control - - -# [START servicecontrol_v2_generated_ServiceController_Report_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import servicecontrol_v2 - - -async def sample_report(): - # Create a client - client = servicecontrol_v2.ServiceControllerAsyncClient() - - # Initialize request argument(s) - request = servicecontrol_v2.ReportRequest( - ) - - # Make the request - response = await client.report(request=request) - - # Handle the response - print(response) - -# [END servicecontrol_v2_generated_ServiceController_Report_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_sync.py b/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_sync.py deleted file mode 100644 index 6065f65..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/servicecontrol_v2_generated_service_controller_report_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 code. DO NOT EDIT! -# -# Snippet for Report -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-control - - -# [START servicecontrol_v2_generated_ServiceController_Report_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import servicecontrol_v2 - - -def sample_report(): - # Create a client - client = servicecontrol_v2.ServiceControllerClient() - - # Initialize request argument(s) - request = servicecontrol_v2.ReportRequest( - ) - - # Make the request - response = client.report(request=request) - - # Handle the response - print(response) - -# [END servicecontrol_v2_generated_ServiceController_Report_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json deleted file mode 100644 index 2b78179..0000000 --- a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json +++ /dev/null @@ -1,321 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.api.servicecontrol.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-cloud-service-control", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicecontrol_v2.ServiceControllerAsyncClient", - "shortName": "ServiceControllerAsyncClient" - }, - "fullName": "google.cloud.servicecontrol_v2.ServiceControllerAsyncClient.check", - "method": { - "fullName": "google.api.servicecontrol.v2.ServiceController.Check", - "service": { - "fullName": "google.api.servicecontrol.v2.ServiceController", - "shortName": "ServiceController" - }, - "shortName": "Check" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicecontrol_v2.types.CheckRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.servicecontrol_v2.types.CheckResponse", - "shortName": "check" - }, - "description": "Sample for Check", - "file": "servicecontrol_v2_generated_service_controller_check_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicecontrol_v2_generated_ServiceController_Check_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicecontrol_v2_generated_service_controller_check_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicecontrol_v2.ServiceControllerClient", - "shortName": "ServiceControllerClient" - }, - "fullName": "google.cloud.servicecontrol_v2.ServiceControllerClient.check", - "method": { - "fullName": "google.api.servicecontrol.v2.ServiceController.Check", - "service": { - "fullName": "google.api.servicecontrol.v2.ServiceController", - "shortName": "ServiceController" - }, - "shortName": "Check" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicecontrol_v2.types.CheckRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.servicecontrol_v2.types.CheckResponse", - "shortName": "check" - }, - "description": "Sample for Check", - "file": "servicecontrol_v2_generated_service_controller_check_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicecontrol_v2_generated_ServiceController_Check_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicecontrol_v2_generated_service_controller_check_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicecontrol_v2.ServiceControllerAsyncClient", - "shortName": "ServiceControllerAsyncClient" - }, - "fullName": "google.cloud.servicecontrol_v2.ServiceControllerAsyncClient.report", - "method": { - "fullName": "google.api.servicecontrol.v2.ServiceController.Report", - "service": { - "fullName": "google.api.servicecontrol.v2.ServiceController", - "shortName": "ServiceController" - }, - "shortName": "Report" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicecontrol_v2.types.ReportRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.servicecontrol_v2.types.ReportResponse", - "shortName": "report" - }, - "description": "Sample for Report", - "file": "servicecontrol_v2_generated_service_controller_report_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicecontrol_v2_generated_ServiceController_Report_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicecontrol_v2_generated_service_controller_report_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicecontrol_v2.ServiceControllerClient", - "shortName": "ServiceControllerClient" - }, - "fullName": "google.cloud.servicecontrol_v2.ServiceControllerClient.report", - "method": { - "fullName": "google.api.servicecontrol.v2.ServiceController.Report", - "service": { - "fullName": "google.api.servicecontrol.v2.ServiceController", - "shortName": "ServiceController" - }, - "shortName": "Report" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicecontrol_v2.types.ReportRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.servicecontrol_v2.types.ReportResponse", - "shortName": "report" - }, - "description": "Sample for Report", - "file": "servicecontrol_v2_generated_service_controller_report_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicecontrol_v2_generated_ServiceController_Report_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicecontrol_v2_generated_service_controller_report_sync.py" - } - ] -} diff --git a/owl-bot-staging/v2/scripts/fixup_servicecontrol_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_servicecontrol_v2_keywords.py deleted file mode 100644 index f15a780..0000000 --- a/owl-bot-staging/v2/scripts/fixup_servicecontrol_v2_keywords.py +++ /dev/null @@ -1,177 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 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 servicecontrolCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'check': ('service_name', 'service_config_id', 'attributes', 'resources', 'flags', ), - 'report': ('service_name', 'service_config_id', 'operations', ), - } - - 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: a.keyword.value not 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=servicecontrolCallTransformer(), -): - """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 servicecontrol 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/owl-bot-staging/v2/setup.py b/owl-bot-staging/v2/setup.py deleted file mode 100644 index 8108ffe..0000000 --- a/owl-bot-staging/v2/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-service-control' - - -description = "Google Cloud Service Control API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/servicecontrol/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-service-control" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/v2/testing/constraints-3.10.txt b/owl-bot-staging/v2/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v2/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2/testing/constraints-3.11.txt b/owl-bot-staging/v2/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v2/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2/testing/constraints-3.12.txt b/owl-bot-staging/v2/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v2/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2/testing/constraints-3.7.txt b/owl-bot-staging/v2/testing/constraints-3.7.txt deleted file mode 100644 index 6c44adf..0000000 --- a/owl-bot-staging/v2/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/v2/testing/constraints-3.8.txt b/owl-bot-staging/v2/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v2/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2/testing/constraints-3.9.txt b/owl-bot-staging/v2/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9ae..0000000 --- a/owl-bot-staging/v2/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/test_service_controller.py b/owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/test_service_controller.py deleted file mode 100644 index e8436dc..0000000 --- a/owl-bot-staging/v2/tests/unit/gapic/servicecontrol_v2/test_service_controller.py +++ /dev/null @@ -1,1704 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_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.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.servicecontrol_v2.services.service_controller import ServiceControllerAsyncClient -from google.cloud.servicecontrol_v2.services.service_controller import ServiceControllerClient -from google.cloud.servicecontrol_v2.services.service_controller import transports -from google.cloud.servicecontrol_v2.types import service_controller -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.rpc.context import attribute_context_pb2 # type: ignore -import google.auth - - -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 ServiceControllerClient._get_default_mtls_endpoint(None) is None - assert ServiceControllerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ServiceControllerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ServiceControllerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ServiceControllerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ServiceControllerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ServiceControllerClient, "grpc"), - (ServiceControllerAsyncClient, "grpc_asyncio"), - (ServiceControllerClient, "rest"), -]) -def test_service_controller_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'servicecontrol.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://servicecontrol.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ServiceControllerGrpcTransport, "grpc"), - (transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ServiceControllerRestTransport, "rest"), -]) -def test_service_controller_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ServiceControllerClient, "grpc"), - (ServiceControllerAsyncClient, "grpc_asyncio"), - (ServiceControllerClient, "rest"), -]) -def test_service_controller_client_from_service_account_file(client_class, transport_name): - creds = ga_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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'servicecontrol.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://servicecontrol.googleapis.com' - ) - - -def test_service_controller_client_get_transport_class(): - transport = ServiceControllerClient.get_transport_class() - available_transports = [ - transports.ServiceControllerGrpcTransport, - transports.ServiceControllerRestTransport, - ] - assert transport in available_transports - - transport = ServiceControllerClient.get_transport_class("grpc") - assert transport == transports.ServiceControllerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc"), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio"), - (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest"), -]) -@mock.patch.object(ServiceControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerClient)) -@mock.patch.object(ServiceControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerAsyncClient)) -def test_service_controller_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(ServiceControllerClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_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(ServiceControllerClient, '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(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", "true"), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", "false"), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest", "true"), - (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest", "false"), -]) -@mock.patch.object(ServiceControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerClient)) -@mock.patch.object(ServiceControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_service_controller_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: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ServiceControllerClient, ServiceControllerAsyncClient -]) -@mock.patch.object(ServiceControllerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerClient)) -@mock.patch.object(ServiceControllerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceControllerAsyncClient)) -def test_service_controller_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc"), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio"), - (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest"), -]) -def test_service_controller_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", grpc_helpers), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest", None), -]) -def test_service_controller_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_service_controller_client_client_options_from_dict(): - with mock.patch('google.cloud.servicecontrol_v2.services.service_controller.transports.ServiceControllerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ServiceControllerClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc", grpc_helpers), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_service_controller_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "servicecontrol.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', -), - scopes=None, - default_host="servicecontrol.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - service_controller.CheckRequest, - dict, -]) -def test_check(request_type, transport: str = 'grpc'): - client = ServiceControllerClient( - credentials=ga_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.check), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_controller.CheckResponse( - ) - response = client.check(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service_controller.CheckRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service_controller.CheckResponse) - - -def test_check_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check), - '__call__') as call: - client.check() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service_controller.CheckRequest() - -@pytest.mark.asyncio -async def test_check_async(transport: str = 'grpc_asyncio', request_type=service_controller.CheckRequest): - client = ServiceControllerAsyncClient( - credentials=ga_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.check), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_controller.CheckResponse( - )) - response = await client.check(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service_controller.CheckRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service_controller.CheckResponse) - - -@pytest.mark.asyncio -async def test_check_async_from_dict(): - await test_check_async(request_type=dict) - - -def test_check_field_headers(): - client = ServiceControllerClient( - credentials=ga_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 = service_controller.CheckRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check), - '__call__') as call: - call.return_value = service_controller.CheckResponse() - client.check(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', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_check_field_headers_async(): - client = ServiceControllerAsyncClient( - credentials=ga_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 = service_controller.CheckRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_controller.CheckResponse()) - await client.check(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', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - service_controller.ReportRequest, - dict, -]) -def test_report(request_type, transport: str = 'grpc'): - client = ServiceControllerClient( - credentials=ga_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.report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_controller.ReportResponse( - ) - response = client.report(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service_controller.ReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service_controller.ReportResponse) - - -def test_report_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.report), - '__call__') as call: - client.report() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service_controller.ReportRequest() - -@pytest.mark.asyncio -async def test_report_async(transport: str = 'grpc_asyncio', request_type=service_controller.ReportRequest): - client = ServiceControllerAsyncClient( - credentials=ga_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.report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_controller.ReportResponse( - )) - response = await client.report(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service_controller.ReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service_controller.ReportResponse) - - -@pytest.mark.asyncio -async def test_report_async_from_dict(): - await test_report_async(request_type=dict) - - -def test_report_field_headers(): - client = ServiceControllerClient( - credentials=ga_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 = service_controller.ReportRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.report), - '__call__') as call: - call.return_value = service_controller.ReportResponse() - client.report(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', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_report_field_headers_async(): - client = ServiceControllerAsyncClient( - credentials=ga_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 = service_controller.ReportRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.report), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_controller.ReportResponse()) - await client.report(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', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - service_controller.CheckRequest, - dict, -]) -def test_check_rest(request_type): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service_controller.CheckResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = service_controller.CheckResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.check(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service_controller.CheckResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_check_rest_interceptors(null_interceptor): - transport = transports.ServiceControllerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceControllerRestInterceptor(), - ) - client = ServiceControllerClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ServiceControllerRestInterceptor, "post_check") as post, \ - mock.patch.object(transports.ServiceControllerRestInterceptor, "pre_check") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service_controller.CheckRequest.pb(service_controller.CheckRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = service_controller.CheckResponse.to_json(service_controller.CheckResponse()) - - request = service_controller.CheckRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service_controller.CheckResponse() - - client.check(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_check_rest_bad_request(transport: str = 'rest', request_type=service_controller.CheckRequest): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.check(request) - - -def test_check_rest_error(): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - service_controller.ReportRequest, - dict, -]) -def test_report_rest(request_type): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service_controller.ReportResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = service_controller.ReportResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.report(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service_controller.ReportResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_report_rest_interceptors(null_interceptor): - transport = transports.ServiceControllerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceControllerRestInterceptor(), - ) - client = ServiceControllerClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ServiceControllerRestInterceptor, "post_report") as post, \ - mock.patch.object(transports.ServiceControllerRestInterceptor, "pre_report") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service_controller.ReportRequest.pb(service_controller.ReportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = service_controller.ReportResponse.to_json(service_controller.ReportResponse()) - - request = service_controller.ReportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service_controller.ReportResponse() - - client.report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_report_rest_bad_request(transport: str = 'rest', request_type=service_controller.ReportRequest): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.report(request) - - -def test_report_rest_error(): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServiceControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServiceControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServiceControllerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ServiceControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServiceControllerClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServiceControllerClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ServiceControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServiceControllerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServiceControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ServiceControllerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServiceControllerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ServiceControllerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ServiceControllerGrpcTransport, - transports.ServiceControllerGrpcAsyncIOTransport, - transports.ServiceControllerRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ServiceControllerClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ServiceControllerGrpcTransport, - ) - -def test_service_controller_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ServiceControllerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_service_controller_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.servicecontrol_v2.services.service_controller.transports.ServiceControllerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ServiceControllerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'check', - 'report', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_service_controller_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.servicecontrol_v2.services.service_controller.transports.ServiceControllerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServiceControllerTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', -), - quota_project_id="octopus", - ) - - -def test_service_controller_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.servicecontrol_v2.services.service_controller.transports.ServiceControllerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServiceControllerTransport() - adc.assert_called_once() - - -def test_service_controller_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ServiceControllerClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServiceControllerGrpcTransport, - transports.ServiceControllerGrpcAsyncIOTransport, - ], -) -def test_service_controller_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/servicecontrol',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServiceControllerGrpcTransport, - transports.ServiceControllerGrpcAsyncIOTransport, - transports.ServiceControllerRestTransport, - ], -) -def test_service_controller_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ServiceControllerGrpcTransport, grpc_helpers), - (transports.ServiceControllerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_service_controller_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "servicecontrol.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol', -), - scopes=["1", "2"], - default_host="servicecontrol.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ServiceControllerGrpcTransport, transports.ServiceControllerGrpcAsyncIOTransport]) -def test_service_controller_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_service_controller_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ServiceControllerRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_service_controller_host_no_port(transport_name): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicecontrol.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'servicecontrol.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://servicecontrol.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_service_controller_host_with_port(transport_name): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicecontrol.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'servicecontrol.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://servicecontrol.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_service_controller_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ServiceControllerClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ServiceControllerClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.check._session - session2 = client2.transport.check._session - assert session1 != session2 - session1 = client1.transport.report._session - session2 = client2.transport.report._session - assert session1 != session2 -def test_service_controller_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServiceControllerGrpcTransport( - 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_service_controller_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServiceControllerGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ServiceControllerGrpcTransport, transports.ServiceControllerGrpcAsyncIOTransport]) -def test_service_controller_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") 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 = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ServiceControllerGrpcTransport, transports.ServiceControllerGrpcAsyncIOTransport]) -def test_service_controller_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") 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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ServiceControllerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = ServiceControllerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceControllerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = ServiceControllerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = ServiceControllerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceControllerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ServiceControllerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = ServiceControllerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceControllerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = ServiceControllerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = ServiceControllerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceControllerClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ServiceControllerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = ServiceControllerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceControllerClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ServiceControllerTransport, '_prep_wrapped_messages') as prep: - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ServiceControllerTransport, '_prep_wrapped_messages') as prep: - transport_class = ServiceControllerClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ServiceControllerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ServiceControllerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport), - (ServiceControllerAsyncClient, transports.ServiceControllerGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json b/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json index 625bd2f..ae2dfb3 100644 --- a/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json +++ b/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-service-control", - "version": "1.8.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json b/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json index f6a8745..2b78179 100644 --- a/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json +++ b/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-service-control", - "version": "1.8.0" + "version": "0.1.0" }, "snippets": [ {