From 3631e3f4fb36039251ec585e7bb41b6e6fffd098 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 8 Feb 2023 22:20:51 +0000 Subject: [PATCH 1/2] feat: enable "rest" transport in Python for services supporting numeric enums PiperOrigin-RevId: 508143576 Source-Link: https://github.com/googleapis/googleapis/commit/7a702a989db3b413f39ff8994ca53fb38b6928c2 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6ad1279c0e7aa787ac6b66c9fd4a210692edffcd Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNmFkMTI3OWMwZTdhYTc4N2FjNmI2NmM5ZmQ0YTIxMDY5MmVkZmZjZCJ9 --- 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 + .../v1/docs/optimization_v1/fleet_routing.rst | 6 + .../v1/docs/optimization_v1/services.rst | 6 + .../v1/docs/optimization_v1/types.rst | 6 + .../v1/google/cloud/optimization/__init__.py | 83 + .../cloud/optimization/gapic_version.py | 16 + .../v1/google/cloud/optimization/py.typed | 2 + .../google/cloud/optimization_v1/__init__.py | 84 + .../cloud/optimization_v1/gapic_metadata.json | 58 + .../cloud/optimization_v1/gapic_version.py | 16 + .../v1/google/cloud/optimization_v1/py.typed | 2 + .../optimization_v1/services/__init__.py | 15 + .../services/fleet_routing/__init__.py | 22 + .../services/fleet_routing/async_client.py | 500 ++ .../services/fleet_routing/client.py | 687 +++ .../fleet_routing/transports/__init__.py | 38 + .../services/fleet_routing/transports/base.py | 191 + .../services/fleet_routing/transports/grpc.py | 375 ++ .../fleet_routing/transports/grpc_asyncio.py | 374 ++ .../services/fleet_routing/transports/rest.py | 590 +++ .../cloud/optimization_v1/types/__init__.py | 78 + .../optimization_v1/types/async_model.py | 201 + .../optimization_v1/types/fleet_routing.py | 4334 +++++++++++++++++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 184 + ...leet_routing_batch_optimize_tours_async.py | 61 + ...fleet_routing_batch_optimize_tours_sync.py | 61 + ...ated_fleet_routing_optimize_tours_async.py | 52 + ...rated_fleet_routing_optimize_tours_sync.py | 52 + ...metadata_google.cloud.optimization.v1.json | 321 ++ .../scripts/fixup_optimization_v1_keywords.py | 177 + 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/optimization_v1/__init__.py | 16 + .../optimization_v1/test_fleet_routing.py | 2104 ++++++++ 48 files changed, 11372 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/optimization_v1/fleet_routing.rst create mode 100644 owl-bot-staging/v1/docs/optimization_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/optimization_v1/types.rst create mode 100644 owl-bot-staging/v1/google/cloud/optimization/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/client.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/rest.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/types/async_model.py create mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/types/fleet_routing.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/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.optimization.v1.json create mode 100644 owl-bot-staging/v1/scripts/fixup_optimization_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/optimization_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/optimization_v1/test_fleet_routing.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 0000000..a52613e --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/optimization/__init__.py + google/cloud/optimization/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..12730a7 --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/optimization *.py +recursive-include google/cloud/optimization_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 0000000..9742358 --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Optimization 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 Optimization 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..da0ad31 --- /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-optimization 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-optimization" +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-optimization-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-optimization.tex", + u"google-cloud-optimization 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-optimization", + u"Google Cloud Optimization 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-optimization", + u"google-cloud-optimization Documentation", + author, + "google-cloud-optimization", + "GAPIC library for Google Cloud Optimization 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..ccbb913 --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + optimization_v1/services + optimization_v1/types diff --git a/owl-bot-staging/v1/docs/optimization_v1/fleet_routing.rst b/owl-bot-staging/v1/docs/optimization_v1/fleet_routing.rst new file mode 100644 index 0000000..ce97b29 --- /dev/null +++ b/owl-bot-staging/v1/docs/optimization_v1/fleet_routing.rst @@ -0,0 +1,6 @@ +FleetRouting +------------------------------ + +.. automodule:: google.cloud.optimization_v1.services.fleet_routing + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/optimization_v1/services.rst b/owl-bot-staging/v1/docs/optimization_v1/services.rst new file mode 100644 index 0000000..2fb17d5 --- /dev/null +++ b/owl-bot-staging/v1/docs/optimization_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Optimization v1 API +============================================= +.. toctree:: + :maxdepth: 2 + + fleet_routing diff --git a/owl-bot-staging/v1/docs/optimization_v1/types.rst b/owl-bot-staging/v1/docs/optimization_v1/types.rst new file mode 100644 index 0000000..bc2dcf0 --- /dev/null +++ b/owl-bot-staging/v1/docs/optimization_v1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Optimization v1 API +========================================== + +.. automodule:: google.cloud.optimization_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/optimization/__init__.py b/owl-bot-staging/v1/google/cloud/optimization/__init__.py new file mode 100644 index 0000000..f91a3bb --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization/__init__.py @@ -0,0 +1,83 @@ +# -*- 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.optimization import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.optimization_v1.services.fleet_routing.client import FleetRoutingClient +from google.cloud.optimization_v1.services.fleet_routing.async_client import FleetRoutingAsyncClient + +from google.cloud.optimization_v1.types.async_model import AsyncModelMetadata +from google.cloud.optimization_v1.types.async_model import GcsDestination +from google.cloud.optimization_v1.types.async_model import GcsSource +from google.cloud.optimization_v1.types.async_model import InputConfig +from google.cloud.optimization_v1.types.async_model import OutputConfig +from google.cloud.optimization_v1.types.async_model import DataFormat +from google.cloud.optimization_v1.types.fleet_routing import AggregatedMetrics +from google.cloud.optimization_v1.types.fleet_routing import BatchOptimizeToursRequest +from google.cloud.optimization_v1.types.fleet_routing import BatchOptimizeToursResponse +from google.cloud.optimization_v1.types.fleet_routing import BreakRule +from google.cloud.optimization_v1.types.fleet_routing import CapacityQuantity +from google.cloud.optimization_v1.types.fleet_routing import CapacityQuantityInterval +from google.cloud.optimization_v1.types.fleet_routing import DistanceLimit +from google.cloud.optimization_v1.types.fleet_routing import InjectedSolutionConstraint +from google.cloud.optimization_v1.types.fleet_routing import Location +from google.cloud.optimization_v1.types.fleet_routing import OptimizeToursRequest +from google.cloud.optimization_v1.types.fleet_routing import OptimizeToursResponse +from google.cloud.optimization_v1.types.fleet_routing import OptimizeToursValidationError +from google.cloud.optimization_v1.types.fleet_routing import Shipment +from google.cloud.optimization_v1.types.fleet_routing import ShipmentModel +from google.cloud.optimization_v1.types.fleet_routing import ShipmentRoute +from google.cloud.optimization_v1.types.fleet_routing import ShipmentTypeIncompatibility +from google.cloud.optimization_v1.types.fleet_routing import ShipmentTypeRequirement +from google.cloud.optimization_v1.types.fleet_routing import SkippedShipment +from google.cloud.optimization_v1.types.fleet_routing import TimeWindow +from google.cloud.optimization_v1.types.fleet_routing import TransitionAttributes +from google.cloud.optimization_v1.types.fleet_routing import Vehicle +from google.cloud.optimization_v1.types.fleet_routing import Waypoint + +__all__ = ('FleetRoutingClient', + 'FleetRoutingAsyncClient', + 'AsyncModelMetadata', + 'GcsDestination', + 'GcsSource', + 'InputConfig', + 'OutputConfig', + 'DataFormat', + 'AggregatedMetrics', + 'BatchOptimizeToursRequest', + 'BatchOptimizeToursResponse', + 'BreakRule', + 'CapacityQuantity', + 'CapacityQuantityInterval', + 'DistanceLimit', + 'InjectedSolutionConstraint', + 'Location', + 'OptimizeToursRequest', + 'OptimizeToursResponse', + 'OptimizeToursValidationError', + 'Shipment', + 'ShipmentModel', + 'ShipmentRoute', + 'ShipmentTypeIncompatibility', + 'ShipmentTypeRequirement', + 'SkippedShipment', + 'TimeWindow', + 'TransitionAttributes', + 'Vehicle', + 'Waypoint', +) diff --git a/owl-bot-staging/v1/google/cloud/optimization/gapic_version.py b/owl-bot-staging/v1/google/cloud/optimization/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization/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/optimization/py.typed b/owl-bot-staging/v1/google/cloud/optimization/py.typed new file mode 100644 index 0000000..5157828 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-optimization package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/__init__.py b/owl-bot-staging/v1/google/cloud/optimization_v1/__init__.py new file mode 100644 index 0000000..a8ee01e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/__init__.py @@ -0,0 +1,84 @@ +# -*- 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.optimization_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.fleet_routing import FleetRoutingClient +from .services.fleet_routing import FleetRoutingAsyncClient + +from .types.async_model import AsyncModelMetadata +from .types.async_model import GcsDestination +from .types.async_model import GcsSource +from .types.async_model import InputConfig +from .types.async_model import OutputConfig +from .types.async_model import DataFormat +from .types.fleet_routing import AggregatedMetrics +from .types.fleet_routing import BatchOptimizeToursRequest +from .types.fleet_routing import BatchOptimizeToursResponse +from .types.fleet_routing import BreakRule +from .types.fleet_routing import CapacityQuantity +from .types.fleet_routing import CapacityQuantityInterval +from .types.fleet_routing import DistanceLimit +from .types.fleet_routing import InjectedSolutionConstraint +from .types.fleet_routing import Location +from .types.fleet_routing import OptimizeToursRequest +from .types.fleet_routing import OptimizeToursResponse +from .types.fleet_routing import OptimizeToursValidationError +from .types.fleet_routing import Shipment +from .types.fleet_routing import ShipmentModel +from .types.fleet_routing import ShipmentRoute +from .types.fleet_routing import ShipmentTypeIncompatibility +from .types.fleet_routing import ShipmentTypeRequirement +from .types.fleet_routing import SkippedShipment +from .types.fleet_routing import TimeWindow +from .types.fleet_routing import TransitionAttributes +from .types.fleet_routing import Vehicle +from .types.fleet_routing import Waypoint + +__all__ = ( + 'FleetRoutingAsyncClient', +'AggregatedMetrics', +'AsyncModelMetadata', +'BatchOptimizeToursRequest', +'BatchOptimizeToursResponse', +'BreakRule', +'CapacityQuantity', +'CapacityQuantityInterval', +'DataFormat', +'DistanceLimit', +'FleetRoutingClient', +'GcsDestination', +'GcsSource', +'InjectedSolutionConstraint', +'InputConfig', +'Location', +'OptimizeToursRequest', +'OptimizeToursResponse', +'OptimizeToursValidationError', +'OutputConfig', +'Shipment', +'ShipmentModel', +'ShipmentRoute', +'ShipmentTypeIncompatibility', +'ShipmentTypeRequirement', +'SkippedShipment', +'TimeWindow', +'TransitionAttributes', +'Vehicle', +'Waypoint', +) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/optimization_v1/gapic_metadata.json new file mode 100644 index 0000000..c9c5016 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/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.optimization_v1", + "protoPackage": "google.cloud.optimization.v1", + "schema": "1.0", + "services": { + "FleetRouting": { + "clients": { + "grpc": { + "libraryClient": "FleetRoutingClient", + "rpcs": { + "BatchOptimizeTours": { + "methods": [ + "batch_optimize_tours" + ] + }, + "OptimizeTours": { + "methods": [ + "optimize_tours" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FleetRoutingAsyncClient", + "rpcs": { + "BatchOptimizeTours": { + "methods": [ + "batch_optimize_tours" + ] + }, + "OptimizeTours": { + "methods": [ + "optimize_tours" + ] + } + } + }, + "rest": { + "libraryClient": "FleetRoutingClient", + "rpcs": { + "BatchOptimizeTours": { + "methods": [ + "batch_optimize_tours" + ] + }, + "OptimizeTours": { + "methods": [ + "optimize_tours" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/optimization_v1/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_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/optimization_v1/py.typed b/owl-bot-staging/v1/google/cloud/optimization_v1/py.typed new file mode 100644 index 0000000..5157828 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-optimization package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_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/optimization_v1/services/fleet_routing/__init__.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/__init__.py new file mode 100644 index 0000000..eee0bb0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/__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 FleetRoutingClient +from .async_client import FleetRoutingAsyncClient + +__all__ = ( + 'FleetRoutingClient', + 'FleetRoutingAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/async_client.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/async_client.py new file mode 100644 index 0000000..1370625 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/async_client.py @@ -0,0 +1,500 @@ +# -*- 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.optimization_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.optimization_v1.types import async_model +from google.cloud.optimization_v1.types import fleet_routing +from google.longrunning import operations_pb2 +from .transports.base import FleetRoutingTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FleetRoutingGrpcAsyncIOTransport +from .client import FleetRoutingClient + + +class FleetRoutingAsyncClient: + """A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + """ + + _client: FleetRoutingClient + + DEFAULT_ENDPOINT = FleetRoutingClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FleetRoutingClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(FleetRoutingClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(FleetRoutingClient.parse_common_billing_account_path) + common_folder_path = staticmethod(FleetRoutingClient.common_folder_path) + parse_common_folder_path = staticmethod(FleetRoutingClient.parse_common_folder_path) + common_organization_path = staticmethod(FleetRoutingClient.common_organization_path) + parse_common_organization_path = staticmethod(FleetRoutingClient.parse_common_organization_path) + common_project_path = staticmethod(FleetRoutingClient.common_project_path) + parse_common_project_path = staticmethod(FleetRoutingClient.parse_common_project_path) + common_location_path = staticmethod(FleetRoutingClient.common_location_path) + parse_common_location_path = staticmethod(FleetRoutingClient.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: + FleetRoutingAsyncClient: The constructed client. + """ + return FleetRoutingClient.from_service_account_info.__func__(FleetRoutingAsyncClient, 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: + FleetRoutingAsyncClient: The constructed client. + """ + return FleetRoutingClient.from_service_account_file.__func__(FleetRoutingAsyncClient, 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 FleetRoutingClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> FleetRoutingTransport: + """Returns the transport used by the client instance. + + Returns: + FleetRoutingTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(FleetRoutingClient).get_transport_class, type(FleetRoutingClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, FleetRoutingTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the fleet routing 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, ~.FleetRoutingTransport]): 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 = FleetRoutingClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def optimize_tours(self, + request: Optional[Union[fleet_routing.OptimizeToursRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fleet_routing.OptimizeToursResponse: + r"""Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` + and returns an ``OptimizeToursResponse`` containing + ``ShipmentRoute``\ s, which are a set of routes to be performed + by vehicles minimizing the overall cost. + + A ``ShipmentModel`` model consists mainly of ``Shipment``\ s + that need to be carried out and ``Vehicle``\ s that can be used + to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s + assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, + they assign a series of ``Visit``\ s to each vehicle, where a + ``Visit`` corresponds to a ``VisitRequest``, which is a pickup + or delivery for a ``Shipment``. + + The goal is to provide an assignment of ``ShipmentRoute``\ s to + ``Vehicle``\ s that minimizes the total cost where cost has many + components defined in the ``ShipmentModel``. + + .. 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 optimization_v1 + + async def sample_optimize_tours(): + # Create a client + client = optimization_v1.FleetRoutingAsyncClient() + + # Initialize request argument(s) + request = optimization_v1.OptimizeToursRequest( + parent="parent_value", + ) + + # Make the request + response = await client.optimize_tours(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.optimization_v1.types.OptimizeToursRequest, dict]]): + The request object. Request to be given to a tour + optimization solver which defines the shipment model to + solve as well as optimization parameters. + 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.optimization_v1.types.OptimizeToursResponse: + Response after solving a tour + optimization problem containing the + routes followed by each vehicle, the + shipments which have been skipped and + the overall cost of the solution. + + """ + # Create or coerce a protobuf request object. + request = fleet_routing.OptimizeToursRequest(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.optimize_tours, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=3600.0, + ), + default_timeout=3600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_optimize_tours(self, + request: Optional[Union[fleet_routing.BatchOptimizeToursRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Optimizes vehicle tours for one or more ``OptimizeToursRequest`` + messages as a batch. + + This method is a Long Running Operation (LRO). The inputs for + optimization (``OptimizeToursRequest`` messages) and outputs + (``OptimizeToursResponse`` messages) are read/written from/to + Cloud Storage in user-specified format. Like the + ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains + a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` + containing ``ShipmentRoute``\ s, which are a set of routes to be + performed by vehicles minimizing the overall cost. + + .. 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 optimization_v1 + + async def sample_batch_optimize_tours(): + # Create a client + client = optimization_v1.FleetRoutingAsyncClient() + + # Initialize request argument(s) + model_configs = optimization_v1.AsyncModelConfig() + model_configs.input_config.gcs_source.uri = "uri_value" + model_configs.output_config.gcs_destination.uri = "uri_value" + + request = optimization_v1.BatchOptimizeToursRequest( + parent="parent_value", + model_configs=model_configs, + ) + + # Make the request + operation = client.batch_optimize_tours(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.optimization_v1.types.BatchOptimizeToursRequest, dict]]): + The request object. Request to batch optimize tours as + an asynchronous operation. Each input file should + contain one `OptimizeToursRequest`, and each output file + will contain one `OptimizeToursResponse`. The request + contains information to read/write and parse the files. + All the input and output files should be under the same + project. + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.optimization_v1.types.BatchOptimizeToursResponse` Response to a BatchOptimizeToursRequest. This is returned in + the LRO Operation after the operation is complete. + + """ + # Create or coerce a protobuf request object. + request = fleet_routing.BatchOptimizeToursRequest(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.batch_optimize_tours, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + fleet_routing.BatchOptimizeToursResponse, + metadata_type=async_model.AsyncModelMetadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` 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: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + 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( + (("name", request.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__ = ( + "FleetRoutingAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/client.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/client.py new file mode 100644 index 0000000..bf608b1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/client.py @@ -0,0 +1,687 @@ +# -*- 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.optimization_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.optimization_v1.types import async_model +from google.cloud.optimization_v1.types import fleet_routing +from google.longrunning import operations_pb2 +from .transports.base import FleetRoutingTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FleetRoutingGrpcTransport +from .transports.grpc_asyncio import FleetRoutingGrpcAsyncIOTransport +from .transports.rest import FleetRoutingRestTransport + + +class FleetRoutingClientMeta(type): + """Metaclass for the FleetRouting 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[FleetRoutingTransport]] + _transport_registry["grpc"] = FleetRoutingGrpcTransport + _transport_registry["grpc_asyncio"] = FleetRoutingGrpcAsyncIOTransport + _transport_registry["rest"] = FleetRoutingRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[FleetRoutingTransport]: + """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 FleetRoutingClient(metaclass=FleetRoutingClientMeta): + """A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + """ + + @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 = "cloudoptimization.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: + FleetRoutingClient: 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: + FleetRoutingClient: 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) -> FleetRoutingTransport: + """Returns the transport used by the client instance. + + Returns: + FleetRoutingTransport: 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, FleetRoutingTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the fleet routing 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, FleetRoutingTransport]): 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, FleetRoutingTransport): + # transport is a FleetRoutingTransport 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 optimize_tours(self, + request: Optional[Union[fleet_routing.OptimizeToursRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fleet_routing.OptimizeToursResponse: + r"""Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` + and returns an ``OptimizeToursResponse`` containing + ``ShipmentRoute``\ s, which are a set of routes to be performed + by vehicles minimizing the overall cost. + + A ``ShipmentModel`` model consists mainly of ``Shipment``\ s + that need to be carried out and ``Vehicle``\ s that can be used + to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s + assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, + they assign a series of ``Visit``\ s to each vehicle, where a + ``Visit`` corresponds to a ``VisitRequest``, which is a pickup + or delivery for a ``Shipment``. + + The goal is to provide an assignment of ``ShipmentRoute``\ s to + ``Vehicle``\ s that minimizes the total cost where cost has many + components defined in the ``ShipmentModel``. + + .. 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 optimization_v1 + + def sample_optimize_tours(): + # Create a client + client = optimization_v1.FleetRoutingClient() + + # Initialize request argument(s) + request = optimization_v1.OptimizeToursRequest( + parent="parent_value", + ) + + # Make the request + response = client.optimize_tours(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.optimization_v1.types.OptimizeToursRequest, dict]): + The request object. Request to be given to a tour + optimization solver which defines the shipment model to + solve as well as optimization parameters. + 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.optimization_v1.types.OptimizeToursResponse: + Response after solving a tour + optimization problem containing the + routes followed by each vehicle, the + shipments which have been skipped and + the overall cost of the solution. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a fleet_routing.OptimizeToursRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, fleet_routing.OptimizeToursRequest): + request = fleet_routing.OptimizeToursRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.optimize_tours] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_optimize_tours(self, + request: Optional[Union[fleet_routing.BatchOptimizeToursRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Optimizes vehicle tours for one or more ``OptimizeToursRequest`` + messages as a batch. + + This method is a Long Running Operation (LRO). The inputs for + optimization (``OptimizeToursRequest`` messages) and outputs + (``OptimizeToursResponse`` messages) are read/written from/to + Cloud Storage in user-specified format. Like the + ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains + a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` + containing ``ShipmentRoute``\ s, which are a set of routes to be + performed by vehicles minimizing the overall cost. + + .. 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 optimization_v1 + + def sample_batch_optimize_tours(): + # Create a client + client = optimization_v1.FleetRoutingClient() + + # Initialize request argument(s) + model_configs = optimization_v1.AsyncModelConfig() + model_configs.input_config.gcs_source.uri = "uri_value" + model_configs.output_config.gcs_destination.uri = "uri_value" + + request = optimization_v1.BatchOptimizeToursRequest( + parent="parent_value", + model_configs=model_configs, + ) + + # Make the request + operation = client.batch_optimize_tours(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.optimization_v1.types.BatchOptimizeToursRequest, dict]): + The request object. Request to batch optimize tours as + an asynchronous operation. Each input file should + contain one `OptimizeToursRequest`, and each output file + will contain one `OptimizeToursResponse`. The request + contains information to read/write and parse the files. + All the input and output files should be under the same + project. + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.optimization_v1.types.BatchOptimizeToursResponse` Response to a BatchOptimizeToursRequest. This is returned in + the LRO Operation after the operation is complete. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a fleet_routing.BatchOptimizeToursRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, fleet_routing.BatchOptimizeToursRequest): + request = fleet_routing.BatchOptimizeToursRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_optimize_tours] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + fleet_routing.BatchOptimizeToursResponse, + metadata_type=async_model.AsyncModelMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "FleetRoutingClient": + 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() + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` 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: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + 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( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "FleetRoutingClient", +) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/__init__.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/__init__.py new file mode 100644 index 0000000..6bdd233 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/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 FleetRoutingTransport +from .grpc import FleetRoutingGrpcTransport +from .grpc_asyncio import FleetRoutingGrpcAsyncIOTransport +from .rest import FleetRoutingRestTransport +from .rest import FleetRoutingRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FleetRoutingTransport]] +_transport_registry['grpc'] = FleetRoutingGrpcTransport +_transport_registry['grpc_asyncio'] = FleetRoutingGrpcAsyncIOTransport +_transport_registry['rest'] = FleetRoutingRestTransport + +__all__ = ( + 'FleetRoutingTransport', + 'FleetRoutingGrpcTransport', + 'FleetRoutingGrpcAsyncIOTransport', + 'FleetRoutingRestTransport', + 'FleetRoutingRestInterceptor', +) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/base.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/base.py new file mode 100644 index 0000000..b8d3bbf --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/base.py @@ -0,0 +1,191 @@ +# -*- 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.optimization_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.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.optimization_v1.types import fleet_routing +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class FleetRoutingTransport(abc.ABC): + """Abstract transport class for FleetRouting.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'cloudoptimization.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.optimize_tours: gapic_v1.method.wrap_method( + self.optimize_tours, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=3600.0, + ), + default_timeout=3600.0, + client_info=client_info, + ), + self.batch_optimize_tours: gapic_v1.method.wrap_method( + self.batch_optimize_tours, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def optimize_tours(self) -> Callable[ + [fleet_routing.OptimizeToursRequest], + Union[ + fleet_routing.OptimizeToursResponse, + Awaitable[fleet_routing.OptimizeToursResponse] + ]]: + raise NotImplementedError() + + @property + def batch_optimize_tours(self) -> Callable[ + [fleet_routing.BatchOptimizeToursRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'FleetRoutingTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc.py new file mode 100644 index 0000000..ffae111 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc.py @@ -0,0 +1,375 @@ +# -*- 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 operations_v1 +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.optimization_v1.types import fleet_routing +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import FleetRoutingTransport, DEFAULT_CLIENT_INFO + + +class FleetRoutingGrpcTransport(FleetRoutingTransport): + """gRPC backend transport for FleetRouting. + + A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + + 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 = 'cloudoptimization.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] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + 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 = 'cloudoptimization.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def optimize_tours(self) -> Callable[ + [fleet_routing.OptimizeToursRequest], + fleet_routing.OptimizeToursResponse]: + r"""Return a callable for the optimize tours method over gRPC. + + Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` + and returns an ``OptimizeToursResponse`` containing + ``ShipmentRoute``\ s, which are a set of routes to be performed + by vehicles minimizing the overall cost. + + A ``ShipmentModel`` model consists mainly of ``Shipment``\ s + that need to be carried out and ``Vehicle``\ s that can be used + to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s + assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, + they assign a series of ``Visit``\ s to each vehicle, where a + ``Visit`` corresponds to a ``VisitRequest``, which is a pickup + or delivery for a ``Shipment``. + + The goal is to provide an assignment of ``ShipmentRoute``\ s to + ``Vehicle``\ s that minimizes the total cost where cost has many + components defined in the ``ShipmentModel``. + + Returns: + Callable[[~.OptimizeToursRequest], + ~.OptimizeToursResponse]: + 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 'optimize_tours' not in self._stubs: + self._stubs['optimize_tours'] = self.grpc_channel.unary_unary( + '/google.cloud.optimization.v1.FleetRouting/OptimizeTours', + request_serializer=fleet_routing.OptimizeToursRequest.serialize, + response_deserializer=fleet_routing.OptimizeToursResponse.deserialize, + ) + return self._stubs['optimize_tours'] + + @property + def batch_optimize_tours(self) -> Callable[ + [fleet_routing.BatchOptimizeToursRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch optimize tours method over gRPC. + + Optimizes vehicle tours for one or more ``OptimizeToursRequest`` + messages as a batch. + + This method is a Long Running Operation (LRO). The inputs for + optimization (``OptimizeToursRequest`` messages) and outputs + (``OptimizeToursResponse`` messages) are read/written from/to + Cloud Storage in user-specified format. Like the + ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains + a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` + containing ``ShipmentRoute``\ s, which are a set of routes to be + performed by vehicles minimizing the overall cost. + + Returns: + Callable[[~.BatchOptimizeToursRequest], + ~.Operation]: + 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 'batch_optimize_tours' not in self._stubs: + self._stubs['batch_optimize_tours'] = self.grpc_channel.unary_unary( + '/google.cloud.optimization.v1.FleetRouting/BatchOptimizeTours', + request_serializer=fleet_routing.BatchOptimizeToursRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_optimize_tours'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'FleetRoutingGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc_asyncio.py new file mode 100644 index 0000000..b80a34f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc_asyncio.py @@ -0,0 +1,374 @@ +# -*- 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.api_core import operations_v1 +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.optimization_v1.types import fleet_routing +from google.longrunning import operations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from .base import FleetRoutingTransport, DEFAULT_CLIENT_INFO +from .grpc import FleetRoutingGrpcTransport + + +class FleetRoutingGrpcAsyncIOTransport(FleetRoutingTransport): + """gRPC AsyncIO backend transport for FleetRouting. + + A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + + 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 = 'cloudoptimization.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 = 'cloudoptimization.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] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + 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 operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def optimize_tours(self) -> Callable[ + [fleet_routing.OptimizeToursRequest], + Awaitable[fleet_routing.OptimizeToursResponse]]: + r"""Return a callable for the optimize tours method over gRPC. + + Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` + and returns an ``OptimizeToursResponse`` containing + ``ShipmentRoute``\ s, which are a set of routes to be performed + by vehicles minimizing the overall cost. + + A ``ShipmentModel`` model consists mainly of ``Shipment``\ s + that need to be carried out and ``Vehicle``\ s that can be used + to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s + assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, + they assign a series of ``Visit``\ s to each vehicle, where a + ``Visit`` corresponds to a ``VisitRequest``, which is a pickup + or delivery for a ``Shipment``. + + The goal is to provide an assignment of ``ShipmentRoute``\ s to + ``Vehicle``\ s that minimizes the total cost where cost has many + components defined in the ``ShipmentModel``. + + Returns: + Callable[[~.OptimizeToursRequest], + Awaitable[~.OptimizeToursResponse]]: + 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 'optimize_tours' not in self._stubs: + self._stubs['optimize_tours'] = self.grpc_channel.unary_unary( + '/google.cloud.optimization.v1.FleetRouting/OptimizeTours', + request_serializer=fleet_routing.OptimizeToursRequest.serialize, + response_deserializer=fleet_routing.OptimizeToursResponse.deserialize, + ) + return self._stubs['optimize_tours'] + + @property + def batch_optimize_tours(self) -> Callable[ + [fleet_routing.BatchOptimizeToursRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch optimize tours method over gRPC. + + Optimizes vehicle tours for one or more ``OptimizeToursRequest`` + messages as a batch. + + This method is a Long Running Operation (LRO). The inputs for + optimization (``OptimizeToursRequest`` messages) and outputs + (``OptimizeToursResponse`` messages) are read/written from/to + Cloud Storage in user-specified format. Like the + ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains + a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` + containing ``ShipmentRoute``\ s, which are a set of routes to be + performed by vehicles minimizing the overall cost. + + Returns: + Callable[[~.BatchOptimizeToursRequest], + Awaitable[~.Operation]]: + 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 'batch_optimize_tours' not in self._stubs: + self._stubs['batch_optimize_tours'] = self.grpc_channel.unary_unary( + '/google.cloud.optimization.v1.FleetRouting/BatchOptimizeTours', + request_serializer=fleet_routing.BatchOptimizeToursRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_optimize_tours'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + +__all__ = ( + 'FleetRoutingGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/rest.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/rest.py new file mode 100644 index 0000000..d4cd012 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/rest.py @@ -0,0 +1,590 @@ +# -*- 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 google.api_core import operations_v1 +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import 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.optimization_v1.types import fleet_routing +from google.longrunning import operations_pb2 # type: ignore + +from .base import FleetRoutingTransport, 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 FleetRoutingRestInterceptor: + """Interceptor for FleetRouting. + + 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 FleetRoutingRestTransport. + + .. code-block:: python + class MyCustomFleetRoutingInterceptor(FleetRoutingRestInterceptor): + def pre_batch_optimize_tours(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_optimize_tours(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_optimize_tours(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_optimize_tours(self, response): + logging.log(f"Received response: {response}") + return response + + transport = FleetRoutingRestTransport(interceptor=MyCustomFleetRoutingInterceptor()) + client = FleetRoutingClient(transport=transport) + + + """ + def pre_batch_optimize_tours(self, request: fleet_routing.BatchOptimizeToursRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[fleet_routing.BatchOptimizeToursRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_optimize_tours + + Override in a subclass to manipulate the request or metadata + before they are sent to the FleetRouting server. + """ + return request, metadata + + def post_batch_optimize_tours(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_optimize_tours + + Override in a subclass to manipulate the response + after it is returned by the FleetRouting server but before + it is returned to user code. + """ + return response + def pre_optimize_tours(self, request: fleet_routing.OptimizeToursRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[fleet_routing.OptimizeToursRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for optimize_tours + + Override in a subclass to manipulate the request or metadata + before they are sent to the FleetRouting server. + """ + return request, metadata + + def post_optimize_tours(self, response: fleet_routing.OptimizeToursResponse) -> fleet_routing.OptimizeToursResponse: + """Post-rpc interceptor for optimize_tours + + Override in a subclass to manipulate the response + after it is returned by the FleetRouting server but before + it is returned to user code. + """ + return response + + def pre_get_operation(self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]]) -> operations_pb2.Operation: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the FleetRouting server. + """ + return request, metadata + + def post_get_operation(self, response: operations_pb2.GetOperationRequest) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the FleetRouting server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class FleetRoutingRestStub: + _session: AuthorizedSession + _host: str + _interceptor: FleetRoutingRestInterceptor + + +class FleetRoutingRestTransport(FleetRoutingTransport): + """REST backend transport for FleetRouting. + + A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + + 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 = 'cloudoptimization.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[FleetRoutingRestInterceptor] = 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) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or FleetRoutingRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _BatchOptimizeTours(FleetRoutingRestStub): + def __hash__(self): + return hash("BatchOptimizeTours") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: fleet_routing.BatchOptimizeToursRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the batch optimize tours method over HTTP. + + Args: + request (~.fleet_routing.BatchOptimizeToursRequest): + The request object. Request to batch optimize tours as an asynchronous + operation. Each input file should contain one + ``OptimizeToursRequest``, and each output file will + contain one ``OptimizeToursResponse``. The request + contains information to read/write and parse the files. + All the input and output files should be under the same + project. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}:batchOptimizeTours', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*}:batchOptimizeTours', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_batch_optimize_tours(request, metadata) + pb_request = fleet_routing.BatchOptimizeToursRequest.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.update(self._get_unset_required_fields(query_params)) + + 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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_optimize_tours(resp) + return resp + + class _OptimizeTours(FleetRoutingRestStub): + def __hash__(self): + return hash("OptimizeTours") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: fleet_routing.OptimizeToursRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> fleet_routing.OptimizeToursResponse: + r"""Call the optimize tours method over HTTP. + + Args: + request (~.fleet_routing.OptimizeToursRequest): + The request object. Request to be given to a tour + optimization solver which defines the + shipment model to solve as well as + optimization parameters. + + 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: + ~.fleet_routing.OptimizeToursResponse: + Response after solving a tour + optimization problem containing the + routes followed by each vehicle, the + shipments which have been skipped and + the overall cost of the solution. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}:optimizeTours', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*}:optimizeTours', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_optimize_tours(request, metadata) + pb_request = fleet_routing.OptimizeToursRequest.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.update(self._get_unset_required_fields(query_params)) + + 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 = fleet_routing.OptimizeToursResponse() + pb_resp = fleet_routing.OptimizeToursResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_optimize_tours(resp) + return resp + + @property + def batch_optimize_tours(self) -> Callable[ + [fleet_routing.BatchOptimizeToursRequest], + operations_pb2.Operation]: + # 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._BatchOptimizeTours(self._session, self._host, self._interceptor) # type: ignore + + @property + def optimize_tours(self) -> Callable[ + [fleet_routing.OptimizeToursRequest], + fleet_routing.OptimizeToursResponse]: + # 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._OptimizeTours(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(FleetRoutingRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation 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: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # 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), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'FleetRoutingRestTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/optimization_v1/types/__init__.py new file mode 100644 index 0000000..a6cc7b6 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/types/__init__.py @@ -0,0 +1,78 @@ +# -*- 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 .async_model import ( + AsyncModelMetadata, + GcsDestination, + GcsSource, + InputConfig, + OutputConfig, + DataFormat, +) +from .fleet_routing import ( + AggregatedMetrics, + BatchOptimizeToursRequest, + BatchOptimizeToursResponse, + BreakRule, + CapacityQuantity, + CapacityQuantityInterval, + DistanceLimit, + InjectedSolutionConstraint, + Location, + OptimizeToursRequest, + OptimizeToursResponse, + OptimizeToursValidationError, + Shipment, + ShipmentModel, + ShipmentRoute, + ShipmentTypeIncompatibility, + ShipmentTypeRequirement, + SkippedShipment, + TimeWindow, + TransitionAttributes, + Vehicle, + Waypoint, +) + +__all__ = ( + 'AsyncModelMetadata', + 'GcsDestination', + 'GcsSource', + 'InputConfig', + 'OutputConfig', + 'DataFormat', + 'AggregatedMetrics', + 'BatchOptimizeToursRequest', + 'BatchOptimizeToursResponse', + 'BreakRule', + 'CapacityQuantity', + 'CapacityQuantityInterval', + 'DistanceLimit', + 'InjectedSolutionConstraint', + 'Location', + 'OptimizeToursRequest', + 'OptimizeToursResponse', + 'OptimizeToursValidationError', + 'Shipment', + 'ShipmentModel', + 'ShipmentRoute', + 'ShipmentTypeIncompatibility', + 'ShipmentTypeRequirement', + 'SkippedShipment', + 'TimeWindow', + 'TransitionAttributes', + 'Vehicle', + 'Waypoint', +) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/types/async_model.py b/owl-bot-staging/v1/google/cloud/optimization_v1/types/async_model.py new file mode 100644 index 0000000..8753a33 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/types/async_model.py @@ -0,0 +1,201 @@ +# -*- 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.optimization.v1', + manifest={ + 'DataFormat', + 'InputConfig', + 'OutputConfig', + 'GcsSource', + 'GcsDestination', + 'AsyncModelMetadata', + }, +) + + +class DataFormat(proto.Enum): + r"""Data formats for input and output files. + + Values: + DATA_FORMAT_UNSPECIFIED (0): + Default value. + JSON (1): + Input data in json format. + STRING (2): + Input data in string format. + """ + DATA_FORMAT_UNSPECIFIED = 0 + JSON = 1 + STRING = 2 + + +class InputConfig(proto.Message): + r"""The desired input location information. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_source (google.cloud.optimization_v1.types.GcsSource): + The Google Cloud Storage location to read the + input from. This must be a single file. + + This field is a member of `oneof`_ ``source``. + data_format (google.cloud.optimization_v1.types.DataFormat): + The input data format that used to store the + model in Cloud Storage. + """ + + gcs_source: 'GcsSource' = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='GcsSource', + ) + data_format: 'DataFormat' = proto.Field( + proto.ENUM, + number=2, + enum='DataFormat', + ) + + +class OutputConfig(proto.Message): + r"""The desired output location. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_destination (google.cloud.optimization_v1.types.GcsDestination): + The Google Cloud Storage location to write + the output to. + + This field is a member of `oneof`_ ``destination``. + data_format (google.cloud.optimization_v1.types.DataFormat): + The output data format that used to store the + results in Cloud Storage. + """ + + gcs_destination: 'GcsDestination' = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message='GcsDestination', + ) + data_format: 'DataFormat' = proto.Field( + proto.ENUM, + number=2, + enum='DataFormat', + ) + + +class GcsSource(proto.Message): + r"""The Google Cloud Storage location where the input file will + be read from. + + Attributes: + uri (str): + Required. URI of the Google Cloud Storage + location. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GcsDestination(proto.Message): + r"""The Google Cloud Storage location where the output file will + be written to. + + Attributes: + uri (str): + Required. URI of the Google Cloud Storage + location. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AsyncModelMetadata(proto.Message): + r"""The long running operation metadata for async model related + methods. + + Attributes: + state (google.cloud.optimization_v1.types.AsyncModelMetadata.State): + The state of the current operation. + state_message (str): + A message providing more details about the + current state of the operation. For example, the + error message if the operation is failed. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of the operation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The last update time of the operation. + """ + class State(proto.Enum): + r"""Possible states of the operation. + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + RUNNING (1): + Request is being processed. + SUCCEEDED (2): + The operation completed successfully. + CANCELLED (3): + The operation was cancelled. + FAILED (4): + The operation has failed. + """ + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + CANCELLED = 3 + FAILED = 4 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/types/fleet_routing.py b/owl-bot-staging/v1/google/cloud/optimization_v1/types/fleet_routing.py new file mode 100644 index 0000000..2d7fa29 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/optimization_v1/types/fleet_routing.py @@ -0,0 +1,4334 @@ +# -*- 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.optimization_v1.types import async_model +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.optimization.v1', + manifest={ + 'OptimizeToursRequest', + 'OptimizeToursResponse', + 'BatchOptimizeToursRequest', + 'BatchOptimizeToursResponse', + 'ShipmentModel', + 'Shipment', + 'ShipmentTypeIncompatibility', + 'ShipmentTypeRequirement', + 'Vehicle', + 'TimeWindow', + 'CapacityQuantity', + 'CapacityQuantityInterval', + 'DistanceLimit', + 'TransitionAttributes', + 'Waypoint', + 'Location', + 'BreakRule', + 'ShipmentRoute', + 'SkippedShipment', + 'AggregatedMetrics', + 'InjectedSolutionConstraint', + 'OptimizeToursValidationError', + }, +) + + +class OptimizeToursRequest(proto.Message): + r"""Request to be given to a tour optimization solver which + defines the shipment model to solve as well as optimization + parameters. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. Target project and location to make a call. + + Format: ``projects/{project-id}/locations/{location-id}``. + + If no location is specified, a region will be chosen + automatically. + timeout (google.protobuf.duration_pb2.Duration): + If this timeout is set, the server returns a + response before the timeout period has elapsed + or the server deadline for synchronous requests + is reached, whichever is sooner. + + For asynchronous requests, the server will + generate a solution (if possible) before the + timeout has elapsed. + model (google.cloud.optimization_v1.types.ShipmentModel): + Shipment model to solve. + solving_mode (google.cloud.optimization_v1.types.OptimizeToursRequest.SolvingMode): + By default, the solving mode is ``DEFAULT_SOLVE`` (0). + max_validation_errors (int): + Truncates the number of validation errors returned. These + errors are typically attached to an INVALID_ARGUMENT error + payload as a BadRequest error detail + (https://cloud.google.com/apis/design/errors#error_details), + unless solving_mode=VALIDATE_ONLY: see the + [OptimizeToursResponse.validation_errors][google.cloud.optimization.v1.OptimizeToursResponse.validation_errors] + field. This defaults to 100 and is capped at 10,000. + + This field is a member of `oneof`_ ``_max_validation_errors``. + search_mode (google.cloud.optimization_v1.types.OptimizeToursRequest.SearchMode): + Search mode used to solve the request. + injected_first_solution_routes (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute]): + Guide the optimization algorithm in finding a first solution + that is similar to a previous solution. + + The model is constrained when the first solution is built. + Any shipments not performed on a route are implicitly + skipped in the first solution, but they may be performed in + successive solutions. + + The solution must satisfy some basic validity assumptions: + + - for all routes, ``vehicle_index`` must be in range and + not be duplicated. + - for all visits, ``shipment_index`` and + ``visit_request_index`` must be in range. + - a shipment may only be referenced on one route. + - the pickup of a pickup-delivery shipment must be + performed before the delivery. + - no more than one pickup alternative or delivery + alternative of a shipment may be performed. + - for all routes, times are increasing (i.e., + ``vehicle_start_time <= visits[0].start_time <= visits[1].start_time ... <= vehicle_end_time``). + - a shipment may only be performed on a vehicle that is + allowed. A vehicle is allowed if + [Shipment.allowed_vehicle_indices][google.cloud.optimization.v1.Shipment.allowed_vehicle_indices] + is empty or its ``vehicle_index`` is included in + [Shipment.allowed_vehicle_indices][google.cloud.optimization.v1.Shipment.allowed_vehicle_indices]. + + If the injected solution is not feasible, a validation error + is not necessarily returned and an error indicating + infeasibility may be returned instead. + injected_solution_constraint (google.cloud.optimization_v1.types.InjectedSolutionConstraint): + Constrain the optimization algorithm to find + a final solution that is similar to a previous + solution. For example, this may be used to + freeze portions of routes which have already + been completed or which are to be completed but + must not be modified. + + If the injected solution is not feasible, a + validation error is not necessarily returned and + an error indicating infeasibility may be + returned instead. + refresh_details_routes (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute]): + If non-empty, the given routes will be refreshed, without + modifying their underlying sequence of visits or travel + times: only other details will be updated. This does not + solve the model. + + As of 2020/11, this only populates the polylines of + non-empty routes and requires that ``populate_polylines`` is + true. + + The ``route_polyline`` fields of the passed-in routes may be + inconsistent with route ``transitions``. + + This field must not be used together with + ``injected_first_solution_routes`` or + ``injected_solution_constraint``. + + ``Shipment.ignore`` and ``Vehicle.ignore`` have no effect on + the behavior. Polylines are still populated between all + visits in all non-empty routes regardless of whether the + related shipments or vehicles are ignored. + interpret_injected_solutions_using_labels (bool): + If true: + + - uses + [ShipmentRoute.vehicle_label][google.cloud.optimization.v1.ShipmentRoute.vehicle_label] + instead of ``vehicle_index`` to match routes in an + injected solution with vehicles in the request; reuses + the mapping of original + [ShipmentRoute.vehicle_index][google.cloud.optimization.v1.ShipmentRoute.vehicle_index] + to new + [ShipmentRoute.vehicle_index][google.cloud.optimization.v1.ShipmentRoute.vehicle_index] + to update + [ConstraintRelaxation.vehicle_indices][google.cloud.optimization.v1.InjectedSolutionConstraint.ConstraintRelaxation.vehicle_indices] + if non-empty, but the mapping must be unambiguous (i.e., + multiple ``ShipmentRoute``\ s must not share the same + original ``vehicle_index``). + - uses + [ShipmentRoute.Visit.shipment_label][google.cloud.optimization.v1.ShipmentRoute.Visit.shipment_label] + instead of ``shipment_index`` to match visits in an + injected solution with shipments in the request; + - uses + [SkippedShipment.label][google.cloud.optimization.v1.SkippedShipment.label] + instead of + [SkippedShipment.index][google.cloud.optimization.v1.SkippedShipment.index] + to match skipped shipments in the injected solution with + request shipments. + + This interpretation applies to the + ``injected_first_solution_routes``, + ``injected_solution_constraint``, and + ``refresh_details_routes`` fields. It can be used when + shipment or vehicle indices in the request have changed + since the solution was created, perhaps because shipments or + vehicles have been removed from or added to the request. + + If true, labels in the following categories must appear at + most once in their category: + + - [Vehicle.label][google.cloud.optimization.v1.Vehicle.label] + in the request; + - [Shipment.label][google.cloud.optimization.v1.Shipment.label] + in the request; + - [ShipmentRoute.vehicle_label][google.cloud.optimization.v1.ShipmentRoute.vehicle_label] + in the injected solution; + - [SkippedShipment.label][google.cloud.optimization.v1.SkippedShipment.label] + and + [ShipmentRoute.Visit.shipment_label][google.cloud.optimization.v1.ShipmentRoute.Visit.shipment_label] + in the injected solution (except pickup/delivery visit + pairs, whose ``shipment_label`` must appear twice). + + If a ``vehicle_label`` in the injected solution does not + correspond to a request vehicle, the corresponding route is + removed from the solution along with its visits. If a + ``shipment_label`` in the injected solution does not + correspond to a request shipment, the corresponding visit is + removed from the solution. If a + [SkippedShipment.label][google.cloud.optimization.v1.SkippedShipment.label] + in the injected solution does not correspond to a request + shipment, the ``SkippedShipment`` is removed from the + solution. + + Removing route visits or entire routes from an injected + solution may have an effect on the implied constraints, + which may lead to change in solution, validation errors, or + infeasibility. + + NOTE: The caller must ensure that each + [Vehicle.label][google.cloud.optimization.v1.Vehicle.label] + (resp. + [Shipment.label][google.cloud.optimization.v1.Shipment.label]) + uniquely identifies a vehicle (resp. shipment) entity used + across the two relevant requests: the past request that + produced the ``OptimizeToursResponse`` used in the injected + solution and the current request that includes the injected + solution. The uniqueness checks described above are not + enough to guarantee this requirement. + consider_road_traffic (bool): + Consider traffic estimation in calculating ``ShipmentRoute`` + fields + [Transition.travel_duration][google.cloud.optimization.v1.ShipmentRoute.Transition.travel_duration], + [Visit.start_time][google.cloud.optimization.v1.ShipmentRoute.Visit.start_time], + and ``vehicle_end_time``; in setting the + [ShipmentRoute.has_traffic_infeasibilities][google.cloud.optimization.v1.ShipmentRoute.has_traffic_infeasibilities] + field, and in calculating the + [OptimizeToursResponse.total_cost][google.cloud.optimization.v1.OptimizeToursResponse.total_cost] + field. + populate_polylines (bool): + If true, polylines will be populated in response + ``ShipmentRoute``\ s. + populate_transition_polylines (bool): + If true, polylines will be populated in response + [ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions]. + Note that in this case, the polylines will also be populated + in the deprecated ``travel_steps``. + allow_large_deadline_despite_interruption_risk (bool): + If this is set, then the request can have a + deadline (see https://grpc.io/blog/deadlines) of + up to 60 minutes. Otherwise, the maximum + deadline is only 30 minutes. Note that + long-lived requests have a significantly larger + (but still small) risk of interruption. + use_geodesic_distances (bool): + If true, travel distances will be computed using geodesic + distances instead of Google Maps distances, and travel times + will be computed using geodesic distances with a speed + defined by ``geodesic_meters_per_second``. + geodesic_meters_per_second (float): + When ``use_geodesic_distances`` is true, this field must be + set and defines the speed applied to compute travel times. + Its value must be at least 1.0 meters/seconds. + + This field is a member of `oneof`_ ``_geodesic_meters_per_second``. + label (str): + Label that may be used to identify this request, reported + back in the + [OptimizeToursResponse.request_label][google.cloud.optimization.v1.OptimizeToursResponse.request_label]. + populate_travel_step_polylines (bool): + Deprecated: Use + [OptimizeToursRequest.populate_transition_polylines][google.cloud.optimization.v1.OptimizeToursRequest.populate_transition_polylines] + instead. If true, polylines will be populated in response + [ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions]. + Note that in this case, the polylines will also be populated + in the deprecated ``travel_steps``. + """ + class SolvingMode(proto.Enum): + r"""Defines how the solver should handle the request. In all modes but + ``VALIDATE_ONLY``, if the request is invalid, you will receive an + ``INVALID_REQUEST`` error. See + [max_validation_errors][google.cloud.optimization.v1.OptimizeToursRequest.max_validation_errors] + to cap the number of errors returned. + + Values: + DEFAULT_SOLVE (0): + Solve the model. + VALIDATE_ONLY (1): + Only validates the model without solving it: populates as + many + [OptimizeToursResponse.validation_errors][google.cloud.optimization.v1.OptimizeToursResponse.validation_errors] + as possible. + DETECT_SOME_INFEASIBLE_SHIPMENTS (2): + Only populates + [OptimizeToursResponse.skipped_shipments][google.cloud.optimization.v1.OptimizeToursResponse.skipped_shipments], + and doesn't actually solve the rest of the request + (``status`` and ``routes`` are unset in the response). + + *IMPORTANT*: not all infeasible shipments are returned here, + but only the ones that are detected as infeasible as a + preprocessing. + """ + DEFAULT_SOLVE = 0 + VALIDATE_ONLY = 1 + DETECT_SOME_INFEASIBLE_SHIPMENTS = 2 + + class SearchMode(proto.Enum): + r"""Mode defining the behavior of the search, trading off latency + versus solution quality. In all modes, the global request + deadline is enforced. + + Values: + SEARCH_MODE_UNSPECIFIED (0): + Unspecified search mode, equivalent to ``RETURN_FAST``. + RETURN_FAST (1): + Stop the search after finding the first good + solution. + CONSUME_ALL_AVAILABLE_TIME (2): + Spend all the available time to search for + better solutions. + """ + SEARCH_MODE_UNSPECIFIED = 0 + RETURN_FAST = 1 + CONSUME_ALL_AVAILABLE_TIME = 2 + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + model: 'ShipmentModel' = proto.Field( + proto.MESSAGE, + number=3, + message='ShipmentModel', + ) + solving_mode: SolvingMode = proto.Field( + proto.ENUM, + number=4, + enum=SolvingMode, + ) + max_validation_errors: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + search_mode: SearchMode = proto.Field( + proto.ENUM, + number=6, + enum=SearchMode, + ) + injected_first_solution_routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='ShipmentRoute', + ) + injected_solution_constraint: 'InjectedSolutionConstraint' = proto.Field( + proto.MESSAGE, + number=8, + message='InjectedSolutionConstraint', + ) + refresh_details_routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='ShipmentRoute', + ) + interpret_injected_solutions_using_labels: bool = proto.Field( + proto.BOOL, + number=10, + ) + consider_road_traffic: bool = proto.Field( + proto.BOOL, + number=11, + ) + populate_polylines: bool = proto.Field( + proto.BOOL, + number=12, + ) + populate_transition_polylines: bool = proto.Field( + proto.BOOL, + number=13, + ) + allow_large_deadline_despite_interruption_risk: bool = proto.Field( + proto.BOOL, + number=14, + ) + use_geodesic_distances: bool = proto.Field( + proto.BOOL, + number=15, + ) + geodesic_meters_per_second: float = proto.Field( + proto.DOUBLE, + number=16, + optional=True, + ) + label: str = proto.Field( + proto.STRING, + number=17, + ) + populate_travel_step_polylines: bool = proto.Field( + proto.BOOL, + number=20, + ) + + +class OptimizeToursResponse(proto.Message): + r"""Response after solving a tour optimization problem containing + the routes followed by each vehicle, the shipments which have + been skipped and the overall cost of the solution. + + Attributes: + routes (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute]): + Routes computed for each vehicle; the i-th + route corresponds to the i-th vehicle in the + model. + request_label (str): + Copy of the + [OptimizeToursRequest.label][google.cloud.optimization.v1.OptimizeToursRequest.label], + if a label was specified in the request. + skipped_shipments (MutableSequence[google.cloud.optimization_v1.types.SkippedShipment]): + The list of all shipments skipped. + validation_errors (MutableSequence[google.cloud.optimization_v1.types.OptimizeToursValidationError]): + List of all the validation errors that we were able to + detect independently. See the "MULTIPLE ERRORS" explanation + for the + [OptimizeToursValidationError][google.cloud.optimization.v1.OptimizeToursValidationError] + message. + metrics (google.cloud.optimization_v1.types.OptimizeToursResponse.Metrics): + Duration, distance and usage metrics for this + solution. + total_cost (float): + Deprecated: Use + [Metrics.total_cost][google.cloud.optimization.v1.OptimizeToursResponse.Metrics.total_cost] + instead. Total cost of the solution. This takes into account + all costs: costs per per hour and travel hour, fixed vehicle + costs, unperformed shipment penalty costs, global duration + cost, etc. + """ + + class Metrics(proto.Message): + r"""Overall metrics, aggregated over all routes. + + Attributes: + aggregated_route_metrics (google.cloud.optimization_v1.types.AggregatedMetrics): + Aggregated over the routes. Each metric is the sum (or max, + for loads) over all + [ShipmentRoute.metrics][google.cloud.optimization.v1.ShipmentRoute.metrics] + fields of the same name. + skipped_mandatory_shipment_count (int): + Number of mandatory shipments skipped. + used_vehicle_count (int): + Number of vehicles used. Note: if a vehicle route is empty + and + [Vehicle.used_if_route_is_empty][google.cloud.optimization.v1.Vehicle.used_if_route_is_empty] + is true, the vehicle is considered used. + earliest_vehicle_start_time (google.protobuf.timestamp_pb2.Timestamp): + The earliest start time for a used vehicle, computed as the + minimum over all used vehicles of + [ShipmentRoute.vehicle_start_time][google.cloud.optimization.v1.ShipmentRoute.vehicle_start_time]. + latest_vehicle_end_time (google.protobuf.timestamp_pb2.Timestamp): + The latest end time for a used vehicle, computed as the + maximum over all used vehicles of + [ShipmentRoute.vehicle_end_time][google.cloud.optimization.v1.ShipmentRoute.vehicle_end_time]. + costs (MutableMapping[str, float]): + Cost of the solution, broken down by cost-related request + fields. The keys are proto paths, relative to the input + OptimizeToursRequest, e.g. "model.shipments.pickups.cost", + and the values are the total cost generated by the + corresponding cost field, aggregated over the whole + solution. In other words, + costs["model.shipments.pickups.cost"] is the sum of all + pickup costs over the solution. All costs defined in the + model are reported in detail here with the exception of + costs related to TransitionAttributes that are only reported + in an aggregated way as of 2022/01. + total_cost (float): + Total cost of the solution. The sum of all + values in the costs map. + """ + + aggregated_route_metrics: 'AggregatedMetrics' = proto.Field( + proto.MESSAGE, + number=1, + message='AggregatedMetrics', + ) + skipped_mandatory_shipment_count: int = proto.Field( + proto.INT32, + number=2, + ) + used_vehicle_count: int = proto.Field( + proto.INT32, + number=3, + ) + earliest_vehicle_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + latest_vehicle_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + costs: MutableMapping[str, float] = proto.MapField( + proto.STRING, + proto.DOUBLE, + number=10, + ) + total_cost: float = proto.Field( + proto.DOUBLE, + number=6, + ) + + routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ShipmentRoute', + ) + request_label: str = proto.Field( + proto.STRING, + number=3, + ) + skipped_shipments: MutableSequence['SkippedShipment'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='SkippedShipment', + ) + validation_errors: MutableSequence['OptimizeToursValidationError'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='OptimizeToursValidationError', + ) + metrics: Metrics = proto.Field( + proto.MESSAGE, + number=6, + message=Metrics, + ) + total_cost: float = proto.Field( + proto.DOUBLE, + number=2, + ) + + +class BatchOptimizeToursRequest(proto.Message): + r"""Request to batch optimize tours as an asynchronous operation. Each + input file should contain one ``OptimizeToursRequest``, and each + output file will contain one ``OptimizeToursResponse``. The request + contains information to read/write and parse the files. All the + input and output files should be under the same project. + + Attributes: + parent (str): + Required. Target project and location to make a call. + + Format: ``projects/{project-id}/locations/{location-id}``. + + If no location is specified, a region will be chosen + automatically. + model_configs (MutableSequence[google.cloud.optimization_v1.types.BatchOptimizeToursRequest.AsyncModelConfig]): + Required. Input/Output information each + purchase model, such as file paths and data + formats. + """ + + class AsyncModelConfig(proto.Message): + r"""Information for solving one optimization model + asynchronously. + + Attributes: + display_name (str): + User defined model name, can be used as alias + by users to keep track of models. + input_config (google.cloud.optimization_v1.types.InputConfig): + Required. Information about the input model. + output_config (google.cloud.optimization_v1.types.OutputConfig): + Required. The desired output location + information. + enable_checkpoints (bool): + If this is set, the model will be solved in the checkpoint + mode. In this mode, the input model can have a deadline + longer than 30 mins without the risk of interruption. The + model will be solved in multiple short-running stages. Each + stage generates an intermediate checkpoint and stores it in + the user's Cloud Storage buckets. The checkpoint mode should + be preferred over + allow_large_deadline_despite_interruption_risk since it + prevents the risk of interruption. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + input_config: async_model.InputConfig = proto.Field( + proto.MESSAGE, + number=2, + message=async_model.InputConfig, + ) + output_config: async_model.OutputConfig = proto.Field( + proto.MESSAGE, + number=3, + message=async_model.OutputConfig, + ) + enable_checkpoints: bool = proto.Field( + proto.BOOL, + number=4, + ) + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + model_configs: MutableSequence[AsyncModelConfig] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=AsyncModelConfig, + ) + + +class BatchOptimizeToursResponse(proto.Message): + r"""Response to a ``BatchOptimizeToursRequest``. This is returned in the + LRO Operation after the operation is complete. + + """ + + +class ShipmentModel(proto.Message): + r"""A shipment model contains a set of shipments which must be performed + by a set of vehicles, while minimizing the overall cost, which is + the sum of: + + - the cost of routing the vehicles (sum of cost per total time, + cost per travel time, and fixed cost over all vehicles). + - the unperformed shipment penalties. + - the cost of the global duration of the shipments + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + shipments (MutableSequence[google.cloud.optimization_v1.types.Shipment]): + Set of shipments which must be performed in + the model. + vehicles (MutableSequence[google.cloud.optimization_v1.types.Vehicle]): + Set of vehicles which can be used to perform + visits. + max_active_vehicles (int): + Constrains the maximum number of active + vehicles. A vehicle is active if its route + performs at least one shipment. This can be used + to limit the number of routes in the case where + there are fewer drivers than vehicles and that + the fleet of vehicles is heterogeneous. The + optimization will then select the best subset of + vehicles to use. Must be strictly positive. + + This field is a member of `oneof`_ ``_max_active_vehicles``. + global_start_time (google.protobuf.timestamp_pb2.Timestamp): + Global start and end time of the model: no times outside of + this range can be considered valid. + + The model's time span must be less than a year, i.e. the + ``global_end_time`` and the ``global_start_time`` must be + within 31536000 seconds of each other. + + When using ``cost_per_*hour`` fields, you might want to set + this window to a smaller interval to increase performance + (eg. if you model a single day, you should set the global + time limits to that day). If unset, 00:00:00 UTC, January 1, + 1970 (i.e. seconds: 0, nanos: 0) is used as default. + global_end_time (google.protobuf.timestamp_pb2.Timestamp): + If unset, 00:00:00 UTC, January 1, 1971 (i.e. + seconds: 31536000, nanos: 0) is used as default. + global_duration_cost_per_hour (float): + The "global duration" of the overall plan is the difference + between the earliest effective start time and the latest + effective end time of all vehicles. Users can assign a cost + per hour to that quantity to try and optimize for earliest + job completion, for example. This cost must be in the same + unit as + [Shipment.penalty_cost][google.cloud.optimization.v1.Shipment.penalty_cost]. + duration_distance_matrices (MutableSequence[google.cloud.optimization_v1.types.ShipmentModel.DurationDistanceMatrix]): + Specifies duration and distance matrices used in the model. + If this field is empty, Google Maps or geodesic distances + will be used instead, depending on the value of the + ``use_geodesic_distances`` field. If it is not empty, + ``use_geodesic_distances`` cannot be true and neither + ``duration_distance_matrix_src_tags`` nor + ``duration_distance_matrix_dst_tags`` can be empty. + + Usage examples: + + - There are two locations: locA and locB. + - 1 vehicle starting its route at locA and ending it at + locA. + - 1 pickup visit request at locB. + + :: + + model { + vehicles { start_tags: "locA" end_tags: "locA" } + shipments { pickups { tags: "locB" } } + duration_distance_matrix_src_tags: "locA" + duration_distance_matrix_src_tags: "locB" + duration_distance_matrix_dst_tags: "locA" + duration_distance_matrix_dst_tags: "locB" + duration_distance_matrices { + rows { # from: locA + durations { seconds: 0 } meters: 0 # to: locA + durations { seconds: 100 } meters: 1000 # to: locB + } + rows { # from: locB + durations { seconds: 102 } meters: 990 # to: locA + durations { seconds: 0 } meters: 0 # to: locB + } + } + } + + - There are three locations: locA, locB and locC. + - 1 vehicle starting its route at locA and ending it at + locB, using matrix "fast". + - 1 vehicle starting its route at locB and ending it at + locB, using matrix "slow". + - 1 vehicle starting its route at locB and ending it at + locB, using matrix "fast". + - 1 pickup visit request at locC. + + :: + + model { + vehicles { start_tags: "locA" end_tags: "locB" start_tags: "fast" } + vehicles { start_tags: "locB" end_tags: "locB" start_tags: "slow" } + vehicles { start_tags: "locB" end_tags: "locB" start_tags: "fast" } + shipments { pickups { tags: "locC" } } + duration_distance_matrix_src_tags: "locA" + duration_distance_matrix_src_tags: "locB" + duration_distance_matrix_src_tags: "locC" + duration_distance_matrix_dst_tags: "locB" + duration_distance_matrix_dst_tags: "locC" + duration_distance_matrices { + vehicle_start_tag: "fast" + rows { # from: locA + durations { seconds: 1000 } meters: 2000 # to: locB + durations { seconds: 600 } meters: 1000 # to: locC + } + rows { # from: locB + durations { seconds: 0 } meters: 0 # to: locB + durations { seconds: 700 } meters: 1200 # to: locC + } + rows { # from: locC + durations { seconds: 702 } meters: 1190 # to: locB + durations { seconds: 0 } meters: 0 # to: locC + } + } + duration_distance_matrices { + vehicle_start_tag: "slow" + rows { # from: locA + durations { seconds: 1800 } meters: 2001 # to: locB + durations { seconds: 900 } meters: 1002 # to: locC + } + rows { # from: locB + durations { seconds: 0 } meters: 0 # to: locB + durations { seconds: 1000 } meters: 1202 # to: locC + } + rows { # from: locC + durations { seconds: 1001 } meters: 1195 # to: locB + durations { seconds: 0 } meters: 0 # to: locC + } + } + } + duration_distance_matrix_src_tags (MutableSequence[str]): + Tags defining the sources of the duration and distance + matrices; ``duration_distance_matrices(i).rows(j)`` defines + durations and distances from visits with tag + ``duration_distance_matrix_src_tags(j)`` to other visits in + matrix i. + + Tags correspond to + [VisitRequest.tags][google.cloud.optimization.v1.Shipment.VisitRequest.tags] + or + [Vehicle.start_tags][google.cloud.optimization.v1.Vehicle.start_tags]. + A given ``VisitRequest`` or ``Vehicle`` must match exactly + one tag in this field. Note that a ``Vehicle``'s source, + destination and matrix tags may be the same; similarly a + ``VisitRequest``'s source and destination tags may be the + same. All tags must be different and cannot be empty + strings. If this field is not empty, then + ``duration_distance_matrices`` must not be empty. + duration_distance_matrix_dst_tags (MutableSequence[str]): + Tags defining the destinations of the duration and distance + matrices; + ``duration_distance_matrices(i).rows(j).durations(k)`` + (resp. ``duration_distance_matrices(i).rows(j).meters(k))`` + defines the duration (resp. the distance) of the travel from + visits with tag ``duration_distance_matrix_src_tags(j)`` to + visits with tag ``duration_distance_matrix_dst_tags(k)`` in + matrix i. + + Tags correspond to + [VisitRequest.tags][google.cloud.optimization.v1.Shipment.VisitRequest.tags] + or + [Vehicle.start_tags][google.cloud.optimization.v1.Vehicle.start_tags]. + A given ``VisitRequest`` or ``Vehicle`` must match exactly + one tag in this field. Note that a ``Vehicle``'s source, + destination and matrix tags may be the same; similarly a + ``VisitRequest``'s source and destination tags may be the + same. All tags must be different and cannot be empty + strings. If this field is not empty, then + ``duration_distance_matrices`` must not be empty. + transition_attributes (MutableSequence[google.cloud.optimization_v1.types.TransitionAttributes]): + Transition attributes added to the model. + shipment_type_incompatibilities (MutableSequence[google.cloud.optimization_v1.types.ShipmentTypeIncompatibility]): + Sets of incompatible shipment_types (see + ``ShipmentTypeIncompatibility``). + shipment_type_requirements (MutableSequence[google.cloud.optimization_v1.types.ShipmentTypeRequirement]): + Sets of ``shipment_type`` requirements (see + ``ShipmentTypeRequirement``). + precedence_rules (MutableSequence[google.cloud.optimization_v1.types.ShipmentModel.PrecedenceRule]): + Set of precedence rules which must be + enforced in the model. + break_rules (MutableSequence[google.cloud.optimization_v1.types.ShipmentModel.BreakRule]): + Deprecated: No longer used. Set of break rules used in the + model. Each vehicle specifies the ``BreakRule`` that applies + to it via the + [Vehicle.break_rule_indices][google.cloud.optimization.v1.Vehicle.break_rule_indices] + field (which must be a singleton). + """ + + class DurationDistanceMatrix(proto.Message): + r"""Specifies a duration and distance matrix from visit and + vehicle start locations to visit and vehicle end locations. + + Attributes: + rows (MutableSequence[google.cloud.optimization_v1.types.ShipmentModel.DurationDistanceMatrix.Row]): + Specifies the rows of the duration and distance matrix. It + must have as many elements as + [ShipmentModel.duration_distance_matrix_src_tags][google.cloud.optimization.v1.ShipmentModel.duration_distance_matrix_src_tags]. + vehicle_start_tag (str): + Tag defining to which vehicles this duration and distance + matrix applies. If empty, this applies to all vehicles, and + there can only be a single matrix. + + Each vehicle start must match exactly one matrix, i.e. + exactly one of their ``start_tags`` field must match the + ``vehicle_start_tag`` of a matrix (and of that matrix only). + + All matrices must have a different ``vehicle_start_tag``. + """ + + class Row(proto.Message): + r"""Specifies a row of the duration and distance matrix. + + Attributes: + durations (MutableSequence[google.protobuf.duration_pb2.Duration]): + Duration values for a given row. It must have as many + elements as + [ShipmentModel.duration_distance_matrix_dst_tags][google.cloud.optimization.v1.ShipmentModel.duration_distance_matrix_dst_tags]. + meters (MutableSequence[float]): + Distance values for a given row. If no costs or constraints + refer to distances in the model, this can be left empty; + otherwise it must have as many elements as ``durations``. + """ + + durations: MutableSequence[duration_pb2.Duration] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + meters: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + + rows: MutableSequence['ShipmentModel.DurationDistanceMatrix.Row'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ShipmentModel.DurationDistanceMatrix.Row', + ) + vehicle_start_tag: str = proto.Field( + proto.STRING, + number=2, + ) + + class PrecedenceRule(proto.Message): + r"""A precedence rule between two events (each event is the pickup or + the delivery of a shipment): the "second" event has to start at + least ``offset_duration`` after "first" has started. + + Several precedences can refer to the same (or related) events, e.g., + "pickup of B happens after delivery of A" and "pickup of C happens + after pickup of B". + + Furthermore, precedences only apply when both shipments are + performed and are otherwise ignored. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + first_index (int): + Shipment index of the "first" event. This + field must be specified. + + This field is a member of `oneof`_ ``_first_index``. + first_is_delivery (bool): + Indicates if the "first" event is a delivery. + second_index (int): + Shipment index of the "second" event. This + field must be specified. + + This field is a member of `oneof`_ ``_second_index``. + second_is_delivery (bool): + Indicates if the "second" event is a + delivery. + offset_duration (google.protobuf.duration_pb2.Duration): + The offset between the "first" and "second" + event. It can be negative. + """ + + first_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + first_is_delivery: bool = proto.Field( + proto.BOOL, + number=3, + ) + second_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + second_is_delivery: bool = proto.Field( + proto.BOOL, + number=4, + ) + offset_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + + class BreakRule(proto.Message): + r"""Deprecated: Use top level + [BreakRule][google.cloud.optimization.v1.ShipmentModel.BreakRule] + instead. Rules to generate time breaks for a vehicle (e.g. lunch + breaks). A break is a contiguous period of time during which the + vehicle remains idle at its current position and cannot perform any + visit. A break may occur: + + - during the travel between two visits (which includes the time + right before or right after a visit, but not in the middle of a + visit), in which case it extends the corresponding transit time + between the visits + - before the vehicle start (the vehicle may not start in the middle + of a break), in which case it does not affect the vehicle start + time. + - after the vehicle end (ditto, with the vehicle end time). + + Attributes: + break_requests (MutableSequence[google.cloud.optimization_v1.types.ShipmentModel.BreakRule.BreakRequest]): + Sequence of breaks. See the ``BreakRequest`` message. + frequency_constraints (MutableSequence[google.cloud.optimization_v1.types.ShipmentModel.BreakRule.FrequencyConstraint]): + Several ``FrequencyConstraint`` may apply. They must all be + satisfied by the ``BreakRequest``\ s of this ``BreakRule``. + See ``FrequencyConstraint``. + """ + + class BreakRequest(proto.Message): + r"""The sequence of breaks (i.e. their number and order) that apply to + each vehicle must be known beforehand. The repeated + ``BreakRequest``\ s define that sequence, in the order in which they + must occur. Their time windows (``earliest_start_time`` / + ``latest_start_time``) may overlap, but they must be compatible with + the order (this is checked). + + Attributes: + earliest_start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Lower bound (inclusive) on the + start of the break. + latest_start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Upper bound (inclusive) on the + start of the break. + min_duration (google.protobuf.duration_pb2.Duration): + Required. Minimum duration of the break. Must + be positive. + """ + + earliest_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + latest_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + min_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + class FrequencyConstraint(proto.Message): + r"""One may further constrain the frequency and duration of the breaks + specified above, by enforcing a minimum break frequency, such as + "There must be a break of at least 1 hour every 12 hours". Assuming + that this can be interpreted as "Within any sliding time window of + 12h, there must be at least one break of at least one hour", that + example would translate to the following ``FrequencyConstraint``: + + :: + + { + min_break_duration { seconds: 3600 } # 1 hour. + max_inter_break_duration { seconds: 39600 } # 11 hours (12 - 1 = 11). + } + + The timing and duration of the breaks in the solution will respect + all such constraints, in addition to the time windows and minimum + durations already specified in the ``BreakRequest``. + + A ``FrequencyConstraint`` may in practice apply to non-consecutive + breaks. For example, the following schedule honors the "1h every + 12h" example: + + :: + + 04:00 vehicle start + .. performing travel and visits .. + 09:00 1 hour break + 10:00 end of the break + .. performing travel and visits .. + 12:00 20-min lunch break + 12:20 end of the break + .. performing travel and visits .. + 21:00 1 hour break + 22:00 end of the break + .. performing travel and visits .. + 23:59 vehicle end + + Attributes: + min_break_duration (google.protobuf.duration_pb2.Duration): + Required. Minimum break duration for this constraint. + Nonnegative. See description of ``FrequencyConstraint``. + max_inter_break_duration (google.protobuf.duration_pb2.Duration): + Required. Maximum allowed span of any interval of time in + the route that does not include at least partially a break + of ``duration >= min_break_duration``. Must be positive. + """ + + min_break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + max_inter_break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + break_requests: MutableSequence['ShipmentModel.BreakRule.BreakRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ShipmentModel.BreakRule.BreakRequest', + ) + frequency_constraints: MutableSequence['ShipmentModel.BreakRule.FrequencyConstraint'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ShipmentModel.BreakRule.FrequencyConstraint', + ) + + shipments: MutableSequence['Shipment'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Shipment', + ) + vehicles: MutableSequence['Vehicle'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Vehicle', + ) + max_active_vehicles: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + global_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + global_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + global_duration_cost_per_hour: float = proto.Field( + proto.DOUBLE, + number=7, + ) + duration_distance_matrices: MutableSequence[DurationDistanceMatrix] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=DurationDistanceMatrix, + ) + duration_distance_matrix_src_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + duration_distance_matrix_dst_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + transition_attributes: MutableSequence['TransitionAttributes'] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='TransitionAttributes', + ) + shipment_type_incompatibilities: MutableSequence['ShipmentTypeIncompatibility'] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='ShipmentTypeIncompatibility', + ) + shipment_type_requirements: MutableSequence['ShipmentTypeRequirement'] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message='ShipmentTypeRequirement', + ) + precedence_rules: MutableSequence[PrecedenceRule] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=PrecedenceRule, + ) + break_rules: MutableSequence[BreakRule] = proto.RepeatedField( + proto.MESSAGE, + number=15, + message=BreakRule, + ) + + +class Shipment(proto.Message): + r"""The shipment of a single item, from one of its pickups to one + of its deliveries. For the shipment to be considered as + performed, a unique vehicle must visit one of its pickup + locations (and decrease its spare capacities accordingly), then + visit one of its delivery locations later on (and therefore + re-increase its spare capacities accordingly). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + pickups (MutableSequence[google.cloud.optimization_v1.types.Shipment.VisitRequest]): + Set of pickup alternatives associated to the + shipment. If not specified, the vehicle only + needs to visit a location corresponding to the + deliveries. + deliveries (MutableSequence[google.cloud.optimization_v1.types.Shipment.VisitRequest]): + Set of delivery alternatives associated to + the shipment. If not specified, the vehicle only + needs to visit a location corresponding to the + pickups. + load_demands (MutableMapping[str, google.cloud.optimization_v1.types.Shipment.Load]): + Load demands of the shipment (for example weight, volume, + number of pallets etc). The keys in the map should be + identifiers describing the type of the corresponding load, + ideally also including the units. For example: "weight_kg", + "volume_gallons", "pallet_count", etc. If a given key does + not appear in the map, the corresponding load is considered + as null. + penalty_cost (float): + If the shipment is not completed, this penalty is added to + the overall cost of the routes. A shipment is considered + completed if one of its pickup and delivery alternatives is + visited. The cost may be expressed in the same unit used for + all other cost-related fields in the model and must be + positive. + + *IMPORTANT*: If this penalty is not specified, it is + considered infinite, i.e. the shipment must be completed. + + This field is a member of `oneof`_ ``_penalty_cost``. + allowed_vehicle_indices (MutableSequence[int]): + The set of vehicles that may perform this shipment. If + empty, all vehicles may perform it. Vehicles are given by + their index in the ``ShipmentModel``'s ``vehicles`` list. + costs_per_vehicle (MutableSequence[float]): + Specifies the cost that is incurred when this shipment is + delivered by each vehicle. If specified, it must have + EITHER: + + - the same number of elements as + ``costs_per_vehicle_indices``. ``costs_per_vehicle[i]`` + corresponds to vehicle ``costs_per_vehicle_indices[i]`` + of the model. + - the same number of elements as there are vehicles in the + model. The i-th element corresponds to vehicle #i of the + model. + + These costs must be in the same unit as ``penalty_cost`` and + must not be negative. Leave this field empty, if there are + no such costs. + costs_per_vehicle_indices (MutableSequence[int]): + Indices of the vehicles to which ``costs_per_vehicle`` + applies. If non-empty, it must have the same number of + elements as ``costs_per_vehicle``. A vehicle index may not + be specified more than once. If a vehicle is excluded from + ``costs_per_vehicle_indices``, its cost is zero. + pickup_to_delivery_relative_detour_limit (float): + Specifies the maximum relative detour time compared to the + shortest path from pickup to delivery. If specified, it must + be nonnegative, and the shipment must contain at least a + pickup and a delivery. + + For example, let t be the shortest time taken to go from the + selected pickup alternative directly to the selected + delivery alternative. Then setting + ``pickup_to_delivery_relative_detour_limit`` enforces: + + :: + + start_time(delivery) - start_time(pickup) <= + std::ceil(t * (1.0 + pickup_to_delivery_relative_detour_limit)) + + If both relative and absolute limits are specified on the + same shipment, the more constraining limit is used for each + possible pickup/delivery pair. As of 2017/10, detours are + only supported when travel durations do not depend on + vehicles. + + This field is a member of `oneof`_ ``_pickup_to_delivery_relative_detour_limit``. + pickup_to_delivery_absolute_detour_limit (google.protobuf.duration_pb2.Duration): + Specifies the maximum absolute detour time compared to the + shortest path from pickup to delivery. If specified, it must + be nonnegative, and the shipment must contain at least a + pickup and a delivery. + + For example, let t be the shortest time taken to go from the + selected pickup alternative directly to the selected + delivery alternative. Then setting + ``pickup_to_delivery_absolute_detour_limit`` enforces: + + :: + + start_time(delivery) - start_time(pickup) <= + t + pickup_to_delivery_absolute_detour_limit + + If both relative and absolute limits are specified on the + same shipment, the more constraining limit is used for each + possible pickup/delivery pair. As of 2017/10, detours are + only supported when travel durations do not depend on + vehicles. + pickup_to_delivery_time_limit (google.protobuf.duration_pb2.Duration): + Specifies the maximum duration from start of + pickup to start of delivery of a shipment. If + specified, it must be nonnegative, and the + shipment must contain at least a pickup and a + delivery. This does not depend on which + alternatives are selected for pickup and + delivery, nor on vehicle speed. This can be + specified alongside maximum detour constraints: + the solution will respect both specifications. + shipment_type (str): + Non-empty string specifying a "type" for this shipment. This + feature can be used to define incompatibilities or + requirements between ``shipment_types`` (see + ``shipment_type_incompatibilities`` and + ``shipment_type_requirements`` in ``ShipmentModel``). + + Differs from ``visit_types`` which is specified for a single + visit: All pickup/deliveries belonging to the same shipment + share the same ``shipment_type``. + label (str): + Specifies a label for this shipment. This label is reported + in the response in the ``shipment_label`` of the + corresponding + [ShipmentRoute.Visit][google.cloud.optimization.v1.ShipmentRoute.Visit]. + ignore (bool): + If true, skip this shipment, but don't apply a + ``penalty_cost``. + + Ignoring a shipment results in a validation error when there + are any ``shipment_type_requirements`` in the model. + + Ignoring a shipment that is performed in + ``injected_first_solution_routes`` or + ``injected_solution_constraint`` is permitted; the solver + removes the related pickup/delivery visits from the + performing route. ``precedence_rules`` that reference + ignored shipments will also be ignored. + demands (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): + Deprecated: Use + [Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands] + instead. + """ + + class VisitRequest(proto.Message): + r"""Request for a visit which can be done by a vehicle: it has a + geo-location (or two, see below), opening and closing times + represented by time windows, and a service duration time (time + spent by the vehicle once it has arrived to pickup or drop off + goods). + + Attributes: + arrival_location (google.type.latlng_pb2.LatLng): + The geo-location where the vehicle arrives when performing + this ``VisitRequest``. If the shipment model has duration + distance matrices, ``arrival_location`` must not be + specified. + arrival_waypoint (google.cloud.optimization_v1.types.Waypoint): + The waypoint where the vehicle arrives when performing this + ``VisitRequest``. If the shipment model has duration + distance matrices, ``arrival_waypoint`` must not be + specified. + departure_location (google.type.latlng_pb2.LatLng): + The geo-location where the vehicle departs after completing + this ``VisitRequest``. Can be omitted if it is the same as + ``arrival_location``. If the shipment model has duration + distance matrices, ``departure_location`` must not be + specified. + departure_waypoint (google.cloud.optimization_v1.types.Waypoint): + The waypoint where the vehicle departs after completing this + ``VisitRequest``. Can be omitted if it is the same as + ``arrival_waypoint``. If the shipment model has duration + distance matrices, ``departure_waypoint`` must not be + specified. + tags (MutableSequence[str]): + Specifies tags attached to the visit request. + Empty or duplicate strings are not allowed. + time_windows (MutableSequence[google.cloud.optimization_v1.types.TimeWindow]): + Time windows which constrain the arrival time at a visit. + Note that a vehicle may depart outside of the arrival time + window, i.e. arrival time + duration do not need to be + inside a time window. This can result in waiting time if the + vehicle arrives before + [TimeWindow.start_time][google.cloud.optimization.v1.TimeWindow.start_time]. + + The absence of ``TimeWindow`` means that the vehicle can + perform this visit at any time. + + Time windows must be disjoint, i.e. no time window must + overlap with or be adjacent to another, and they must be in + increasing order. + + ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` + can only be set if there is a single time window. + duration (google.protobuf.duration_pb2.Duration): + Duration of the visit, i.e. time spent by the vehicle + between arrival and departure (to be added to the possible + waiting time; see ``time_windows``). + cost (float): + Cost to service this visit request on a vehicle route. This + can be used to pay different costs for each alternative + pickup or delivery of a shipment. This cost must be in the + same unit as ``Shipment.penalty_cost`` and must not be + negative. + load_demands (MutableMapping[str, google.cloud.optimization_v1.types.Shipment.Load]): + Load demands of this visit request. This is just like + [Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands] + field, except that it only applies to this + [VisitRequest][google.cloud.optimization.v1.Shipment.VisitRequest] + instead of the whole + [Shipment][google.cloud.optimization.v1.Shipment]. The + demands listed here are added to the demands listed in + [Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands]. + visit_types (MutableSequence[str]): + Specifies the types of the visit. This may be used to + allocate additional time required for a vehicle to complete + this visit (see + [Vehicle.extra_visit_duration_for_visit_type][google.cloud.optimization.v1.Vehicle.extra_visit_duration_for_visit_type]). + + A type can only appear once. + label (str): + Specifies a label for this ``VisitRequest``. This label is + reported in the response as ``visit_label`` in the + corresponding + [ShipmentRoute.Visit][google.cloud.optimization.v1.ShipmentRoute.Visit]. + demands (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): + Deprecated: Use + [VisitRequest.load_demands][google.cloud.optimization.v1.Shipment.VisitRequest.load_demands] + instead. + """ + + arrival_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + arrival_waypoint: 'Waypoint' = proto.Field( + proto.MESSAGE, + number=2, + message='Waypoint', + ) + departure_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=3, + message=latlng_pb2.LatLng, + ) + departure_waypoint: 'Waypoint' = proto.Field( + proto.MESSAGE, + number=4, + message='Waypoint', + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + time_windows: MutableSequence['TimeWindow'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='TimeWindow', + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + cost: float = proto.Field( + proto.DOUBLE, + number=8, + ) + load_demands: MutableMapping[str, 'Shipment.Load'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=12, + message='Shipment.Load', + ) + visit_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + label: str = proto.Field( + proto.STRING, + number=11, + ) + demands: MutableSequence['CapacityQuantity'] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='CapacityQuantity', + ) + + class Load(proto.Message): + r"""When performing a visit, a predefined amount may be added to the + vehicle load if it's a pickup, or subtracted if it's a delivery. + This message defines such amount. See + [load_demands][google.cloud.optimization.v1.Shipment.load_demands]. + + Attributes: + amount (int): + The amount by which the load of the vehicle + performing the corresponding visit will vary. + Since it is an integer, users are advised to + choose an appropriate unit to avoid loss of + precision. Must be ≥ 0. + """ + + amount: int = proto.Field( + proto.INT64, + number=2, + ) + + pickups: MutableSequence[VisitRequest] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=VisitRequest, + ) + deliveries: MutableSequence[VisitRequest] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=VisitRequest, + ) + load_demands: MutableMapping[str, Load] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=14, + message=Load, + ) + penalty_cost: float = proto.Field( + proto.DOUBLE, + number=4, + optional=True, + ) + allowed_vehicle_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=5, + ) + costs_per_vehicle: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=6, + ) + costs_per_vehicle_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=7, + ) + pickup_to_delivery_relative_detour_limit: float = proto.Field( + proto.DOUBLE, + number=8, + optional=True, + ) + pickup_to_delivery_absolute_detour_limit: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=9, + message=duration_pb2.Duration, + ) + pickup_to_delivery_time_limit: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=10, + message=duration_pb2.Duration, + ) + shipment_type: str = proto.Field( + proto.STRING, + number=11, + ) + label: str = proto.Field( + proto.STRING, + number=12, + ) + ignore: bool = proto.Field( + proto.BOOL, + number=13, + ) + demands: MutableSequence['CapacityQuantity'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='CapacityQuantity', + ) + + +class ShipmentTypeIncompatibility(proto.Message): + r"""Specifies incompatibilties between shipments depending on their + shipment_type. The appearance of incompatible shipments on the same + route is restricted based on the incompatibility mode. + + Attributes: + types (MutableSequence[str]): + List of incompatible types. Two shipments having different + ``shipment_types`` among those listed are "incompatible". + incompatibility_mode (google.cloud.optimization_v1.types.ShipmentTypeIncompatibility.IncompatibilityMode): + Mode applied to the incompatibility. + """ + class IncompatibilityMode(proto.Enum): + r"""Modes defining how the appearance of incompatible shipments + are restricted on the same route. + + Values: + INCOMPATIBILITY_MODE_UNSPECIFIED (0): + Unspecified incompatibility mode. This value + should never be used. + NOT_PERFORMED_BY_SAME_VEHICLE (1): + In this mode, two shipments with incompatible + types can never share the same vehicle. + NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY (2): + For two shipments with incompatible types with the + ``NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY`` incompatibility mode: + + - If both are pickups only (no deliveries) or deliveries + only (no pickups), they cannot share the same vehicle at + all. + - If one of the shipments has a delivery and the other a + pickup, the two shipments can share the same vehicle iff + the former shipment is delivered before the latter is + picked up. + """ + INCOMPATIBILITY_MODE_UNSPECIFIED = 0 + NOT_PERFORMED_BY_SAME_VEHICLE = 1 + NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY = 2 + + types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + incompatibility_mode: IncompatibilityMode = proto.Field( + proto.ENUM, + number=2, + enum=IncompatibilityMode, + ) + + +class ShipmentTypeRequirement(proto.Message): + r"""Specifies requirements between shipments based on their + shipment_type. The specifics of the requirement are defined by the + requirement mode. + + Attributes: + required_shipment_type_alternatives (MutableSequence[str]): + List of alternative shipment types required by the + ``dependent_shipment_types``. + dependent_shipment_types (MutableSequence[str]): + All shipments with a type in the + ``dependent_shipment_types`` field require at least one + shipment of type ``required_shipment_type_alternatives`` to + be visited on the same route. + + NOTE: Chains of requirements such that a ``shipment_type`` + depends on itself are not allowed. + requirement_mode (google.cloud.optimization_v1.types.ShipmentTypeRequirement.RequirementMode): + Mode applied to the requirement. + """ + class RequirementMode(proto.Enum): + r"""Modes defining the appearance of dependent shipments on a + route. + + Values: + REQUIREMENT_MODE_UNSPECIFIED (0): + Unspecified requirement mode. This value + should never be used. + PERFORMED_BY_SAME_VEHICLE (1): + In this mode, all "dependent" shipments must + share the same vehicle as at least one of their + "required" shipments. + IN_SAME_VEHICLE_AT_PICKUP_TIME (2): + With the ``IN_SAME_VEHICLE_AT_PICKUP_TIME`` mode, all + "dependent" shipments need to have at least one "required" + shipment on their vehicle at the time of their pickup. + + A "dependent" shipment pickup must therefore have either: + + - A delivery-only "required" shipment delivered on the + route after, or + - A "required" shipment picked up on the route before it, + and if the "required" shipment has a delivery, this + delivery must be performed after the "dependent" + shipment's pickup. + IN_SAME_VEHICLE_AT_DELIVERY_TIME (3): + Same as before, except the "dependent" shipments need to + have a "required" shipment on their vehicle at the time of + their *delivery*. + """ + REQUIREMENT_MODE_UNSPECIFIED = 0 + PERFORMED_BY_SAME_VEHICLE = 1 + IN_SAME_VEHICLE_AT_PICKUP_TIME = 2 + IN_SAME_VEHICLE_AT_DELIVERY_TIME = 3 + + required_shipment_type_alternatives: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + dependent_shipment_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + requirement_mode: RequirementMode = proto.Field( + proto.ENUM, + number=3, + enum=RequirementMode, + ) + + +class Vehicle(proto.Message): + r"""Models a vehicle in a shipment problem. Solving a shipment problem + will build a route starting from ``start_location`` and ending at + ``end_location`` for this vehicle. A route is a sequence of visits + (see ``ShipmentRoute``). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + travel_mode (google.cloud.optimization_v1.types.Vehicle.TravelMode): + The travel mode which affects the roads usable by the + vehicle and its speed. See also + ``travel_duration_multiple``. + start_location (google.type.latlng_pb2.LatLng): + Geographic location where the vehicle starts before picking + up any shipments. If not specified, the vehicle starts at + its first pickup. If the shipment model has duration and + distance matrices, ``start_location`` must not be specified. + start_waypoint (google.cloud.optimization_v1.types.Waypoint): + Waypoint representing a geographic location where the + vehicle starts before picking up any shipments. If neither + ``start_waypoint`` nor ``start_location`` is specified, the + vehicle starts at its first pickup. If the shipment model + has duration and distance matrices, ``start_waypoint`` must + not be specified. + end_location (google.type.latlng_pb2.LatLng): + Geographic location where the vehicle ends after it has + completed its last ``VisitRequest``. If not specified the + vehicle's ``ShipmentRoute`` ends immediately when it + completes its last ``VisitRequest``. If the shipment model + has duration and distance matrices, ``end_location`` must + not be specified. + end_waypoint (google.cloud.optimization_v1.types.Waypoint): + Waypoint representing a geographic location where the + vehicle ends after it has completed its last + ``VisitRequest``. If neither ``end_waypoint`` nor + ``end_location`` is specified, the vehicle's + ``ShipmentRoute`` ends immediately when it completes its + last ``VisitRequest``. If the shipment model has duration + and distance matrices, ``end_waypoint`` must not be + specified. + start_tags (MutableSequence[str]): + Specifies tags attached to the start of the + vehicle's route. + Empty or duplicate strings are not allowed. + end_tags (MutableSequence[str]): + Specifies tags attached to the end of the + vehicle's route. + Empty or duplicate strings are not allowed. + start_time_windows (MutableSequence[google.cloud.optimization_v1.types.TimeWindow]): + Time windows during which the vehicle may depart its start + location. They must be within the global time limits (see + [ShipmentModel.global_*][google.cloud.optimization.v1.ShipmentModel.global_start_time] + fields). If unspecified, there is no limitation besides + those global time limits. + + Time windows belonging to the same repeated field must be + disjoint, i.e. no time window can overlap with or be + adjacent to another, and they must be in chronological + order. + + ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` + can only be set if there is a single time window. + end_time_windows (MutableSequence[google.cloud.optimization_v1.types.TimeWindow]): + Time windows during which the vehicle may arrive at its end + location. They must be within the global time limits (see + [ShipmentModel.global_*][google.cloud.optimization.v1.ShipmentModel.global_start_time] + fields). If unspecified, there is no limitation besides + those global time limits. + + Time windows belonging to the same repeated field must be + disjoint, i.e. no time window can overlap with or be + adjacent to another, and they must be in chronological + order. + + ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` + can only be set if there is a single time window. + travel_duration_multiple (float): + Specifies a multiplicative factor that can be used to + increase or decrease travel times of this vehicle. For + example, setting this to 2.0 means that this vehicle is + slower and has travel times that are twice what they are for + standard vehicles. This multiple does not affect visit + durations. It does affect cost if ``cost_per_hour`` or + ``cost_per_traveled_hour`` are specified. This must be in + the range [0.001, 1000.0]. If unset, the vehicle is + standard, and this multiple is considered 1.0. + + WARNING: Travel times will be rounded to the nearest second + after this multiple is applied but before performing any + numerical operations, thus, a small multiple may result in a + loss of precision. + + See also ``extra_visit_duration_for_visit_type`` below. + + This field is a member of `oneof`_ ``_travel_duration_multiple``. + unloading_policy (google.cloud.optimization_v1.types.Vehicle.UnloadingPolicy): + Unloading policy enforced on the vehicle. + load_limits (MutableMapping[str, google.cloud.optimization_v1.types.Vehicle.LoadLimit]): + Capacities of the vehicle (weight, volume, # of pallets for + example). The keys in the map are the identifiers of the + type of load, consistent with the keys of the + [Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands] + field. If a given key is absent from this map, the + corresponding capacity is considered to be limitless. + cost_per_hour (float): + Vehicle costs: all costs add up and must be in the same unit + as + [Shipment.penalty_cost][google.cloud.optimization.v1.Shipment.penalty_cost]. + + Cost per hour of the vehicle route. This cost is applied to + the total time taken by the route, and includes travel time, + waiting time, and visit time. Using ``cost_per_hour`` + instead of just ``cost_per_traveled_hour`` may result in + additional latency. + cost_per_traveled_hour (float): + Cost per traveled hour of the vehicle route. This cost is + applied only to travel time taken by the route (i.e., that + reported in + [ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions]), + and excludes waiting time and visit time. + cost_per_kilometer (float): + Cost per kilometer of the vehicle route. This cost is + applied to the distance reported in the + [ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions] + and does not apply to any distance implicitly traveled from + the ``arrival_location`` to the ``departure_location`` of a + single ``VisitRequest``. + fixed_cost (float): + Fixed cost applied if this vehicle is used to + handle a shipment. + used_if_route_is_empty (bool): + This field only applies to vehicles when their route does + not serve any shipments. It indicates if the vehicle should + be considered as used or not in this case. + + If true, the vehicle goes from its start to its end location + even if it doesn't serve any shipments, and time and + distance costs resulting from its start --> end travel are + taken into account. + + Otherwise, it doesn't travel from its start to its end + location, and no ``break_rule`` or delay (from + ``TransitionAttributes``) are scheduled for this vehicle. In + this case, the vehicle's ``ShipmentRoute`` doesn't contain + any information except for the vehicle index and label. + route_duration_limit (google.cloud.optimization_v1.types.Vehicle.DurationLimit): + Limit applied to the total duration of the vehicle's route. + In a given ``OptimizeToursResponse``, the route duration of + a vehicle is the difference between its ``vehicle_end_time`` + and ``vehicle_start_time``. + travel_duration_limit (google.cloud.optimization_v1.types.Vehicle.DurationLimit): + Limit applied to the travel duration of the vehicle's route. + In a given ``OptimizeToursResponse``, the route travel + duration is the sum of all its + [transitions.travel_duration][google.cloud.optimization.v1.ShipmentRoute.Transition.travel_duration]. + route_distance_limit (google.cloud.optimization_v1.types.DistanceLimit): + Limit applied to the total distance of the vehicle's route. + In a given ``OptimizeToursResponse``, the route distance is + the sum of all its + [transitions.travel_distance_meters][google.cloud.optimization.v1.ShipmentRoute.Transition.travel_distance_meters]. + extra_visit_duration_for_visit_type (MutableMapping[str, google.protobuf.duration_pb2.Duration]): + Specifies a map from visit_types strings to durations. The + duration is time in addition to + [VisitRequest.duration][google.cloud.optimization.v1.Shipment.VisitRequest.duration] + to be taken at visits with the specified ``visit_types``. + This extra visit duration adds cost if ``cost_per_hour`` is + specified. Keys (i.e. ``visit_types``) cannot be empty + strings. + + If a visit request has multiple types, a duration will be + added for each type in the map. + break_rule (google.cloud.optimization_v1.types.BreakRule): + Describes the break schedule to be enforced + on this vehicle. If empty, no breaks will be + scheduled for this vehicle. + label (str): + Specifies a label for this vehicle. This label is reported + in the response as the ``vehicle_label`` of the + corresponding + [ShipmentRoute][google.cloud.optimization.v1.ShipmentRoute]. + ignore (bool): + If true, ``used_if_route_is_empty`` must be false, and this + vehicle will remain unused. + + If a shipment is performed by an ignored vehicle in + ``injected_first_solution_routes``, it is skipped in the + first solution but is free to be performed in the response. + + If a shipment is performed by an ignored vehicle in + ``injected_solution_constraint`` and any related + pickup/delivery is constrained to remain on the vehicle + (i.e., not relaxed to level ``RELAX_ALL_AFTER_THRESHOLD``), + it is skipped in the response. If a shipment has a non-empty + ``allowed_vehicle_indices`` field and all of the allowed + vehicles are ignored, it is skipped in the response. + break_rule_indices (MutableSequence[int]): + Deprecated: No longer used. Indices in the ``break_rule`` + field in the source + [ShipmentModel][google.cloud.optimization.v1.ShipmentModel]. + They correspond to break rules enforced on the vehicle. + + As of 2018/03, at most one rule index per vehicle can be + specified. + capacities (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): + Deprecated: Use + [Vehicle.load_limits][google.cloud.optimization.v1.Vehicle.load_limits] + instead. + start_load_intervals (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantityInterval]): + Deprecated: Use + [Vehicle.LoadLimit.start_load_interval][google.cloud.optimization.v1.Vehicle.LoadLimit.start_load_interval] + instead. + end_load_intervals (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantityInterval]): + Deprecated: Use + [Vehicle.LoadLimit.end_load_interval][google.cloud.optimization.v1.Vehicle.LoadLimit.end_load_interval] + instead. + """ + class TravelMode(proto.Enum): + r"""Travel modes which can be used by vehicles. + + These should be a subset of the Google Maps Platform Routes + Preferred API travel modes, see: + https://developers.google.com/maps/documentation/routes_preferred/reference/rest/Shared.Types/RouteTravelMode. + + Values: + TRAVEL_MODE_UNSPECIFIED (0): + Unspecified travel mode, equivalent to ``DRIVING``. + DRIVING (1): + Travel mode corresponding to driving + directions (car, ...). + """ + TRAVEL_MODE_UNSPECIFIED = 0 + DRIVING = 1 + + class UnloadingPolicy(proto.Enum): + r"""Policy on how a vehicle can be unloaded. Applies only to shipments + having both a pickup and a delivery. + + Other shipments are free to occur anywhere on the route independent + of ``unloading_policy``. + + Values: + UNLOADING_POLICY_UNSPECIFIED (0): + Unspecified unloading policy; deliveries must + just occur after their corresponding pickups. + LAST_IN_FIRST_OUT (1): + Deliveries must occur in reverse order of + pickups + FIRST_IN_FIRST_OUT (2): + Deliveries must occur in the same order as + pickups + """ + UNLOADING_POLICY_UNSPECIFIED = 0 + LAST_IN_FIRST_OUT = 1 + FIRST_IN_FIRST_OUT = 2 + + class LoadLimit(proto.Message): + r"""Defines a load limit applying to a vehicle, e.g. "this truck may + only carry up to 3500 kg". See + [load_limits][google.cloud.optimization.v1.Vehicle.load_limits]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + max_load (int): + The maximum acceptable amount of load. + + This field is a member of `oneof`_ ``_max_load``. + soft_max_load (int): + A soft limit of the load. See + [cost_per_unit_above_soft_max][google.cloud.optimization.v1.Vehicle.LoadLimit.cost_per_unit_above_soft_max]. + cost_per_unit_above_soft_max (float): + If the load ever exceeds + [soft_max_load][google.cloud.optimization.v1.Vehicle.LoadLimit.soft_max_load] + along this vehicle's route, the following cost penalty + applies (only once per vehicle): (load - + [soft_max_load][google.cloud.optimization.v1.Vehicle.LoadLimit.soft_max_load]) + + - [cost_per_unit_above_soft_max][google.cloud.optimization.v1.Vehicle.LoadLimit.cost_per_unit_above_soft_max]. + All costs add up and must be in the same unit as + [Shipment.penalty_cost][google.cloud.optimization.v1.Shipment.penalty_cost]. + start_load_interval (google.cloud.optimization_v1.types.Vehicle.LoadLimit.Interval): + The acceptable load interval of the vehicle + at the start of the route. + end_load_interval (google.cloud.optimization_v1.types.Vehicle.LoadLimit.Interval): + The acceptable load interval of the vehicle + at the end of the route. + """ + + class Interval(proto.Message): + r"""Interval of acceptable load amounts. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + min_ (int): + A minimum acceptable load. Must be ≥ 0. If they're both + specified, + [min][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval.min] + must be ≤ + [max][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval.max]. + max_ (int): + A maximum acceptable load. Must be ≥ 0. If unspecified, the + maximum load is unrestricted by this message. If they're + both specified, + [min][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval.min] + must be ≤ + [max][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval.max]. + + This field is a member of `oneof`_ ``_max``. + """ + + min_: int = proto.Field( + proto.INT64, + number=1, + ) + max_: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + max_load: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + soft_max_load: int = proto.Field( + proto.INT64, + number=2, + ) + cost_per_unit_above_soft_max: float = proto.Field( + proto.DOUBLE, + number=3, + ) + start_load_interval: 'Vehicle.LoadLimit.Interval' = proto.Field( + proto.MESSAGE, + number=4, + message='Vehicle.LoadLimit.Interval', + ) + end_load_interval: 'Vehicle.LoadLimit.Interval' = proto.Field( + proto.MESSAGE, + number=5, + message='Vehicle.LoadLimit.Interval', + ) + + class DurationLimit(proto.Message): + r"""A limit defining a maximum duration of the route of a + vehicle. It can be either hard or soft. + + When a soft limit field is defined, both the soft max threshold + and its associated cost must be defined together. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + max_duration (google.protobuf.duration_pb2.Duration): + A hard limit constraining the duration to be at most + max_duration. + soft_max_duration (google.protobuf.duration_pb2.Duration): + A soft limit not enforcing a maximum duration limit, but + when violated makes the route incur a cost. This cost adds + up to other costs defined in the model, with the same unit. + + If defined, ``soft_max_duration`` must be nonnegative. If + max_duration is also defined, ``soft_max_duration`` must be + less than max_duration. + cost_per_hour_after_soft_max (float): + Cost per hour incurred if the ``soft_max_duration`` + threshold is violated. The additional cost is 0 if the + duration is under the threshold, otherwise the cost depends + on the duration as follows: + + :: + + cost_per_hour_after_soft_max * (duration - soft_max_duration) + + The cost must be nonnegative. + + This field is a member of `oneof`_ ``_cost_per_hour_after_soft_max``. + quadratic_soft_max_duration (google.protobuf.duration_pb2.Duration): + A soft limit not enforcing a maximum duration limit, but + when violated makes the route incur a cost, quadratic in the + duration. This cost adds up to other costs defined in the + model, with the same unit. + + If defined, ``quadratic_soft_max_duration`` must be + nonnegative. If ``max_duration`` is also defined, + ``quadratic_soft_max_duration`` must be less than + ``max_duration``, and the difference must be no larger than + one day: + + :: + + `max_duration - quadratic_soft_max_duration <= 86400 seconds` + cost_per_square_hour_after_quadratic_soft_max (float): + Cost per square hour incurred if the + ``quadratic_soft_max_duration`` threshold is violated. + + The additional cost is 0 if the duration is under the + threshold, otherwise the cost depends on the duration as + follows: + + :: + + cost_per_square_hour_after_quadratic_soft_max * + (duration - quadratic_soft_max_duration)^2 + + The cost must be nonnegative. + + This field is a member of `oneof`_ ``_cost_per_square_hour_after_quadratic_soft_max``. + """ + + max_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + soft_max_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + cost_per_hour_after_soft_max: float = proto.Field( + proto.DOUBLE, + number=3, + optional=True, + ) + quadratic_soft_max_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + cost_per_square_hour_after_quadratic_soft_max: float = proto.Field( + proto.DOUBLE, + number=5, + optional=True, + ) + + travel_mode: TravelMode = proto.Field( + proto.ENUM, + number=1, + enum=TravelMode, + ) + start_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=3, + message=latlng_pb2.LatLng, + ) + start_waypoint: 'Waypoint' = proto.Field( + proto.MESSAGE, + number=4, + message='Waypoint', + ) + end_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=5, + message=latlng_pb2.LatLng, + ) + end_waypoint: 'Waypoint' = proto.Field( + proto.MESSAGE, + number=6, + message='Waypoint', + ) + start_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + end_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + start_time_windows: MutableSequence['TimeWindow'] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='TimeWindow', + ) + end_time_windows: MutableSequence['TimeWindow'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='TimeWindow', + ) + travel_duration_multiple: float = proto.Field( + proto.DOUBLE, + number=11, + optional=True, + ) + unloading_policy: UnloadingPolicy = proto.Field( + proto.ENUM, + number=12, + enum=UnloadingPolicy, + ) + load_limits: MutableMapping[str, LoadLimit] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=30, + message=LoadLimit, + ) + cost_per_hour: float = proto.Field( + proto.DOUBLE, + number=16, + ) + cost_per_traveled_hour: float = proto.Field( + proto.DOUBLE, + number=17, + ) + cost_per_kilometer: float = proto.Field( + proto.DOUBLE, + number=18, + ) + fixed_cost: float = proto.Field( + proto.DOUBLE, + number=19, + ) + used_if_route_is_empty: bool = proto.Field( + proto.BOOL, + number=20, + ) + route_duration_limit: DurationLimit = proto.Field( + proto.MESSAGE, + number=21, + message=DurationLimit, + ) + travel_duration_limit: DurationLimit = proto.Field( + proto.MESSAGE, + number=22, + message=DurationLimit, + ) + route_distance_limit: 'DistanceLimit' = proto.Field( + proto.MESSAGE, + number=23, + message='DistanceLimit', + ) + extra_visit_duration_for_visit_type: MutableMapping[str, duration_pb2.Duration] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=24, + message=duration_pb2.Duration, + ) + break_rule: 'BreakRule' = proto.Field( + proto.MESSAGE, + number=25, + message='BreakRule', + ) + label: str = proto.Field( + proto.STRING, + number=27, + ) + ignore: bool = proto.Field( + proto.BOOL, + number=28, + ) + break_rule_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=29, + ) + capacities: MutableSequence['CapacityQuantity'] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message='CapacityQuantity', + ) + start_load_intervals: MutableSequence['CapacityQuantityInterval'] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='CapacityQuantityInterval', + ) + end_load_intervals: MutableSequence['CapacityQuantityInterval'] = proto.RepeatedField( + proto.MESSAGE, + number=15, + message='CapacityQuantityInterval', + ) + + +class TimeWindow(proto.Message): + r"""Time windows constrain the time of an event, such as the arrival + time at a visit, or the start and end time of a vehicle. + + Hard time window bounds, ``start_time`` and ``end_time``, enforce + the earliest and latest time of the event, such that + ``start_time <= event_time <= end_time``. The soft time window lower + bound, ``soft_start_time``, expresses a preference for the event to + happen at or after ``soft_start_time`` by incurring a cost + proportional to how long before soft_start_time the event occurs. + The soft time window upper bound, ``soft_end_time``, expresses a + preference for the event to happen at or before ``soft_end_time`` by + incurring a cost proportional to how long after ``soft_end_time`` + the event occurs. ``start_time``, ``end_time``, ``soft_start_time`` + and ``soft_end_time`` should be within the global time limits (see + [ShipmentModel.global_start_time][google.cloud.optimization.v1.ShipmentModel.global_start_time] + and + [ShipmentModel.global_end_time][google.cloud.optimization.v1.ShipmentModel.global_end_time]) + and should respect: + + :: + + 0 <= `start_time` <= `soft_start_time` <= `end_time` and + 0 <= `start_time` <= `soft_end_time` <= `end_time`. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + The hard time window start time. If unspecified it will be + set to ``ShipmentModel.global_start_time``. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The hard time window end time. If unspecified it will be set + to ``ShipmentModel.global_end_time``. + soft_start_time (google.protobuf.timestamp_pb2.Timestamp): + The soft start time of the time window. + soft_end_time (google.protobuf.timestamp_pb2.Timestamp): + The soft end time of the time window. + cost_per_hour_before_soft_start_time (float): + A cost per hour added to other costs in the model if the + event occurs before soft_start_time, computed as: + + :: + + max(0, soft_start_time - t.seconds) + * cost_per_hour_before_soft_start_time / 3600, + t being the time of the event. + + This cost must be positive, and the field can only be set if + soft_start_time has been set. + + This field is a member of `oneof`_ ``_cost_per_hour_before_soft_start_time``. + cost_per_hour_after_soft_end_time (float): + A cost per hour added to other costs in the model if the + event occurs after ``soft_end_time``, computed as: + + :: + + max(0, t.seconds - soft_end_time.seconds) + * cost_per_hour_after_soft_end_time / 3600, + t being the time of the event. + + This cost must be positive, and the field can only be set if + ``soft_end_time`` has been set. + + This field is a member of `oneof`_ ``_cost_per_hour_after_soft_end_time``. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + soft_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + soft_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + cost_per_hour_before_soft_start_time: float = proto.Field( + proto.DOUBLE, + number=5, + optional=True, + ) + cost_per_hour_after_soft_end_time: float = proto.Field( + proto.DOUBLE, + number=6, + optional=True, + ) + + +class CapacityQuantity(proto.Message): + r"""Deprecated: Use + [Vehicle.LoadLimit.Interval][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval] + instead. + + Attributes: + type_ (str): + + value (int): + + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + value: int = proto.Field( + proto.INT64, + number=2, + ) + + +class CapacityQuantityInterval(proto.Message): + r"""Deprecated: Use + [Vehicle.LoadLimit.Interval][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval] + instead. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (str): + + min_value (int): + + This field is a member of `oneof`_ ``_min_value``. + max_value (int): + + This field is a member of `oneof`_ ``_max_value``. + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + min_value: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + max_value: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + + +class DistanceLimit(proto.Message): + r"""A limit defining a maximum distance which can be traveled. It can be + either hard or soft. + + If a soft limit is defined, both ``soft_max_meters`` and + ``cost_per_kilometer_above_soft_max`` must be defined and be + nonnegative. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + max_meters (int): + A hard limit constraining the distance to be at most + max_meters. The limit must be nonnegative. + + This field is a member of `oneof`_ ``_max_meters``. + soft_max_meters (int): + A soft limit not enforcing a maximum distance limit, but + when violated results in a cost which adds up to other costs + defined in the model, with the same unit. + + If defined soft_max_meters must be less than max_meters and + must be nonnegative. + + This field is a member of `oneof`_ ``_soft_max_meters``. + cost_per_kilometer_above_soft_max (float): + Cost per kilometer incurred if distance is above + ``soft_max_meters`` limit. The additional cost is 0 if the + distance is under the limit, otherwise the formula used to + compute the cost is the following: + + :: + + (distance_meters - soft_max_meters) / 1000.0 * + cost_per_kilometer_above_soft_max. + + The cost must be nonnegative. + + This field is a member of `oneof`_ ``_cost_per_kilometer_above_soft_max``. + """ + + max_meters: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + soft_max_meters: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + cost_per_kilometer_above_soft_max: float = proto.Field( + proto.DOUBLE, + number=3, + optional=True, + ) + + +class TransitionAttributes(proto.Message): + r"""Specifies attributes of transitions between two consecutive visits + on a route. Several ``TransitionAttributes`` may apply to the same + transition: in that case, all extra costs add up and the strictest + constraint or limit applies (following natural "AND" semantics). + + Attributes: + src_tag (str): + Tags defining the set of (src->dst) transitions these + attributes apply to. + + A source visit or vehicle start matches iff its + [VisitRequest.tags][google.cloud.optimization.v1.Shipment.VisitRequest.tags] + or + [Vehicle.start_tags][google.cloud.optimization.v1.Vehicle.start_tags] + either contains ``src_tag`` or does not contain + ``excluded_src_tag`` (depending on which of these two fields + is non-empty). + excluded_src_tag (str): + See ``src_tag``. Exactly one of ``src_tag`` and + ``excluded_src_tag`` must be non-empty. + dst_tag (str): + A destination visit or vehicle end matches iff its + [VisitRequest.tags][google.cloud.optimization.v1.Shipment.VisitRequest.tags] + or + [Vehicle.end_tags][google.cloud.optimization.v1.Vehicle.end_tags] + either contains ``dst_tag`` or does not contain + ``excluded_dst_tag`` (depending on which of these two fields + is non-empty). + excluded_dst_tag (str): + See ``dst_tag``. Exactly one of ``dst_tag`` and + ``excluded_dst_tag`` must be non-empty. + cost (float): + Specifies a cost for performing this + transition. This is in the same unit as all + other costs in the model and must not be + negative. It is applied on top of all other + existing costs. + cost_per_kilometer (float): + Specifies a cost per kilometer applied to the distance + traveled while performing this transition. It adds up to any + [Vehicle.cost_per_kilometer][google.cloud.optimization.v1.Vehicle.cost_per_kilometer] + specified on vehicles. + distance_limit (google.cloud.optimization_v1.types.DistanceLimit): + Specifies a limit on the distance traveled + while performing this transition. + + As of 2021/06, only soft limits are supported. + delay (google.protobuf.duration_pb2.Duration): + Specifies a delay incurred when performing this transition. + + This delay always occurs *after* finishing the source visit + and *before* starting the destination visit. + """ + + src_tag: str = proto.Field( + proto.STRING, + number=1, + ) + excluded_src_tag: str = proto.Field( + proto.STRING, + number=2, + ) + dst_tag: str = proto.Field( + proto.STRING, + number=3, + ) + excluded_dst_tag: str = proto.Field( + proto.STRING, + number=4, + ) + cost: float = proto.Field( + proto.DOUBLE, + number=5, + ) + cost_per_kilometer: float = proto.Field( + proto.DOUBLE, + number=6, + ) + distance_limit: 'DistanceLimit' = proto.Field( + proto.MESSAGE, + number=7, + message='DistanceLimit', + ) + delay: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + + +class Waypoint(proto.Message): + r"""Encapsulates a waypoint. Waypoints mark arrival and departure + locations of VisitRequests, and start and end locations of + Vehicles. + + 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: + location (google.cloud.optimization_v1.types.Location): + A point specified using geographic + coordinates, including an optional heading. + + This field is a member of `oneof`_ ``location_type``. + place_id (str): + The POI Place ID associated with the + waypoint. + + This field is a member of `oneof`_ ``location_type``. + side_of_road (bool): + Indicates that the location of this waypoint is meant to + have a preference for the vehicle to stop at a particular + side of road. When you set this value, the route will pass + through the location so that the vehicle can stop at the + side of road that the location is biased towards from the + center of the road. This option works only for the 'DRIVING' + travel mode, and when the 'location_type' is set to + 'location'. + """ + + location: 'Location' = proto.Field( + proto.MESSAGE, + number=1, + oneof='location_type', + message='Location', + ) + place_id: str = proto.Field( + proto.STRING, + number=2, + oneof='location_type', + ) + side_of_road: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class Location(proto.Message): + r"""Encapsulates a location (a geographic point, and an optional + heading). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + lat_lng (google.type.latlng_pb2.LatLng): + The waypoint's geographic coordinates. + heading (int): + The compass heading associated with the + direction of the flow of traffic. This value is + used to specify the side of the road to use for + pickup and drop-off. Heading values can be from + 0 to 360, where 0 specifies a heading of due + North, 90 specifies a heading of due East, etc. + + This field is a member of `oneof`_ ``_heading``. + """ + + lat_lng: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + heading: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + +class BreakRule(proto.Message): + r"""Rules to generate time breaks for a vehicle (e.g. lunch breaks). A + break is a contiguous period of time during which the vehicle + remains idle at its current position and cannot perform any visit. A + break may occur: + + - during the travel between two visits (which includes the time + right before or right after a visit, but not in the middle of a + visit), in which case it extends the corresponding transit time + between the visits, + - or before the vehicle start (the vehicle may not start in the + middle of a break), in which case it does not affect the vehicle + start time. + - or after the vehicle end (ditto, with the vehicle end time). + + Attributes: + break_requests (MutableSequence[google.cloud.optimization_v1.types.BreakRule.BreakRequest]): + Sequence of breaks. See the ``BreakRequest`` message. + frequency_constraints (MutableSequence[google.cloud.optimization_v1.types.BreakRule.FrequencyConstraint]): + Several ``FrequencyConstraint`` may apply. They must all be + satisfied by the ``BreakRequest``\ s of this ``BreakRule``. + See ``FrequencyConstraint``. + """ + + class BreakRequest(proto.Message): + r"""The sequence of breaks (i.e. their number and order) that apply to + each vehicle must be known beforehand. The repeated + ``BreakRequest``\ s define that sequence, in the order in which they + must occur. Their time windows (``earliest_start_time`` / + ``latest_start_time``) may overlap, but they must be compatible with + the order (this is checked). + + Attributes: + earliest_start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Lower bound (inclusive) on the + start of the break. + latest_start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Upper bound (inclusive) on the + start of the break. + min_duration (google.protobuf.duration_pb2.Duration): + Required. Minimum duration of the break. Must + be positive. + """ + + earliest_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + latest_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + min_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + class FrequencyConstraint(proto.Message): + r"""One may further constrain the frequency and duration of the breaks + specified above, by enforcing a minimum break frequency, such as + "There must be a break of at least 1 hour every 12 hours". Assuming + that this can be interpreted as "Within any sliding time window of + 12h, there must be at least one break of at least one hour", that + example would translate to the following ``FrequencyConstraint``: + + :: + + { + min_break_duration { seconds: 3600 } # 1 hour. + max_inter_break_duration { seconds: 39600 } # 11 hours (12 - 1 = 11). + } + + The timing and duration of the breaks in the solution will respect + all such constraints, in addition to the time windows and minimum + durations already specified in the ``BreakRequest``. + + A ``FrequencyConstraint`` may in practice apply to non-consecutive + breaks. For example, the following schedule honors the "1h every + 12h" example: + + :: + + 04:00 vehicle start + .. performing travel and visits .. + 09:00 1 hour break + 10:00 end of the break + .. performing travel and visits .. + 12:00 20-min lunch break + 12:20 end of the break + .. performing travel and visits .. + 21:00 1 hour break + 22:00 end of the break + .. performing travel and visits .. + 23:59 vehicle end + + Attributes: + min_break_duration (google.protobuf.duration_pb2.Duration): + Required. Minimum break duration for this constraint. + Nonnegative. See description of ``FrequencyConstraint``. + max_inter_break_duration (google.protobuf.duration_pb2.Duration): + Required. Maximum allowed span of any interval of time in + the route that does not include at least partially a break + of ``duration >= min_break_duration``. Must be positive. + """ + + min_break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + max_inter_break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + break_requests: MutableSequence[BreakRequest] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=BreakRequest, + ) + frequency_constraints: MutableSequence[FrequencyConstraint] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=FrequencyConstraint, + ) + + +class ShipmentRoute(proto.Message): + r"""A vehicle's route can be decomposed, along the time axis, like this + (we assume there are n visits): + + :: + + | | | | | T[2], | | | + | Transition | Visit #0 | | | V[2], | | | + | #0 | aka | T[1] | V[1] | ... | V[n-1] | T[n] | + | aka T[0] | V[0] | | | V[n-2],| | | + | | | | | T[n-1] | | | + ^ ^ ^ ^ ^ ^ ^ ^ + vehicle V[0].start V[0].end V[1]. V[1]. V[n]. V[n]. vehicle + start (arrival) (departure) start end start end end + + Note that we make a difference between: + + - "punctual events", such as the vehicle start and end and each + visit's start and end (aka arrival and departure). They happen at + a given second. + - "time intervals", such as the visits themselves, and the + transition between visits. Though time intervals can sometimes + have zero duration, i.e. start and end at the same second, they + often have a positive duration. + + Invariants: + + - If there are n visits, there are n+1 transitions. + - A visit is always surrounded by a transition before it (same + index) and a transition after it (index + 1). + - The vehicle start is always followed by transition #0. + - The vehicle end is always preceded by transition #n. + + Zooming in, here is what happens during a ``Transition`` and a + ``Visit``: + + :: + + ---+-------------------------------------+-----------------------------+--> + | TRANSITION[i] | VISIT[i] | + | | | + | * TRAVEL: the vehicle moves from | PERFORM the visit: | + | VISIT[i-1].departure_location to | | + | VISIT[i].arrival_location, which | * Spend some time: | + | takes a given travel duration | the "visit duration". | + | and distance | | + | | * Load or unload | + | * BREAKS: the driver may have | some quantities from the | + | breaks (e.g. lunch break). | vehicle: the "demand". | + | | | + | * WAIT: the driver/vehicle does | | + | nothing. This can happen for | | + | many reasons, for example when | | + | the vehicle reaches the next | | + | event's destination before the | | + | start of its time window | | + | | | + | * DELAY: *right before* the next | | + | arrival. E.g. the vehicle and/or | | + | driver spends time unloading. | | + | | | + ---+-------------------------------------+-----------------------------+--> + ^ ^ ^ + V[i-1].end V[i].start V[i].end + + Lastly, here is how the TRAVEL, BREAKS, DELAY and WAIT can be + arranged during a transition. + + - They don't overlap. + - The DELAY is unique and *must* be a contiguous period of time + right before the next visit (or vehicle end). Thus, it suffice to + know the delay duration to know its start and end time. + - The BREAKS are contiguous, non-overlapping periods of time. The + response specifies the start time and duration of each break. + - TRAVEL and WAIT are "preemptable": they can be interrupted + several times during this transition. Clients can assume that + travel happens "as soon as possible" and that "wait" fills the + remaining time. + + A (complex) example: + + :: + + TRANSITION[i] + --++-----+-----------------------------------------------------------++--> + || | | | | | | || + || T | B | T | | B | | D || + || r | r | r | W | r | W | e || + || a | e | a | a | e | a | l || + || v | a | v | i | a | i | a || + || e | k | e | t | k | t | y || + || l | | l | | | | || + || | | | | | | || + --++-----------------------------------------------------------------++--> + + Attributes: + vehicle_index (int): + Vehicle performing the route, identified by its index in the + source ``ShipmentModel``. + vehicle_label (str): + Label of the vehicle performing this route, equal to + ``ShipmentModel.vehicles(vehicle_index).label``, if + specified. + vehicle_start_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the vehicle starts its route. + vehicle_end_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the vehicle finishes its route. + visits (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute.Visit]): + Ordered sequence of visits representing a route. visits[i] + is the i-th visit in the route. If this field is empty, the + vehicle is considered as unused. + transitions (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute.Transition]): + Ordered list of transitions for the route. + has_traffic_infeasibilities (bool): + When + [OptimizeToursRequest.consider_road_traffic][google.cloud.optimization.v1.OptimizeToursRequest.consider_road_traffic], + is set to true, this field indicates that inconsistencies in + route timings are predicted using traffic-based travel + duration estimates. There may be insufficient time to + complete traffic-adjusted travel, delays, and breaks between + visits, before the first visit, or after the last visit, + while still satisfying the visit and vehicle time windows. + For example, + + :: + + start_time(previous_visit) + duration(previous_visit) + + travel_duration(previous_visit, next_visit) > start_time(next_visit) + + Arrival at next_visit will likely happen later than its + current time window due the increased estimate of travel + time ``travel_duration(previous_visit, next_visit)`` due to + traffic. Also, a break may be forced to overlap with a visit + due to an increase in travel time estimates and visit or + break time window restrictions. + route_polyline (google.cloud.optimization_v1.types.ShipmentRoute.EncodedPolyline): + The encoded polyline representation of the route. This field + is only populated if + [OptimizeToursRequest.populate_polylines][google.cloud.optimization.v1.OptimizeToursRequest.populate_polylines] + is set to true. + breaks (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute.Break]): + Breaks scheduled for the vehicle performing this route. The + ``breaks`` sequence represents time intervals, each starting + at the corresponding ``start_time`` and lasting ``duration`` + seconds. + metrics (google.cloud.optimization_v1.types.AggregatedMetrics): + Duration, distance and load metrics for this route. The + fields of + [AggregatedMetrics][google.cloud.optimization.v1.AggregatedMetrics] + are summed over all + [ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions] + or + [ShipmentRoute.visits][google.cloud.optimization.v1.ShipmentRoute.visits], + depending on the context. + route_costs (MutableMapping[str, float]): + Cost of the route, broken down by cost-related request + fields. The keys are proto paths, relative to the input + OptimizeToursRequest, e.g. "model.shipments.pickups.cost", + and the values are the total cost generated by the + corresponding cost field, aggregated over the whole route. + In other words, costs["model.shipments.pickups.cost"] is the + sum of all pickup costs over the route. All costs defined in + the model are reported in detail here with the exception of + costs related to TransitionAttributes that are only reported + in an aggregated way as of 2022/01. + route_total_cost (float): + Total cost of the route. The sum of all costs + in the cost map. + end_loads (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): + Deprecated: Use + [Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads] + instead. Vehicle loads upon arrival at its end location, for + each type specified in + [Vehicle.capacities][google.cloud.optimization.v1.Vehicle.capacities], + ``start_load_intervals``, ``end_load_intervals`` or demands. + Exception: we omit loads for quantity types unconstrained by + intervals and that don't have any non-zero demand on the + route. + travel_steps (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute.TravelStep]): + Deprecated: Use + [ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions] + instead. Ordered list of travel steps for the route. + vehicle_detour (google.protobuf.duration_pb2.Duration): + Deprecated: No longer used. This field will only be + populated at the + [ShipmentRoute.Visit][google.cloud.optimization.v1.ShipmentRoute.Visit] + level. + + This field is the extra detour time due to the shipments + visited on the route. + + It is equal to ``vehicle_end_time`` - ``vehicle_start_time`` + - travel duration from the vehicle's start_location to its + ``end_location``. + delay_before_vehicle_end (google.cloud.optimization_v1.types.ShipmentRoute.Delay): + Deprecated: Delay occurring before the vehicle end. See + [TransitionAttributes.delay][google.cloud.optimization.v1.TransitionAttributes.delay]. + """ + + class Delay(proto.Message): + r"""Deprecated: Use + [ShipmentRoute.Transition.delay_duration][google.cloud.optimization.v1.ShipmentRoute.Transition.delay_duration] + instead. Time interval spent on the route resulting from a + [TransitionAttributes.delay][google.cloud.optimization.v1.TransitionAttributes.delay]. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start of the delay. + duration (google.protobuf.duration_pb2.Duration): + Duration of the delay. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + class Visit(proto.Message): + r"""A visit performed during a route. This visit corresponds to a pickup + or a delivery of a ``Shipment``. + + Attributes: + shipment_index (int): + Index of the ``shipments`` field in the source + [ShipmentModel][google.cloud.optimization.v1.ShipmentModel]. + is_pickup (bool): + If true the visit corresponds to a pickup of a ``Shipment``. + Otherwise, it corresponds to a delivery. + visit_request_index (int): + Index of ``VisitRequest`` in either the pickup or delivery + field of the ``Shipment`` (see ``is_pickup``). + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the visit starts. Note that the vehicle may + arrive earlier than this at the visit location. Times are + consistent with the ``ShipmentModel``. + load_demands (MutableMapping[str, google.cloud.optimization_v1.types.Shipment.Load]): + Total visit load demand as the sum of the shipment and the + visit request ``load_demands``. The values are negative if + the visit is a delivery. Demands are reported for the same + types as the + [Transition.loads][google.cloud.optimization.v1.ShipmentRoute.Transition] + (see this field). + detour (google.protobuf.duration_pb2.Duration): + Extra detour time due to the shipments visited on the route + before the visit and to the potential waiting time induced + by time windows. If the visit is a delivery, the detour is + computed from the corresponding pickup visit and is equal + to: + + :: + + start_time(delivery) - start_time(pickup) + - (duration(pickup) + travel duration from the pickup location + to the delivery location). + + Otherwise, it is computed from the vehicle + ``start_location`` and is equal to: + + :: + + start_time - vehicle_start_time - travel duration from + the vehicle's `start_location` to the visit. + shipment_label (str): + Copy of the corresponding ``Shipment.label``, if specified + in the ``Shipment``. + visit_label (str): + Copy of the corresponding + [VisitRequest.label][google.cloud.optimization.v1.Shipment.VisitRequest.label], + if specified in the ``VisitRequest``. + arrival_loads (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): + Deprecated: Use + [Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads] + instead. Vehicle loads upon arrival at the visit location, + for each type specified in + [Vehicle.capacities][google.cloud.optimization.v1.Vehicle.capacities], + ``start_load_intervals``, ``end_load_intervals`` or + ``demands``. + + Exception: we omit loads for quantity types unconstrained by + intervals and that don't have any non-zero demand on the + route. + delay_before_start (google.cloud.optimization_v1.types.ShipmentRoute.Delay): + Deprecated: Use + [ShipmentRoute.Transition.delay_duration][google.cloud.optimization.v1.ShipmentRoute.Transition.delay_duration] + instead. Delay occurring before the visit starts. + demands (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): + Deprecated: Use + [Visit.load_demands][google.cloud.optimization.v1.ShipmentRoute.Visit.load_demands] + instead. + """ + + shipment_index: int = proto.Field( + proto.INT32, + number=1, + ) + is_pickup: bool = proto.Field( + proto.BOOL, + number=2, + ) + visit_request_index: int = proto.Field( + proto.INT32, + number=3, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + load_demands: MutableMapping[str, 'Shipment.Load'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=11, + message='Shipment.Load', + ) + detour: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + shipment_label: str = proto.Field( + proto.STRING, + number=7, + ) + visit_label: str = proto.Field( + proto.STRING, + number=8, + ) + arrival_loads: MutableSequence['CapacityQuantity'] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='CapacityQuantity', + ) + delay_before_start: 'ShipmentRoute.Delay' = proto.Field( + proto.MESSAGE, + number=10, + message='ShipmentRoute.Delay', + ) + demands: MutableSequence['CapacityQuantity'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='CapacityQuantity', + ) + + class Transition(proto.Message): + r"""Transition between two events on the route. See the description of + [ShipmentRoute][google.cloud.optimization.v1.ShipmentRoute]. + + If the vehicle does not have a ``start_location`` and/or + ``end_location``, the corresponding travel metrics are 0. + + Attributes: + travel_duration (google.protobuf.duration_pb2.Duration): + Travel duration during this transition. + travel_distance_meters (float): + Distance traveled during the transition. + traffic_info_unavailable (bool): + When traffic is requested via + [OptimizeToursRequest.consider_road_traffic] + [google.cloud.optimization.v1.OptimizeToursRequest.consider_road_traffic], + and the traffic info couldn't be retrieved for a + ``Transition``, this boolean is set to true. This may be + temporary (rare hiccup in the realtime traffic servers) or + permanent (no data for this location). + delay_duration (google.protobuf.duration_pb2.Duration): + Sum of the delay durations applied to this transition. If + any, the delay starts exactly ``delay_duration`` seconds + before the next event (visit or vehicle end). See + [TransitionAttributes.delay][google.cloud.optimization.v1.TransitionAttributes.delay]. + break_duration (google.protobuf.duration_pb2.Duration): + Sum of the duration of the breaks occurring during this + transition, if any. Details about each break's start time + and duration are stored in + [ShipmentRoute.breaks][google.cloud.optimization.v1.ShipmentRoute.breaks]. + wait_duration (google.protobuf.duration_pb2.Duration): + Time spent waiting during this transition. + Wait duration corresponds to idle time and does + not include break time. Also note that this wait + time may be split into several non-contiguous + intervals. + total_duration (google.protobuf.duration_pb2.Duration): + Total duration of the transition, provided for convenience. + It is equal to: + + - next visit ``start_time`` (or ``vehicle_end_time`` if + this is the last transition) - this transition's + ``start_time``; + - if ``ShipmentRoute.has_traffic_infeasibilities`` is + false, the following additionally holds: \`total_duration + = travel_duration + delay_duration + + - break_duration + wait_duration`. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of this transition. + route_polyline (google.cloud.optimization_v1.types.ShipmentRoute.EncodedPolyline): + The encoded polyline representation of the route followed + during the transition. This field is only populated if + [populate_transition_polylines] + [google.cloud.optimization.v1.OptimizeToursRequest.populate_transition_polylines] + is set to true. + vehicle_loads (MutableMapping[str, google.cloud.optimization_v1.types.ShipmentRoute.VehicleLoad]): + Vehicle loads during this transition, for each type that + either appears in this vehicle's + [Vehicle.load_limits][google.cloud.optimization.v1.Vehicle.load_limits], + or that have non-zero + [Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands] + on some shipment performed on this route. + + The loads during the first transition are the starting loads + of the vehicle route. Then, after each visit, the visit's + ``load_demands`` are either added or subtracted to get the + next transition's loads, depending on whether the visit was + a pickup or a delivery. + loads (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): + Deprecated: Use + [Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads] + instead. + """ + + travel_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + travel_distance_meters: float = proto.Field( + proto.DOUBLE, + number=2, + ) + traffic_info_unavailable: bool = proto.Field( + proto.BOOL, + number=3, + ) + delay_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + wait_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + total_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + route_polyline: 'ShipmentRoute.EncodedPolyline' = proto.Field( + proto.MESSAGE, + number=9, + message='ShipmentRoute.EncodedPolyline', + ) + vehicle_loads: MutableMapping[str, 'ShipmentRoute.VehicleLoad'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=11, + message='ShipmentRoute.VehicleLoad', + ) + loads: MutableSequence['CapacityQuantity'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='CapacityQuantity', + ) + + class VehicleLoad(proto.Message): + r"""Reports the actual load of the vehicle at some point along the + route, for a given type (see + [Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads]). + + Attributes: + amount (int): + The amount of load on the vehicle, for the given type. The + unit of load is usually indicated by the type. See + [Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads]. + """ + + amount: int = proto.Field( + proto.INT64, + number=1, + ) + + class EncodedPolyline(proto.Message): + r"""The encoded representation of a polyline. More information on + polyline encoding can be found here: + https://developers.google.com/maps/documentation/utilities/polylinealgorithm + https://developers.google.com/maps/documentation/javascript/reference/geometry#encoding. + + Attributes: + points (str): + String representing encoded points of the + polyline. + """ + + points: str = proto.Field( + proto.STRING, + number=1, + ) + + class Break(proto.Message): + r"""Data representing the execution of a break. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of a break. + duration (google.protobuf.duration_pb2.Duration): + Duration of a break. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + class TravelStep(proto.Message): + r"""Deprecated: Use + [ShipmentRoute.Transition][google.cloud.optimization.v1.ShipmentRoute.Transition] + instead. Travel between each visit along the route: from the + vehicle's ``start_location`` to the first visit's + ``arrival_location``, then from the first visit's + ``departure_location`` to the second visit's ``arrival_location``, + and so on until the vehicle's ``end_location``. This accounts only + for the actual travel between visits, not counting the waiting time, + the time spent performing a visit, nor the distance covered during a + visit. + + Invariant: ``travel_steps_size() == visits_size() + 1``. + + If the vehicle does not have a start\_ and/or end_location, the + corresponding travel metrics are 0 and/or empty. + + Attributes: + duration (google.protobuf.duration_pb2.Duration): + Duration of the travel step. + distance_meters (float): + Distance traveled during the step. + traffic_info_unavailable (bool): + When traffic is requested via + [OptimizeToursRequest.consider_road_traffic][google.cloud.optimization.v1.OptimizeToursRequest.consider_road_traffic], + and the traffic info couldn't be retrieved for a TravelStep, + this boolean is set to true. This may be temporary (rare + hiccup in the realtime traffic servers) or permanent (no + data for this location). + route_polyline (google.cloud.optimization_v1.types.ShipmentRoute.EncodedPolyline): + The encoded polyline representation of the route followed + during the step. + + This field is only populated if + [OptimizeToursRequest.populate_travel_step_polylines][google.cloud.optimization.v1.OptimizeToursRequest.populate_travel_step_polylines] + is set to true. + """ + + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + distance_meters: float = proto.Field( + proto.DOUBLE, + number=2, + ) + traffic_info_unavailable: bool = proto.Field( + proto.BOOL, + number=3, + ) + route_polyline: 'ShipmentRoute.EncodedPolyline' = proto.Field( + proto.MESSAGE, + number=4, + message='ShipmentRoute.EncodedPolyline', + ) + + vehicle_index: int = proto.Field( + proto.INT32, + number=1, + ) + vehicle_label: str = proto.Field( + proto.STRING, + number=2, + ) + vehicle_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + vehicle_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + visits: MutableSequence[Visit] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Visit, + ) + transitions: MutableSequence[Transition] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=Transition, + ) + has_traffic_infeasibilities: bool = proto.Field( + proto.BOOL, + number=9, + ) + route_polyline: EncodedPolyline = proto.Field( + proto.MESSAGE, + number=10, + message=EncodedPolyline, + ) + breaks: MutableSequence[Break] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=Break, + ) + metrics: 'AggregatedMetrics' = proto.Field( + proto.MESSAGE, + number=12, + message='AggregatedMetrics', + ) + route_costs: MutableMapping[str, float] = proto.MapField( + proto.STRING, + proto.DOUBLE, + number=17, + ) + route_total_cost: float = proto.Field( + proto.DOUBLE, + number=18, + ) + end_loads: MutableSequence['CapacityQuantity'] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message='CapacityQuantity', + ) + travel_steps: MutableSequence[TravelStep] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=TravelStep, + ) + vehicle_detour: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=15, + message=duration_pb2.Duration, + ) + delay_before_vehicle_end: Delay = proto.Field( + proto.MESSAGE, + number=16, + message=Delay, + ) + + +class SkippedShipment(proto.Message): + r"""Specifies details of unperformed shipments in a solution. For + trivial cases and/or if we are able to identify the cause for + skipping, we report the reason here. + + Attributes: + index (int): + The index corresponds to the index of the shipment in the + source ``ShipmentModel``. + label (str): + Copy of the corresponding + [Shipment.label][google.cloud.optimization.v1.Shipment.label], + if specified in the ``Shipment``. + reasons (MutableSequence[google.cloud.optimization_v1.types.SkippedShipment.Reason]): + A list of reasons that explain why the shipment was skipped. + See comment above ``Reason``. + """ + + class Reason(proto.Message): + r"""If we can explain why the shipment was skipped, reasons will be + listed here. If the reason is not the same for all vehicles, + ``reason`` will have more than 1 element. A skipped shipment cannot + have duplicate reasons, i.e. where all fields are the same except + for ``example_vehicle_index``. Example: + + :: + + reasons { + code: DEMAND_EXCEEDS_VEHICLE_CAPACITY + example_vehicle_index: 1 + example_exceeded_capacity_type: "Apples" + } + reasons { + code: DEMAND_EXCEEDS_VEHICLE_CAPACITY + example_vehicle_index: 3 + example_exceeded_capacity_type: "Pears" + } + reasons { + code: CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT + example_vehicle_index: 1 + } + + The skipped shipment is incompatible with all vehicles. The reasons + may be different for all vehicles but at least one vehicle's + "Apples" capacity would be exceeded (including vehicle 1), at least + one vehicle's "Pears" capacity would be exceeded (including vehicle + 3) and at least one vehicle's distance limit would be exceeded + (including vehicle 1). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + code (google.cloud.optimization_v1.types.SkippedShipment.Reason.Code): + Refer to the comments of Code. + example_vehicle_index (int): + If the reason is related to a + shipment-vehicle incompatibility, this field + provides the index of one relevant vehicle. + + This field is a member of `oneof`_ ``_example_vehicle_index``. + example_exceeded_capacity_type (str): + If the reason code is ``DEMAND_EXCEEDS_VEHICLE_CAPACITY``, + documents one capacity type that is exceeded. + """ + class Code(proto.Enum): + r"""Code identifying the reason type. The order here is + meaningless. In particular, it gives no indication of whether a + given reason will appear before another in the solution, if both + apply. + + Values: + CODE_UNSPECIFIED (0): + This should never be used. If we are unable + to understand why a shipment was skipped, we + simply return an empty set of reasons. + NO_VEHICLE (1): + There is no vehicle in the model making all + shipments infeasible. + DEMAND_EXCEEDS_VEHICLE_CAPACITY (2): + The demand of the shipment exceeds a vehicle's capacity for + some capacity types, one of which is + ``example_exceeded_capacity_type``. + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT (3): + The minimum distance necessary to perform this shipment, + i.e. from the vehicle's ``start_location`` to the shipment's + pickup and/or delivery locations and to the vehicle's end + location exceeds the vehicle's ``route_distance_limit``. + + Note that for this computation we use the geodesic + distances. + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT (4): + The minimum time necessary to perform this shipment, + including travel time, wait time and service time exceeds + the vehicle's ``route_duration_limit``. + + Note: travel time is computed in the best-case scenario, + namely as geodesic distance x 36 m/s (roughly 130 km/hour). + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TRAVEL_DURATION_LIMIT (5): + Same as above but we only compare minimum travel time and + the vehicle's ``travel_duration_limit``. + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TIME_WINDOWS (6): + The vehicle cannot perform this shipment in the best-case + scenario (see + ``CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT`` for + time computation) if it starts at its earliest start time: + the total time would make the vehicle end after its latest + end time. + VEHICLE_NOT_ALLOWED (7): + The ``allowed_vehicle_indices`` field of the shipment is not + empty and this vehicle does not belong to it. + """ + CODE_UNSPECIFIED = 0 + NO_VEHICLE = 1 + DEMAND_EXCEEDS_VEHICLE_CAPACITY = 2 + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT = 3 + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT = 4 + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TRAVEL_DURATION_LIMIT = 5 + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TIME_WINDOWS = 6 + VEHICLE_NOT_ALLOWED = 7 + + code: 'SkippedShipment.Reason.Code' = proto.Field( + proto.ENUM, + number=1, + enum='SkippedShipment.Reason.Code', + ) + example_vehicle_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + example_exceeded_capacity_type: str = proto.Field( + proto.STRING, + number=3, + ) + + index: int = proto.Field( + proto.INT32, + number=1, + ) + label: str = proto.Field( + proto.STRING, + number=2, + ) + reasons: MutableSequence[Reason] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Reason, + ) + + +class AggregatedMetrics(proto.Message): + r"""Aggregated metrics for + [ShipmentRoute][google.cloud.optimization.v1.ShipmentRoute] (resp. + for + [OptimizeToursResponse][google.cloud.optimization.v1.OptimizeToursResponse] + over all + [Transition][google.cloud.optimization.v1.ShipmentRoute.Transition] + and/or [Visit][google.cloud.optimization.v1.ShipmentRoute.Visit] + (resp. over all + [ShipmentRoute][google.cloud.optimization.v1.ShipmentRoute]) + elements. + + Attributes: + performed_shipment_count (int): + Number of shipments performed. Note that a + pickup and delivery pair only counts once. + travel_duration (google.protobuf.duration_pb2.Duration): + Total travel duration for a route or a + solution. + wait_duration (google.protobuf.duration_pb2.Duration): + Total wait duration for a route or a + solution. + delay_duration (google.protobuf.duration_pb2.Duration): + Total delay duration for a route or a + solution. + break_duration (google.protobuf.duration_pb2.Duration): + Total break duration for a route or a + solution. + visit_duration (google.protobuf.duration_pb2.Duration): + Total visit duration for a route or a + solution. + total_duration (google.protobuf.duration_pb2.Duration): + The total duration should be equal to the sum of all durations above. For routes, it also corresponds to [ShipmentRoute.vehicle_end_time][google.cloud.optimization.v1.ShipmentRoute.vehicle_end_time] + ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + + [ShipmentRoute.vehicle_start_time][google.cloud.optimization.v1.ShipmentRoute.vehicle_start_time]. + travel_distance_meters (float): + Total travel distance for a route or a + solution. + max_loads (MutableMapping[str, google.cloud.optimization_v1.types.ShipmentRoute.VehicleLoad]): + Maximum load achieved over the entire route (resp. + solution), for each of the quantities on this route (resp. + solution), computed as the maximum over all + [Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads] + (resp. + [ShipmentRoute.metrics.max_loads][google.cloud.optimization.v1.AggregatedMetrics.max_loads]. + costs (MutableMapping[str, float]): + Deprecated: Use + [ShipmentRoute.route_costs][google.cloud.optimization.v1.ShipmentRoute.route_costs] + and + [OptimizeToursResponse.Metrics.costs][google.cloud.optimization.v1.OptimizeToursResponse.Metrics.costs] + instead. + total_cost (float): + Deprecated: Use + [ShipmentRoute.route_total_cost][google.cloud.optimization.v1.ShipmentRoute.route_total_cost] + and + [OptimizeToursResponse.Metrics.total_cost][google.cloud.optimization.v1.OptimizeToursResponse.Metrics.total_cost] + instead. + """ + + performed_shipment_count: int = proto.Field( + proto.INT32, + number=1, + ) + travel_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + wait_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + delay_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + visit_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + total_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + travel_distance_meters: float = proto.Field( + proto.DOUBLE, + number=8, + ) + max_loads: MutableMapping[str, 'ShipmentRoute.VehicleLoad'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=9, + message='ShipmentRoute.VehicleLoad', + ) + costs: MutableMapping[str, float] = proto.MapField( + proto.STRING, + proto.DOUBLE, + number=10, + ) + total_cost: float = proto.Field( + proto.DOUBLE, + number=11, + ) + + +class InjectedSolutionConstraint(proto.Message): + r"""Solution injected in the request including information about + which visits must be constrained and how they must be + constrained. + + Attributes: + routes (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute]): + Routes of the solution to inject. Some routes may be omitted + from the original solution. The routes and skipped shipments + must satisfy the basic validity assumptions listed for + ``injected_first_solution_routes``. + skipped_shipments (MutableSequence[google.cloud.optimization_v1.types.SkippedShipment]): + Skipped shipments of the solution to inject. Some may be + omitted from the original solution. See the ``routes`` + field. + constraint_relaxations (MutableSequence[google.cloud.optimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation]): + For zero or more groups of vehicles, + specifies when and how much to relax + constraints. If this field is empty, all + non-empty vehicle routes are fully constrained. + """ + + class ConstraintRelaxation(proto.Message): + r"""For a group of vehicles, specifies at what threshold(s) constraints + on visits will be relaxed and to which level. Shipments listed in + the ``skipped_shipment`` field are constrained to be skipped; i.e., + they cannot be performed. + + Attributes: + relaxations (MutableSequence[google.cloud.optimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation.Relaxation]): + All the visit constraint relaxations that will apply to + visits on routes with vehicles in ``vehicle_indices``. + vehicle_indices (MutableSequence[int]): + Specifies the vehicle indices to which the visit constraint + ``relaxations`` apply. If empty, this is considered the + default and the ``relaxations`` apply to all vehicles that + are not specified in other ``constraint_relaxations``. There + can be at most one default, i.e., at most one constraint + relaxation field is allowed empty ``vehicle_indices``. A + vehicle index can only be listed once, even within several + ``constraint_relaxations``. + + A vehicle index is mapped the same as + [ShipmentRoute.vehicle_index][google.cloud.optimization.v1.ShipmentRoute.vehicle_index], + if ``interpret_injected_solutions_using_labels`` is true + (see ``fields`` comment). + """ + + class Relaxation(proto.Message): + r"""If ``relaxations`` is empty, the start time and sequence of all + visits on ``routes`` are fully constrained and no new visits may be + inserted or added to those routes. Also, a vehicle's start and end + time in ``routes`` is fully constrained, unless the vehicle is empty + (i.e., has no visits and has ``used_if_route_is_empty`` set to false + in the model). + + ``relaxations(i).level`` specifies the constraint relaxation level + applied to a visit #j that satisfies: + + - ``route.visits(j).start_time >= relaxations(i).threshold_time`` + AND + - ``j + 1 >= relaxations(i).threshold_visit_count`` + + Similarly, the vehicle start is relaxed to ``relaxations(i).level`` + if it satisfies: + + - ``vehicle_start_time >= relaxations(i).threshold_time`` AND + - ``relaxations(i).threshold_visit_count == 0`` and the vehicle end + is relaxed to ``relaxations(i).level`` if it satisfies: + - ``vehicle_end_time >= relaxations(i).threshold_time`` AND + - ``route.visits_size() + 1 >= relaxations(i).threshold_visit_count`` + + To apply a relaxation level if a visit meets the + ``threshold_visit_count`` OR the ``threshold_time`` add two + ``relaxations`` with the same ``level``: one with only + ``threshold_visit_count`` set and the other with only + ``threshold_time`` set. If a visit satisfies the conditions of + multiple ``relaxations``, the most relaxed level applies. As a + result, from the vehicle start through the route visits in order to + the vehicle end, the relaxation level becomes more relaxed: i.e., + the relaxation level is non-decreasing as the route progresses. + + The timing and sequence of route visits that do not satisfy the + threshold conditions of any ``relaxations`` are fully constrained + and no visits may be inserted into these sequences. Also, if a + vehicle start or end does not satisfy the conditions of any + relaxation the time is fixed, unless the vehicle is empty. + + Attributes: + level (google.cloud.optimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level): + The constraint relaxation level that applies when the + conditions at or after ``threshold_time`` AND at least + ``threshold_visit_count`` are satisfied. + threshold_time (google.protobuf.timestamp_pb2.Timestamp): + The time at or after which the relaxation ``level`` may be + applied. + threshold_visit_count (int): + The number of visits at or after which the relaxation + ``level`` may be applied. If ``threshold_visit_count`` is 0 + (or unset), the ``level`` may be applied directly at the + vehicle start. + + If it is ``route.visits_size() + 1``, the ``level`` may only + be applied to the vehicle end. If it is more than + ``route.visits_size() + 1``, ``level`` is not applied at all + for that route. + """ + class Level(proto.Enum): + r"""Expresses the different constraint relaxation levels, which + are applied for a visit and those that follow when it satisfies + the threshold conditions. + + The enumeration below is in order of increasing relaxation. + + Values: + LEVEL_UNSPECIFIED (0): + Implicit default relaxation level: no constraints are + relaxed, i.e., all visits are fully constrained. + + This value must not be explicitly used in ``level``. + RELAX_VISIT_TIMES_AFTER_THRESHOLD (1): + Visit start times and vehicle start/end times + will be relaxed, but each visit remains bound to + the same vehicle and the visit sequence must be + observed: no visit can be inserted between them + or before them. + RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD (2): + Same as ``RELAX_VISIT_TIMES_AFTER_THRESHOLD``, but the visit + sequence is also relaxed: visits remain simply bound to + their vehicle. + RELAX_ALL_AFTER_THRESHOLD (3): + Same as ``RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD``, + but the vehicle is also relaxed: visits are completely free + at or after the threshold time and can potentially become + unperformed. + """ + LEVEL_UNSPECIFIED = 0 + RELAX_VISIT_TIMES_AFTER_THRESHOLD = 1 + RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD = 2 + RELAX_ALL_AFTER_THRESHOLD = 3 + + level: 'InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level' = proto.Field( + proto.ENUM, + number=1, + enum='InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level', + ) + threshold_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + threshold_visit_count: int = proto.Field( + proto.INT32, + number=3, + ) + + relaxations: MutableSequence['InjectedSolutionConstraint.ConstraintRelaxation.Relaxation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='InjectedSolutionConstraint.ConstraintRelaxation.Relaxation', + ) + vehicle_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=2, + ) + + routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ShipmentRoute', + ) + skipped_shipments: MutableSequence['SkippedShipment'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SkippedShipment', + ) + constraint_relaxations: MutableSequence[ConstraintRelaxation] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=ConstraintRelaxation, + ) + + +class OptimizeToursValidationError(proto.Message): + r"""Describes an error encountered when validating an + ``OptimizeToursRequest``. + + Attributes: + code (int): + A validation error is defined by the pair (``code``, + ``display_name``) which are always present. + + Other fields (below) provide more context about the error. + + *MULTIPLE ERRORS*: When there are multiple errors, the + validation process tries to output several of them. Much + like a compiler, this is an imperfect process. Some + validation errors will be "fatal", meaning that they stop + the entire validation process. This is the case for + ``display_name="UNSPECIFIED"`` errors, among others. Some + may cause the validation process to skip other errors. + + *STABILITY*: ``code`` and ``display_name`` should be very + stable. But new codes and display names may appear over + time, which may cause a given (invalid) request to yield a + different (``code``, ``display_name``) pair because the new + error hid the old one (see "MULTIPLE ERRORS"). + + *REFERENCE*: A list of all (code, name) pairs: + + - UNSPECIFIED = 0; + + - VALIDATION_TIMEOUT_ERROR = 10; Validation couldn't be + completed within the deadline. + + - REQUEST_OPTIONS_ERROR = 12; + + - REQUEST_OPTIONS_INVALID_SOLVING_MODE = 1201; + - REQUEST_OPTIONS_INVALID_MAX_VALIDATION_ERRORS = 1203; + - REQUEST_OPTIONS_INVALID_GEODESIC_METERS_PER_SECOND = + 1204; + - REQUEST_OPTIONS_GEODESIC_METERS_PER_SECOND_TOO_SMALL = + 1205; + - REQUEST_OPTIONS_MISSING_GEODESIC_METERS_PER_SECOND = + 1206; + - REQUEST_OPTIONS_POPULATE_PATHFINDER_TRIPS_AND_GEODESIC_DISTANCE + = 1207; + - REQUEST_OPTIONS_COST_MODEL_OPTIONS_AND_GEODESIC_DISTANCE + = 1208; + - REQUEST_OPTIONS_TRAVEL_MODE_INCOMPATIBLE_WITH_TRAFFIC + = 1211; + - REQUEST_OPTIONS_MULTIPLE_TRAFFIC_FLAVORS = 1212; + - REQUEST_OPTIONS_INVALID_TRAFFIC_FLAVOR = 1213; + - REQUEST_OPTIONS_TRAFFIC_ENABLED_WITHOUT_GLOBAL_START_TIME + = 1214; + - REQUEST_OPTIONS_TRAFFIC_ENABLED_WITH_PRECEDENCES = + 1215; + - REQUEST_OPTIONS_TRAFFIC_PREFILL_MODE_INVALID = 1216; + - REQUEST_OPTIONS_TRAFFIC_PREFILL_ENABLED_WITHOUT_TRAFFIC + = 1217; + + - INJECTED_SOLUTION_ERROR = 20; + + - INJECTED_SOLUTION_MISSING_LABEL = 2000; + - INJECTED_SOLUTION_DUPLICATE_LABEL = 2001; + - INJECTED_SOLUTION_AMBIGUOUS_INDEX = 2002; + - INJECTED_SOLUTION_INFEASIBLE_AFTER_GETTING_TRAVEL_TIMES + = 2003; + - INJECTED_SOLUTION_TRANSITION_INCONSISTENT_WITH_ACTUAL_TRAVEL + = 2004; + - INJECTED_SOLUTION_CONCURRENT_SOLUTION_TYPES = 2005; + - INJECTED_SOLUTION_MORE_THAN_ONE_PER_TYPE = 2006; + - INJECTED_SOLUTION_REFRESH_WITHOUT_POPULATE = 2008; + + - SHIPMENT_MODEL_ERROR = 22; + + - SHIPMENT_MODEL_TOO_LARGE = 2200; + - SHIPMENT_MODEL_TOO_MANY_CAPACITY_TYPES = 2201; + - SHIPMENT_MODEL_GLOBAL_START_TIME_NEGATIVE_OR_NAN = + 2202; + - SHIPMENT_MODEL_GLOBAL_END_TIME_TOO_LARGE_OR_NAN = + 2203; + - SHIPMENT_MODEL_GLOBAL_START_TIME_AFTER_GLOBAL_END_TIME + = 2204; + - SHIPMENT_MODEL_GLOBAL_DURATION_TOO_LONG = 2205; + - SHIPMENT_MODEL_MAX_ACTIVE_VEHICLES_NOT_POSITIVE = + 2206; + - SHIPMENT_MODEL_DURATION_MATRIX_TOO_LARGE = 2207; + + - INDEX_ERROR = 24; + + - TAG_ERROR = 26; + + - TIME_WINDOW_ERROR = 28; + + - TIME_WINDOW_INVALID_START_TIME = 2800; + - TIME_WINDOW_INVALID_END_TIME = 2801; + - TIME_WINDOW_INVALID_SOFT_START_TIME = 2802; + - TIME_WINDOW_INVALID_SOFT_END_TIME = 2803; + - TIME_WINDOW_OUTSIDE_GLOBAL_TIME_WINDOW = 2804; + - TIME_WINDOW_START_TIME_AFTER_END_TIME = 2805; + - TIME_WINDOW_INVALID_COST_PER_HOUR_BEFORE_SOFT_START_TIME + = 2806; + - TIME_WINDOW_INVALID_COST_PER_HOUR_AFTER_SOFT_END_TIME + = 2807; + - TIME_WINDOW_COST_BEFORE_SOFT_START_TIME_WITHOUT_SOFT_START_TIME + = 2808; + - TIME_WINDOW_COST_AFTER_SOFT_END_TIME_WITHOUT_SOFT_END_TIME + = 2809; + - TIME_WINDOW_SOFT_START_TIME_WITHOUT_COST_BEFORE_SOFT_START_TIME + = 2810; + - TIME_WINDOW_SOFT_END_TIME_WITHOUT_COST_AFTER_SOFT_END_TIME + = 2811; + - TIME_WINDOW_OVERLAPPING_ADJACENT_OR_EARLIER_THAN_PREVIOUS + = 2812; + - TIME_WINDOW_START_TIME_AFTER_SOFT_START_TIME = 2813; + - TIME_WINDOW_SOFT_START_TIME_AFTER_END_TIME = 2814; + - TIME_WINDOW_START_TIME_AFTER_SOFT_END_TIME = 2815; + - TIME_WINDOW_SOFT_END_TIME_AFTER_END_TIME = 2816; + - TIME_WINDOW_COST_BEFORE_SOFT_START_TIME_SET_AND_MULTIPLE_WINDOWS + = 2817; + - TIME_WINDOW_COST_AFTER_SOFT_END_TIME_SET_AND_MULTIPLE_WINDOWS + = 2818; + - TRANSITION_ATTRIBUTES_ERROR = 30; + - TRANSITION_ATTRIBUTES_INVALID_COST = 3000; + - TRANSITION_ATTRIBUTES_INVALID_COST_PER_KILOMETER = + 3001; + - TRANSITION_ATTRIBUTES_DUPLICATE_TAG_PAIR = 3002; + - TRANSITION_ATTRIBUTES_DISTANCE_LIMIT_MAX_METERS_UNSUPPORTED + = 3003; + - TRANSITION_ATTRIBUTES_UNSPECIFIED_SOURCE_TAGS = 3004; + - TRANSITION_ATTRIBUTES_CONFLICTING_SOURCE_TAGS_FIELDS = + 3005; + - TRANSITION_ATTRIBUTES_UNSPECIFIED_DESTINATION_TAGS = + 3006; + - TRANSITION_ATTRIBUTES_CONFLICTING_DESTINATION_TAGS_FIELDS + = 3007; + - TRANSITION_ATTRIBUTES_DELAY_DURATION_NEGATIVE_OR_NAN = + 3008; + - TRANSITION_ATTRIBUTES_DELAY_DURATION_EXCEEDS_GLOBAL_DURATION + = 3009; + + - AMOUNT_ERROR = 31; + + - AMOUNT_NEGATIVE_VALUE = 3100; + + - LOAD_LIMIT_ERROR = 33; + + - LOAD_LIMIT_INVALID_COST_ABOVE_SOFT_MAX = 3303; + - LOAD_LIMIT_SOFT_MAX_WITHOUT_COST_ABOVE_SOFT_MAX = + 3304; + - LOAD_LIMIT_COST_ABOVE_SOFT_MAX_WITHOUT_SOFT_MAX = + 3305; + - LOAD_LIMIT_NEGATIVE_SOFT_MAX = 3306; + - LOAD_LIMIT_MIXED_DEMAND_TYPE = 3307; + - LOAD_LIMIT_MAX_LOAD_NEGATIVE_VALUE = 3308; + - LOAD_LIMIT_SOFT_MAX_ABOVE_MAX = 3309; + + - INTERVAL_ERROR = 34; + + - INTERVAL_MIN_EXCEEDS_MAX = 3401; + - INTERVAL_NEGATIVE_MIN = 3402; + - INTERVAL_NEGATIVE_MAX = 3403; + - INTERVAL_MIN_EXCEEDS_CAPACITY = 3404; + - INTERVAL_MAX_EXCEEDS_CAPACITY = 3405; + + - DISTANCE_LIMIT_ERROR = 36; + + - DISTANCE_LIMIT_INVALID_COST_AFTER_SOFT_MAX = 3601; + - DISTANCE_LIMIT_SOFT_MAX_WITHOUT_COST_AFTER_SOFT_MAX = + 3602; + - DISTANCE_LIMIT_COST_AFTER_SOFT_MAX_WITHOUT_SOFT_MAX = + 3603; + - DISTANCE_LIMIT_NEGATIVE_MAX = 3604; + - DISTANCE_LIMIT_NEGATIVE_SOFT_MAX = 3605; + - DISTANCE_LIMIT_SOFT_MAX_LARGER_THAN_MAX = 3606; + + - DURATION_LIMIT_ERROR = 38; + + - DURATION_LIMIT_MAX_DURATION_NEGATIVE_OR_NAN = 3800; + - DURATION_LIMIT_SOFT_MAX_DURATION_NEGATIVE_OR_NAN = + 3801; + - DURATION_LIMIT_INVALID_COST_PER_HOUR_AFTER_SOFT_MAX = + 3802; + - DURATION_LIMIT_SOFT_MAX_WITHOUT_COST_AFTER_SOFT_MAX = + 3803; + - DURATION_LIMIT_COST_AFTER_SOFT_MAX_WITHOUT_SOFT_MAX = + 3804; + - DURATION_LIMIT_QUADRATIC_SOFT_MAX_DURATION_NEGATIVE_OR_NAN + = 3805; + - DURATION_LIMIT_INVALID_COST_AFTER_QUADRATIC_SOFT_MAX = + 3806; + - DURATION_LIMIT_QUADRATIC_SOFT_MAX_WITHOUT_COST_PER_SQUARE_HOUR + = 3807; + - DURATION_LIMIT_COST_PER_SQUARE_HOUR_WITHOUT_QUADRATIC_SOFT_MAX + = 3808; + - DURATION_LIMIT_QUADRATIC_SOFT_MAX_WITHOUT_MAX = 3809; + - DURATION_LIMIT_SOFT_MAX_LARGER_THAN_MAX = 3810; + - DURATION_LIMIT_QUADRATIC_SOFT_MAX_LARGER_THAN_MAX = + 3811; + - DURATION_LIMIT_DIFF_BETWEEN_MAX_AND_QUADRATIC_SOFT_MAX_TOO_LARGE + = 3812; + - DURATION_LIMIT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION = + 3813; + - DURATION_LIMIT_SOFT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION + = 3814; + - DURATION_LIMIT_QUADRATIC_SOFT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION + = 3815; + + - SHIPMENT_ERROR = 40; + + - SHIPMENT_PD_LIMIT_WITHOUT_PICKUP_AND_DELIVERY = 4014; + - SHIPMENT_PD_ABSOLUTE_DETOUR_LIMIT_DURATION_NEGATIVE_OR_NAN + = 4000; + - SHIPMENT_PD_ABSOLUTE_DETOUR_LIMIT_DURATION_EXCEEDS_GLOBAL_DURATION + = 4001; + - SHIPMENT_PD_RELATIVE_DETOUR_LIMIT_INVALID = 4015; + - SHIPMENT_PD_DETOUR_LIMIT_AND_EXTRA_VISIT_DURATION = + 4016; + - SHIPMENT_PD_TIME_LIMIT_DURATION_NEGATIVE_OR_NAN = + 4002; + - SHIPMENT_PD_TIME_LIMIT_DURATION_EXCEEDS_GLOBAL_DURATION + = 4003; + - SHIPMENT_EMPTY_SHIPMENT_TYPE = 4004; + - SHIPMENT_NO_PICKUP_NO_DELIVERY = 4005; + - SHIPMENT_INVALID_PENALTY_COST = 4006; + - SHIPMENT_ALLOWED_VEHICLE_INDEX_OUT_OF_BOUNDS = 4007; + - SHIPMENT_DUPLICATE_ALLOWED_VEHICLE_INDEX = 4008; + - SHIPMENT_INCONSISTENT_COST_FOR_VEHICLE_SIZE_WITHOUT_INDEX + = 4009; + - SHIPMENT_INCONSISTENT_COST_FOR_VEHICLE_SIZE_WITH_INDEX + = 4010; + - SHIPMENT_INVALID_COST_FOR_VEHICLE = 4011; + - SHIPMENT_COST_FOR_VEHICLE_INDEX_OUT_OF_BOUNDS = 4012; + - SHIPMENT_DUPLICATE_COST_FOR_VEHICLE_INDEX = 4013; + + - VEHICLE_ERROR = 42; + + - VEHICLE_EMPTY_REQUIRED_OPERATOR_TYPE = 4200; + - VEHICLE_DUPLICATE_REQUIRED_OPERATOR_TYPE = 4201; + - VEHICLE_NO_OPERATOR_WITH_REQUIRED_OPERATOR_TYPE = + 4202; + - VEHICLE_EMPTY_START_TAG = 4203; + - VEHICLE_DUPLICATE_START_TAG = 4204; + - VEHICLE_EMPTY_END_TAG = 4205; + - VEHICLE_DUPLICATE_END_TAG = 4206; + - VEHICLE_EXTRA_VISIT_DURATION_NEGATIVE_OR_NAN = 4207; + - VEHICLE_EXTRA_VISIT_DURATION_EXCEEDS_GLOBAL_DURATION = + 4208; + - VEHICLE_EXTRA_VISIT_DURATION_EMPTY_KEY = 4209; + - VEHICLE_FIRST_SHIPMENT_INDEX_OUT_OF_BOUNDS = 4210; + - VEHICLE_FIRST_SHIPMENT_IGNORED = 4211; + - VEHICLE_FIRST_SHIPMENT_NOT_BOUND = 4212; + - VEHICLE_LAST_SHIPMENT_INDEX_OUT_OF_BOUNDS = 4213; + - VEHICLE_LAST_SHIPMENT_IGNORED = 4214; + - VEHICLE_LAST_SHIPMENT_NOT_BOUND = 4215; + - VEHICLE_IGNORED_WITH_USED_IF_ROUTE_IS_EMPTY = 4216; + - VEHICLE_INVALID_COST_PER_KILOMETER = 4217; + - VEHICLE_INVALID_COST_PER_HOUR = 4218; + - VEHICLE_INVALID_COST_PER_TRAVELED_HOUR = 4219; + - VEHICLE_INVALID_FIXED_COST = 4220; + - VEHICLE_INVALID_TRAVEL_DURATION_MULTIPLE = 4221; + - VEHICLE_TRAVEL_DURATION_MULTIPLE_WITH_SHIPMENT_PD_DETOUR_LIMITS + = 4223; + - VEHICLE_MATRIX_INDEX_WITH_SHIPMENT_PD_DETOUR_LIMITS = + 4224; + - VEHICLE_MINIMUM_DURATION_LONGER_THAN_DURATION_LIMIT = + 4222; + + - VISIT_REQUEST_ERROR = 44; + + - VISIT_REQUEST_EMPTY_TAG = 4400; + - VISIT_REQUEST_DUPLICATE_TAG = 4401; + - VISIT_REQUEST_DURATION_NEGATIVE_OR_NAN = 4404; + - VISIT_REQUEST_DURATION_EXCEEDS_GLOBAL_DURATION = 4405; + + - PRECEDENCE_ERROR = 46; + + - BREAK_ERROR = 48; + + - BREAK_RULE_EMPTY = 4800; + - BREAK_REQUEST_UNSPECIFIED_DURATION = 4801; + - BREAK_REQUEST_UNSPECIFIED_EARLIEST_START_TIME = 4802; + - BREAK_REQUEST_UNSPECIFIED_LATEST_START_TIME = 4803; + - BREAK_REQUEST_DURATION_NEGATIVE_OR_NAN = 4804; = 4804; + - BREAK_REQUEST_LATEST_START_TIME_BEFORE_EARLIEST_START_TIME + = 4805; + - BREAK_REQUEST_EARLIEST_START_TIME_BEFORE_GLOBAL_START_TIME + = 4806; + - BREAK_REQUEST_LATEST_END_TIME_AFTER_GLOBAL_END_TIME = + 4807; + - BREAK_REQUEST_NON_SCHEDULABLE = 4808; + - BREAK_FREQUENCY_MAX_INTER_BREAK_DURATION_NEGATIVE_OR_NAN + = 4809; + - BREAK_FREQUENCY_MIN_BREAK_DURATION_NEGATIVE_OR_NAN = + 4810; + - BREAK_FREQUENCY_MIN_BREAK_DURATION_EXCEEDS_GLOBAL_DURATION + = 4811; + - BREAK_FREQUENCY_MAX_INTER_BREAK_DURATION_EXCEEDS_GLOBAL_DURATION + = 4812; + - BREAK_REQUEST_DURATION_EXCEEDS_GLOBAL_DURATION = 4813; + - BREAK_FREQUENCY_MISSING_MAX_INTER_BREAK_DURATION = + 4814; + - BREAK_FREQUENCY_MISSING_MIN_BREAK_DURATION = 4815; + + - SHIPMENT_TYPE_INCOMPATIBILITY_ERROR = 50; + + - SHIPMENT_TYPE_INCOMPATIBILITY_EMPTY_TYPE = 5001; + - SHIPMENT_TYPE_INCOMPATIBILITY_LESS_THAN_TWO_TYPES = + 5002; + - SHIPMENT_TYPE_INCOMPATIBILITY_DUPLICATE_TYPE = 5003; + - SHIPMENT_TYPE_INCOMPATIBILITY_INVALID_INCOMPATIBILITY_MODE + = 5004; + - SHIPMENT_TYPE_INCOMPATIBILITY_TOO_MANY_INCOMPATIBILITIES + = 5005; + + - SHIPMENT_TYPE_REQUIREMENT_ERROR = 52; + + - SHIPMENT_TYPE_REQUIREMENT_NO_REQUIRED_TYPE = 52001; + - SHIPMENT_TYPE_REQUIREMENT_NO_DEPENDENT_TYPE = 52002; + - SHIPMENT_TYPE_REQUIREMENT_INVALID_REQUIREMENT_MODE = + 52003; + - SHIPMENT_TYPE_REQUIREMENT_TOO_MANY_REQUIREMENTS = + 52004; + - SHIPMENT_TYPE_REQUIREMENT_EMPTY_REQUIRED_TYPE = 52005; + - SHIPMENT_TYPE_REQUIREMENT_DUPLICATE_REQUIRED_TYPE = + 52006; + - SHIPMENT_TYPE_REQUIREMENT_NO_REQUIRED_TYPE_FOUND = + 52007; + - SHIPMENT_TYPE_REQUIREMENT_EMPTY_DEPENDENT_TYPE = + 52008; + - SHIPMENT_TYPE_REQUIREMENT_DUPLICATE_DEPENDENT_TYPE = + 52009; + - SHIPMENT_TYPE_REQUIREMENT_SELF_DEPENDENT_TYPE = 52010; + - SHIPMENT_TYPE_REQUIREMENT_GRAPH_HAS_CYCLES = 52011; + + - VEHICLE_OPERATOR_ERROR = 54; + + - VEHICLE_OPERATOR_EMPTY_TYPE = 5400; + - VEHICLE_OPERATOR_MULTIPLE_START_TIME_WINDOWS = 5401; + - VEHICLE_OPERATOR_SOFT_START_TIME_WINDOW = 5402; + - VEHICLE_OPERATOR_MULTIPLE_END_TIME_WINDOWS = 5403; + - VEHICLE_OPERATOR_SOFT_END_TIME_WINDOW = 5404; + + - DURATION_SECONDS_MATRIX_ERROR = 56; + + - DURATION_SECONDS_MATRIX_DURATION_NEGATIVE_OR_NAN = + 5600; + - DURATION_SECONDS_MATRIX_DURATION_EXCEEDS_GLOBAL_DURATION + = 5601; + display_name (str): + The error display name. + fields (MutableSequence[google.cloud.optimization_v1.types.OptimizeToursValidationError.FieldReference]): + An error context may involve 0, 1 (most of the time) or more + fields. For example, referring to vehicle #4 and shipment + #2's first pickup can be done as follows: + + :: + + fields { name: "vehicles" index: 4} + fields { name: "shipments" index: 2 sub_field {name: "pickups" index: 0} } + + Note, however, that the cardinality of ``fields`` should not + change for a given error code. + error_message (str): + Human-readable string describing the error. There is a 1:1 + mapping between ``code`` and ``error_message`` (when code != + "UNSPECIFIED"). + + *STABILITY*: Not stable: the error message associated to a + given ``code`` may change (hopefully to clarify it) over + time. Please rely on the ``display_name`` and ``code`` + instead. + offending_values (str): + May contain the value(s) of the field(s). + This is not always available. You should + absolutely not rely on it and use it only for + manual model debugging. + """ + + class FieldReference(proto.Message): + r"""Specifies a context for the validation error. A ``FieldReference`` + always refers to a given field in this file and follows the same + hierarchical structure. For example, we may specify element #2 of + ``start_time_windows`` of vehicle #5 using: + + :: + + name: "vehicles" index: 5 sub_field { name: "end_time_windows" index: 2 } + + We however omit top-level entities such as ``OptimizeToursRequest`` + or ``ShipmentModel`` to avoid crowding the message. + + 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): + Name of the field, e.g., "vehicles". + index (int): + Index of the field if repeated. + + This field is a member of `oneof`_ ``index_or_key``. + key (str): + Key if the field is a map. + + This field is a member of `oneof`_ ``index_or_key``. + sub_field (google.cloud.optimization_v1.types.OptimizeToursValidationError.FieldReference): + Recursively nested sub-field, if needed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + index: int = proto.Field( + proto.INT32, + number=2, + oneof='index_or_key', + ) + key: str = proto.Field( + proto.STRING, + number=4, + oneof='index_or_key', + ) + sub_field: 'OptimizeToursValidationError.FieldReference' = proto.Field( + proto.MESSAGE, + number=3, + message='OptimizeToursValidationError.FieldReference', + ) + + code: int = proto.Field( + proto.INT32, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + fields: MutableSequence[FieldReference] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=FieldReference, + ) + error_message: str = proto.Field( + proto.STRING, + number=4, + ) + offending_values: str = proto.Field( + proto.STRING, + number=5, + ) + + +__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..67a0b27 --- /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/optimization_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/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_async.py new file mode 100644 index 0000000..f091826 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_async.py @@ -0,0 +1,61 @@ +# -*- 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 BatchOptimizeTours +# 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-optimization + + +# [START cloudoptimization_v1_generated_FleetRouting_BatchOptimizeTours_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 optimization_v1 + + +async def sample_batch_optimize_tours(): + # Create a client + client = optimization_v1.FleetRoutingAsyncClient() + + # Initialize request argument(s) + model_configs = optimization_v1.AsyncModelConfig() + model_configs.input_config.gcs_source.uri = "uri_value" + model_configs.output_config.gcs_destination.uri = "uri_value" + + request = optimization_v1.BatchOptimizeToursRequest( + parent="parent_value", + model_configs=model_configs, + ) + + # Make the request + operation = client.batch_optimize_tours(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudoptimization_v1_generated_FleetRouting_BatchOptimizeTours_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_sync.py new file mode 100644 index 0000000..7750123 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_sync.py @@ -0,0 +1,61 @@ +# -*- 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 BatchOptimizeTours +# 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-optimization + + +# [START cloudoptimization_v1_generated_FleetRouting_BatchOptimizeTours_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 optimization_v1 + + +def sample_batch_optimize_tours(): + # Create a client + client = optimization_v1.FleetRoutingClient() + + # Initialize request argument(s) + model_configs = optimization_v1.AsyncModelConfig() + model_configs.input_config.gcs_source.uri = "uri_value" + model_configs.output_config.gcs_destination.uri = "uri_value" + + request = optimization_v1.BatchOptimizeToursRequest( + parent="parent_value", + model_configs=model_configs, + ) + + # Make the request + operation = client.batch_optimize_tours(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudoptimization_v1_generated_FleetRouting_BatchOptimizeTours_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_async.py new file mode 100644 index 0000000..1ff26eb --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_async.py @@ -0,0 +1,52 @@ +# -*- 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 OptimizeTours +# 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-optimization + + +# [START cloudoptimization_v1_generated_FleetRouting_OptimizeTours_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 optimization_v1 + + +async def sample_optimize_tours(): + # Create a client + client = optimization_v1.FleetRoutingAsyncClient() + + # Initialize request argument(s) + request = optimization_v1.OptimizeToursRequest( + parent="parent_value", + ) + + # Make the request + response = await client.optimize_tours(request=request) + + # Handle the response + print(response) + +# [END cloudoptimization_v1_generated_FleetRouting_OptimizeTours_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_sync.py new file mode 100644 index 0000000..a0e4335 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_sync.py @@ -0,0 +1,52 @@ +# -*- 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 OptimizeTours +# 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-optimization + + +# [START cloudoptimization_v1_generated_FleetRouting_OptimizeTours_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 optimization_v1 + + +def sample_optimize_tours(): + # Create a client + client = optimization_v1.FleetRoutingClient() + + # Initialize request argument(s) + request = optimization_v1.OptimizeToursRequest( + parent="parent_value", + ) + + # Make the request + response = client.optimize_tours(request=request) + + # Handle the response + print(response) + +# [END cloudoptimization_v1_generated_FleetRouting_OptimizeTours_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.optimization.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.optimization.v1.json new file mode 100644 index 0000000..d38082d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.optimization.v1.json @@ -0,0 +1,321 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.optimization.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-optimization", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.optimization_v1.FleetRoutingAsyncClient", + "shortName": "FleetRoutingAsyncClient" + }, + "fullName": "google.cloud.optimization_v1.FleetRoutingAsyncClient.batch_optimize_tours", + "method": { + "fullName": "google.cloud.optimization.v1.FleetRouting.BatchOptimizeTours", + "service": { + "fullName": "google.cloud.optimization.v1.FleetRouting", + "shortName": "FleetRouting" + }, + "shortName": "BatchOptimizeTours" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.optimization_v1.types.BatchOptimizeToursRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "batch_optimize_tours" + }, + "description": "Sample for BatchOptimizeTours", + "file": "cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudoptimization_v1_generated_FleetRouting_BatchOptimizeTours_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.optimization_v1.FleetRoutingClient", + "shortName": "FleetRoutingClient" + }, + "fullName": "google.cloud.optimization_v1.FleetRoutingClient.batch_optimize_tours", + "method": { + "fullName": "google.cloud.optimization.v1.FleetRouting.BatchOptimizeTours", + "service": { + "fullName": "google.cloud.optimization.v1.FleetRouting", + "shortName": "FleetRouting" + }, + "shortName": "BatchOptimizeTours" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.optimization_v1.types.BatchOptimizeToursRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "batch_optimize_tours" + }, + "description": "Sample for BatchOptimizeTours", + "file": "cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudoptimization_v1_generated_FleetRouting_BatchOptimizeTours_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.optimization_v1.FleetRoutingAsyncClient", + "shortName": "FleetRoutingAsyncClient" + }, + "fullName": "google.cloud.optimization_v1.FleetRoutingAsyncClient.optimize_tours", + "method": { + "fullName": "google.cloud.optimization.v1.FleetRouting.OptimizeTours", + "service": { + "fullName": "google.cloud.optimization.v1.FleetRouting", + "shortName": "FleetRouting" + }, + "shortName": "OptimizeTours" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.optimization_v1.types.OptimizeToursRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.optimization_v1.types.OptimizeToursResponse", + "shortName": "optimize_tours" + }, + "description": "Sample for OptimizeTours", + "file": "cloudoptimization_v1_generated_fleet_routing_optimize_tours_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudoptimization_v1_generated_FleetRouting_OptimizeTours_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudoptimization_v1_generated_fleet_routing_optimize_tours_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.optimization_v1.FleetRoutingClient", + "shortName": "FleetRoutingClient" + }, + "fullName": "google.cloud.optimization_v1.FleetRoutingClient.optimize_tours", + "method": { + "fullName": "google.cloud.optimization.v1.FleetRouting.OptimizeTours", + "service": { + "fullName": "google.cloud.optimization.v1.FleetRouting", + "shortName": "FleetRouting" + }, + "shortName": "OptimizeTours" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.optimization_v1.types.OptimizeToursRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.optimization_v1.types.OptimizeToursResponse", + "shortName": "optimize_tours" + }, + "description": "Sample for OptimizeTours", + "file": "cloudoptimization_v1_generated_fleet_routing_optimize_tours_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudoptimization_v1_generated_FleetRouting_OptimizeTours_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudoptimization_v1_generated_fleet_routing_optimize_tours_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1/scripts/fixup_optimization_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_optimization_v1_keywords.py new file mode 100644 index 0000000..514f7ab --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_optimization_v1_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 optimizationCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_optimize_tours': ('parent', 'model_configs', ), + 'optimize_tours': ('parent', 'timeout', 'model', 'solving_mode', 'max_validation_errors', 'search_mode', 'injected_first_solution_routes', 'injected_solution_constraint', 'refresh_details_routes', 'interpret_injected_solutions_using_labels', 'consider_road_traffic', 'populate_polylines', 'populate_transition_polylines', 'allow_large_deadline_despite_interruption_risk', 'use_geodesic_distances', 'geodesic_meters_per_second', 'label', 'populate_travel_step_polylines', ), + } + + 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=optimizationCallTransformer(), +): + """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 optimization 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..bb1428d --- /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-optimization' + + +description = "Google Cloud Optimization API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/optimization/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-optimization" + +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/optimization_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/optimization_v1/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/optimization_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/optimization_v1/test_fleet_routing.py b/owl-bot-staging/v1/tests/unit/gapic/optimization_v1/test_fleet_routing.py new file mode 100644 index 0000000..1c94671 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/optimization_v1/test_fleet_routing.py @@ -0,0 +1,2104 @@ +# -*- 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 future +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 operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.optimization_v1.services.fleet_routing import FleetRoutingAsyncClient +from google.cloud.optimization_v1.services.fleet_routing import FleetRoutingClient +from google.cloud.optimization_v1.services.fleet_routing import transports +from google.cloud.optimization_v1.types import async_model +from google.cloud.optimization_v1.types import fleet_routing +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import latlng_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 FleetRoutingClient._get_default_mtls_endpoint(None) is None + assert FleetRoutingClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert FleetRoutingClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert FleetRoutingClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert FleetRoutingClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert FleetRoutingClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (FleetRoutingClient, "grpc"), + (FleetRoutingAsyncClient, "grpc_asyncio"), + (FleetRoutingClient, "rest"), +]) +def test_fleet_routing_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 == ( + 'cloudoptimization.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudoptimization.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.FleetRoutingGrpcTransport, "grpc"), + (transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.FleetRoutingRestTransport, "rest"), +]) +def test_fleet_routing_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", [ + (FleetRoutingClient, "grpc"), + (FleetRoutingAsyncClient, "grpc_asyncio"), + (FleetRoutingClient, "rest"), +]) +def test_fleet_routing_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 == ( + 'cloudoptimization.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudoptimization.googleapis.com' + ) + + +def test_fleet_routing_client_get_transport_class(): + transport = FleetRoutingClient.get_transport_class() + available_transports = [ + transports.FleetRoutingGrpcTransport, + transports.FleetRoutingRestTransport, + ] + assert transport in available_transports + + transport = FleetRoutingClient.get_transport_class("grpc") + assert transport == transports.FleetRoutingGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FleetRoutingClient, transports.FleetRoutingGrpcTransport, "grpc"), + (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio"), + (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest"), +]) +@mock.patch.object(FleetRoutingClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FleetRoutingClient)) +@mock.patch.object(FleetRoutingAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FleetRoutingAsyncClient)) +def test_fleet_routing_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(FleetRoutingClient, '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(FleetRoutingClient, '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", [ + (FleetRoutingClient, transports.FleetRoutingGrpcTransport, "grpc", "true"), + (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (FleetRoutingClient, transports.FleetRoutingGrpcTransport, "grpc", "false"), + (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest", "true"), + (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest", "false"), +]) +@mock.patch.object(FleetRoutingClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FleetRoutingClient)) +@mock.patch.object(FleetRoutingAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FleetRoutingAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_fleet_routing_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", [ + FleetRoutingClient, FleetRoutingAsyncClient +]) +@mock.patch.object(FleetRoutingClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FleetRoutingClient)) +@mock.patch.object(FleetRoutingAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FleetRoutingAsyncClient)) +def test_fleet_routing_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", [ + (FleetRoutingClient, transports.FleetRoutingGrpcTransport, "grpc"), + (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio"), + (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest"), +]) +def test_fleet_routing_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", [ + (FleetRoutingClient, transports.FleetRoutingGrpcTransport, "grpc", grpc_helpers), + (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest", None), +]) +def test_fleet_routing_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_fleet_routing_client_client_options_from_dict(): + with mock.patch('google.cloud.optimization_v1.services.fleet_routing.transports.FleetRoutingGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = FleetRoutingClient( + 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", [ + (FleetRoutingClient, transports.FleetRoutingGrpcTransport, "grpc", grpc_helpers), + (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_fleet_routing_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( + "cloudoptimization.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="cloudoptimization.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + fleet_routing.OptimizeToursRequest, + dict, +]) +def test_optimize_tours(request_type, transport: str = 'grpc'): + client = FleetRoutingClient( + 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.optimize_tours), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = fleet_routing.OptimizeToursResponse( + request_label='request_label_value', + total_cost=0.10840000000000001, + ) + response = client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == fleet_routing.OptimizeToursRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet_routing.OptimizeToursResponse) + assert response.request_label == 'request_label_value' + assert math.isclose(response.total_cost, 0.10840000000000001, rel_tol=1e-6) + + +def test_optimize_tours_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 = FleetRoutingClient( + 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.optimize_tours), + '__call__') as call: + client.optimize_tours() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == fleet_routing.OptimizeToursRequest() + +@pytest.mark.asyncio +async def test_optimize_tours_async(transport: str = 'grpc_asyncio', request_type=fleet_routing.OptimizeToursRequest): + client = FleetRoutingAsyncClient( + 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.optimize_tours), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(fleet_routing.OptimizeToursResponse( + request_label='request_label_value', + total_cost=0.10840000000000001, + )) + response = await client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == fleet_routing.OptimizeToursRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet_routing.OptimizeToursResponse) + assert response.request_label == 'request_label_value' + assert math.isclose(response.total_cost, 0.10840000000000001, rel_tol=1e-6) + + +@pytest.mark.asyncio +async def test_optimize_tours_async_from_dict(): + await test_optimize_tours_async(request_type=dict) + + +def test_optimize_tours_field_headers(): + client = FleetRoutingClient( + 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 = fleet_routing.OptimizeToursRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.optimize_tours), + '__call__') as call: + call.return_value = fleet_routing.OptimizeToursResponse() + client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_optimize_tours_field_headers_async(): + client = FleetRoutingAsyncClient( + 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 = fleet_routing.OptimizeToursRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.optimize_tours), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fleet_routing.OptimizeToursResponse()) + await client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + fleet_routing.BatchOptimizeToursRequest, + dict, +]) +def test_batch_optimize_tours(request_type, transport: str = 'grpc'): + client = FleetRoutingClient( + 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.batch_optimize_tours), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == fleet_routing.BatchOptimizeToursRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_optimize_tours_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 = FleetRoutingClient( + 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.batch_optimize_tours), + '__call__') as call: + client.batch_optimize_tours() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == fleet_routing.BatchOptimizeToursRequest() + +@pytest.mark.asyncio +async def test_batch_optimize_tours_async(transport: str = 'grpc_asyncio', request_type=fleet_routing.BatchOptimizeToursRequest): + client = FleetRoutingAsyncClient( + 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.batch_optimize_tours), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == fleet_routing.BatchOptimizeToursRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_optimize_tours_async_from_dict(): + await test_batch_optimize_tours_async(request_type=dict) + + +def test_batch_optimize_tours_field_headers(): + client = FleetRoutingClient( + 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 = fleet_routing.BatchOptimizeToursRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_optimize_tours_field_headers_async(): + client = FleetRoutingAsyncClient( + 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 = fleet_routing.BatchOptimizeToursRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + fleet_routing.OptimizeToursRequest, + dict, +]) +def test_optimize_tours_rest(request_type): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + 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 = fleet_routing.OptimizeToursResponse( + request_label='request_label_value', + total_cost=0.10840000000000001, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = fleet_routing.OptimizeToursResponse.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.optimize_tours(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet_routing.OptimizeToursResponse) + assert response.request_label == 'request_label_value' + assert math.isclose(response.total_cost, 0.10840000000000001, rel_tol=1e-6) + + +def test_optimize_tours_rest_required_fields(request_type=fleet_routing.OptimizeToursRequest): + transport_class = transports.FleetRoutingRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).optimize_tours._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).optimize_tours._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = fleet_routing.OptimizeToursResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = fleet_routing.OptimizeToursResponse.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.optimize_tours(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_optimize_tours_rest_unset_required_fields(): + transport = transports.FleetRoutingRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.optimize_tours._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_optimize_tours_rest_interceptors(null_interceptor): + transport = transports.FleetRoutingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FleetRoutingRestInterceptor(), + ) + client = FleetRoutingClient(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.FleetRoutingRestInterceptor, "post_optimize_tours") as post, \ + mock.patch.object(transports.FleetRoutingRestInterceptor, "pre_optimize_tours") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = fleet_routing.OptimizeToursRequest.pb(fleet_routing.OptimizeToursRequest()) + 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 = fleet_routing.OptimizeToursResponse.to_json(fleet_routing.OptimizeToursResponse()) + + request = fleet_routing.OptimizeToursRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = fleet_routing.OptimizeToursResponse() + + client.optimize_tours(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_optimize_tours_rest_bad_request(transport: str = 'rest', request_type=fleet_routing.OptimizeToursRequest): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + 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.optimize_tours(request) + + +def test_optimize_tours_rest_error(): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + fleet_routing.BatchOptimizeToursRequest, + dict, +]) +def test_batch_optimize_tours_rest(request_type): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + 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 = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_optimize_tours(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_optimize_tours_rest_required_fields(request_type=fleet_routing.BatchOptimizeToursRequest): + transport_class = transports.FleetRoutingRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_optimize_tours._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_optimize_tours._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.batch_optimize_tours(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_optimize_tours_rest_unset_required_fields(): + transport = transports.FleetRoutingRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_optimize_tours._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "modelConfigs", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_optimize_tours_rest_interceptors(null_interceptor): + transport = transports.FleetRoutingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FleetRoutingRestInterceptor(), + ) + client = FleetRoutingClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.FleetRoutingRestInterceptor, "post_batch_optimize_tours") as post, \ + mock.patch.object(transports.FleetRoutingRestInterceptor, "pre_batch_optimize_tours") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = fleet_routing.BatchOptimizeToursRequest.pb(fleet_routing.BatchOptimizeToursRequest()) + 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 = json_format.MessageToJson(operations_pb2.Operation()) + + request = fleet_routing.BatchOptimizeToursRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_optimize_tours(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_optimize_tours_rest_bad_request(transport: str = 'rest', request_type=fleet_routing.BatchOptimizeToursRequest): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + 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.batch_optimize_tours(request) + + +def test_batch_optimize_tours_rest_error(): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FleetRoutingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FleetRoutingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FleetRoutingClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.FleetRoutingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = FleetRoutingClient( + 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 = FleetRoutingClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FleetRoutingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FleetRoutingClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FleetRoutingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FleetRoutingClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FleetRoutingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FleetRoutingGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.FleetRoutingGrpcTransport, + transports.FleetRoutingGrpcAsyncIOTransport, + transports.FleetRoutingRestTransport, +]) +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 = FleetRoutingClient.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 = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.FleetRoutingGrpcTransport, + ) + +def test_fleet_routing_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FleetRoutingTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_fleet_routing_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.optimization_v1.services.fleet_routing.transports.FleetRoutingTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.FleetRoutingTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'optimize_tours', + 'batch_optimize_tours', + 'get_operation', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_fleet_routing_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.optimization_v1.services.fleet_routing.transports.FleetRoutingTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FleetRoutingTransport( + 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', +), + quota_project_id="octopus", + ) + + +def test_fleet_routing_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.optimization_v1.services.fleet_routing.transports.FleetRoutingTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FleetRoutingTransport() + adc.assert_called_once() + + +def test_fleet_routing_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) + FleetRoutingClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FleetRoutingGrpcTransport, + transports.FleetRoutingGrpcAsyncIOTransport, + ], +) +def test_fleet_routing_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',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FleetRoutingGrpcTransport, + transports.FleetRoutingGrpcAsyncIOTransport, + transports.FleetRoutingRestTransport, + ], +) +def test_fleet_routing_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.FleetRoutingGrpcTransport, grpc_helpers), + (transports.FleetRoutingGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_fleet_routing_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( + "cloudoptimization.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="cloudoptimization.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.FleetRoutingGrpcTransport, transports.FleetRoutingGrpcAsyncIOTransport]) +def test_fleet_routing_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_fleet_routing_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.FleetRoutingRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_fleet_routing_rest_lro_client(): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_fleet_routing_host_no_port(transport_name): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudoptimization.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudoptimization.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudoptimization.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_fleet_routing_host_with_port(transport_name): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudoptimization.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudoptimization.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudoptimization.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_fleet_routing_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = FleetRoutingClient( + credentials=creds1, + transport=transport_name, + ) + client2 = FleetRoutingClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.optimize_tours._session + session2 = client2.transport.optimize_tours._session + assert session1 != session2 + session1 = client1.transport.batch_optimize_tours._session + session2 = client2.transport.batch_optimize_tours._session + assert session1 != session2 +def test_fleet_routing_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FleetRoutingGrpcTransport( + 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_fleet_routing_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FleetRoutingGrpcAsyncIOTransport( + 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.FleetRoutingGrpcTransport, transports.FleetRoutingGrpcAsyncIOTransport]) +def test_fleet_routing_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.FleetRoutingGrpcTransport, transports.FleetRoutingGrpcAsyncIOTransport]) +def test_fleet_routing_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_fleet_routing_grpc_lro_client(): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_fleet_routing_grpc_lro_async_client(): + client = FleetRoutingAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = FleetRoutingClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = FleetRoutingClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FleetRoutingClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = FleetRoutingClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = FleetRoutingClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FleetRoutingClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = FleetRoutingClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = FleetRoutingClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FleetRoutingClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = FleetRoutingClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = FleetRoutingClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FleetRoutingClient.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 = FleetRoutingClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = FleetRoutingClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FleetRoutingClient.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.FleetRoutingTransport, '_prep_wrapped_messages') as prep: + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.FleetRoutingTransport, '_prep_wrapped_messages') as prep: + transport_class = FleetRoutingClient.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 = FleetRoutingAsyncClient( + 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_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) + + # 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.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/operations/sample2'} + 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 = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation(transport: str = "grpc"): + client = FleetRoutingClient( + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = FleetRoutingAsyncClient( + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = FleetRoutingClient( + 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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = FleetRoutingAsyncClient( + 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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = FleetRoutingAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = FleetRoutingClient( + 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 = FleetRoutingClient( + 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", [ + (FleetRoutingClient, transports.FleetRoutingGrpcTransport), + (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport), +]) +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 53b6817ea237d7d3d875de7e176200ccaf04b4ff Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 8 Feb 2023 22:22:14 +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 --- .../cloud/optimization_v1/gapic_metadata.json | 15 + .../services/fleet_routing/client.py | 2 + .../fleet_routing/transports/__init__.py | 5 + .../services/fleet_routing/transports/rest.py | 307 +- 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 - .../v1/docs/optimization_v1/fleet_routing.rst | 6 - .../v1/docs/optimization_v1/services.rst | 6 - .../v1/docs/optimization_v1/types.rst | 6 - .../v1/google/cloud/optimization/__init__.py | 83 - .../cloud/optimization/gapic_version.py | 16 - .../v1/google/cloud/optimization/py.typed | 2 - .../google/cloud/optimization_v1/__init__.py | 84 - .../cloud/optimization_v1/gapic_metadata.json | 58 - .../cloud/optimization_v1/gapic_version.py | 16 - .../v1/google/cloud/optimization_v1/py.typed | 2 - .../optimization_v1/services/__init__.py | 15 - .../services/fleet_routing/__init__.py | 22 - .../services/fleet_routing/async_client.py | 500 -- .../services/fleet_routing/client.py | 687 --- .../fleet_routing/transports/__init__.py | 38 - .../services/fleet_routing/transports/base.py | 191 - .../services/fleet_routing/transports/grpc.py | 375 -- .../fleet_routing/transports/grpc_asyncio.py | 374 -- .../cloud/optimization_v1/types/__init__.py | 78 - .../optimization_v1/types/async_model.py | 201 - .../optimization_v1/types/fleet_routing.py | 4334 ----------------- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 184 - ...leet_routing_batch_optimize_tours_async.py | 61 - ...fleet_routing_batch_optimize_tours_sync.py | 61 - ...ated_fleet_routing_optimize_tours_async.py | 52 - ...rated_fleet_routing_optimize_tours_sync.py | 52 - ...metadata_google.cloud.optimization.v1.json | 321 -- .../scripts/fixup_optimization_v1_keywords.py | 177 - 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/optimization_v1/__init__.py | 16 - .../optimization_v1/test_fleet_routing.py | 2104 -------- .../optimization_v1/test_fleet_routing.py | 590 ++- 52 files changed, 785 insertions(+), 10916 deletions(-) rename {owl-bot-staging/v1/google => google}/cloud/optimization_v1/services/fleet_routing/transports/rest.py (72%) 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/optimization_v1/fleet_routing.rst delete mode 100644 owl-bot-staging/v1/docs/optimization_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/optimization_v1/types.rst delete mode 100644 owl-bot-staging/v1/google/cloud/optimization/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/types/async_model.py delete mode 100644 owl-bot-staging/v1/google/cloud/optimization_v1/types/fleet_routing.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/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.optimization.v1.json delete mode 100644 owl-bot-staging/v1/scripts/fixup_optimization_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/optimization_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/optimization_v1/test_fleet_routing.py diff --git a/google/cloud/optimization_v1/gapic_metadata.json b/google/cloud/optimization_v1/gapic_metadata.json index 2c7b228..c9c5016 100644 --- a/google/cloud/optimization_v1/gapic_metadata.json +++ b/google/cloud/optimization_v1/gapic_metadata.json @@ -36,6 +36,21 @@ ] } } + }, + "rest": { + "libraryClient": "FleetRoutingClient", + "rpcs": { + "BatchOptimizeTours": { + "methods": [ + "batch_optimize_tours" + ] + }, + "OptimizeTours": { + "methods": [ + "optimize_tours" + ] + } + } } } } diff --git a/google/cloud/optimization_v1/services/fleet_routing/client.py b/google/cloud/optimization_v1/services/fleet_routing/client.py index c25a91c..934defa 100644 --- a/google/cloud/optimization_v1/services/fleet_routing/client.py +++ b/google/cloud/optimization_v1/services/fleet_routing/client.py @@ -54,6 +54,7 @@ from .transports.base import FleetRoutingTransport, DEFAULT_CLIENT_INFO from .transports.grpc import FleetRoutingGrpcTransport from .transports.grpc_asyncio import FleetRoutingGrpcAsyncIOTransport +from .transports.rest import FleetRoutingRestTransport class FleetRoutingClientMeta(type): @@ -67,6 +68,7 @@ class FleetRoutingClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[FleetRoutingTransport]] _transport_registry["grpc"] = FleetRoutingGrpcTransport _transport_registry["grpc_asyncio"] = FleetRoutingGrpcAsyncIOTransport + _transport_registry["rest"] = FleetRoutingRestTransport def get_transport_class( cls, diff --git a/google/cloud/optimization_v1/services/fleet_routing/transports/__init__.py b/google/cloud/optimization_v1/services/fleet_routing/transports/__init__.py index 9e17254..69798ab 100644 --- a/google/cloud/optimization_v1/services/fleet_routing/transports/__init__.py +++ b/google/cloud/optimization_v1/services/fleet_routing/transports/__init__.py @@ -19,15 +19,20 @@ from .base import FleetRoutingTransport from .grpc import FleetRoutingGrpcTransport from .grpc_asyncio import FleetRoutingGrpcAsyncIOTransport +from .rest import FleetRoutingRestTransport +from .rest import FleetRoutingRestInterceptor # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[FleetRoutingTransport]] _transport_registry["grpc"] = FleetRoutingGrpcTransport _transport_registry["grpc_asyncio"] = FleetRoutingGrpcAsyncIOTransport +_transport_registry["rest"] = FleetRoutingRestTransport __all__ = ( "FleetRoutingTransport", "FleetRoutingGrpcTransport", "FleetRoutingGrpcAsyncIOTransport", + "FleetRoutingRestTransport", + "FleetRoutingRestInterceptor", ) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/rest.py b/google/cloud/optimization_v1/services/fleet_routing/transports/rest.py similarity index 72% rename from owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/rest.py rename to google/cloud/optimization_v1/services/fleet_routing/transports/rest.py index d4cd012..3753096 100644 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/rest.py +++ b/google/cloud/optimization_v1/services/fleet_routing/transports/rest.py @@ -90,7 +90,12 @@ def post_optimize_tours(self, response): """ - def pre_batch_optimize_tours(self, request: fleet_routing.BatchOptimizeToursRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[fleet_routing.BatchOptimizeToursRequest, Sequence[Tuple[str, str]]]: + + def pre_batch_optimize_tours( + self, + request: fleet_routing.BatchOptimizeToursRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[fleet_routing.BatchOptimizeToursRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for batch_optimize_tours Override in a subclass to manipulate the request or metadata @@ -98,7 +103,9 @@ def pre_batch_optimize_tours(self, request: fleet_routing.BatchOptimizeToursRequ """ return request, metadata - def post_batch_optimize_tours(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_batch_optimize_tours( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for batch_optimize_tours Override in a subclass to manipulate the response @@ -106,7 +113,12 @@ def post_batch_optimize_tours(self, response: operations_pb2.Operation) -> opera it is returned to user code. """ return response - def pre_optimize_tours(self, request: fleet_routing.OptimizeToursRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[fleet_routing.OptimizeToursRequest, Sequence[Tuple[str, str]]]: + + def pre_optimize_tours( + self, + request: fleet_routing.OptimizeToursRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[fleet_routing.OptimizeToursRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for optimize_tours Override in a subclass to manipulate the request or metadata @@ -114,7 +126,9 @@ def pre_optimize_tours(self, request: fleet_routing.OptimizeToursRequest, metada """ return request, metadata - def post_optimize_tours(self, response: fleet_routing.OptimizeToursResponse) -> fleet_routing.OptimizeToursResponse: + def post_optimize_tours( + self, response: fleet_routing.OptimizeToursResponse + ) -> fleet_routing.OptimizeToursResponse: """Post-rpc interceptor for optimize_tours Override in a subclass to manipulate the response @@ -123,7 +137,11 @@ def post_optimize_tours(self, response: fleet_routing.OptimizeToursResponse) -> """ return response - def pre_get_operation(self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]]) -> operations_pb2.Operation: + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> operations_pb2.Operation: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -131,7 +149,9 @@ def pre_get_operation(self, request: operations_pb2.GetOperationRequest, metadat """ return request, metadata - def post_get_operation(self, response: operations_pb2.GetOperationRequest) -> operations_pb2.Operation: + def post_get_operation( + self, response: operations_pb2.GetOperationRequest + ) -> operations_pb2.Operation: """Post-rpc interceptor for get_operation Override in a subclass to manipulate the response @@ -183,20 +203,21 @@ class FleetRoutingRestTransport(FleetRoutingTransport): """ - def __init__(self, *, - host: str = 'cloudoptimization.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[FleetRoutingRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "cloudoptimization.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[FleetRoutingRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -235,7 +256,9 @@ def __init__(self, *, # 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 + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -246,10 +269,11 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) + self._credentials, default_host=self.DEFAULT_HOST + ) self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) @@ -266,27 +290,30 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Only create a new client if we do not already have one. if self._operations_client is None: http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ + "google.longrunning.Operations.GetOperation": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', + "method": "get", + "uri": "/v1/{name=projects/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, ], } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) # Return the client from cache. return self._operations_client @@ -295,19 +322,24 @@ class _BatchOptimizeTours(FleetRoutingRestStub): def __hash__(self): return hash("BatchOptimizeTours") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: fleet_routing.BatchOptimizeToursRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: fleet_routing.BatchOptimizeToursRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: r"""Call the batch optimize tours method over HTTP. Args: @@ -334,51 +366,56 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}:batchOptimizeTours', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}:batchOptimizeTours', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}:batchOptimizeTours", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{parent=projects/*}:batchOptimizeTours", + "body": "*", + }, ] - request, metadata = self._interceptor.pre_batch_optimize_tours(request, metadata) + request, metadata = self._interceptor.pre_batch_optimize_tours( + request, metadata + ) pb_request = fleet_routing.BatchOptimizeToursRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], + transcoded_request["body"], including_default_value_fields=False, - use_integers_for_enums=True + use_integers_for_enums=True, ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + 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 = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + 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. @@ -395,19 +432,24 @@ class _OptimizeTours(FleetRoutingRestStub): def __hash__(self): return hash("OptimizeTours") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: fleet_routing.OptimizeToursRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> fleet_routing.OptimizeToursResponse: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: fleet_routing.OptimizeToursRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fleet_routing.OptimizeToursResponse: r"""Call the optimize tours method over HTTP. Args: @@ -433,16 +475,17 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}:optimizeTours', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}:optimizeTours', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}:optimizeTours", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{parent=projects/*}:optimizeTours", + "body": "*", + }, ] request, metadata = self._interceptor.pre_optimize_tours(request, metadata) pb_request = fleet_routing.OptimizeToursRequest.pb(request) @@ -451,33 +494,35 @@ def __call__(self, # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], + transcoded_request["body"], including_default_value_fields=False, - use_integers_for_enums=True + use_integers_for_enums=True, ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + 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 = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + 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. @@ -493,32 +538,36 @@ def __call__(self, return resp @property - def batch_optimize_tours(self) -> Callable[ - [fleet_routing.BatchOptimizeToursRequest], - operations_pb2.Operation]: + def batch_optimize_tours( + self, + ) -> Callable[[fleet_routing.BatchOptimizeToursRequest], operations_pb2.Operation]: # 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._BatchOptimizeTours(self._session, self._host, self._interceptor) # type: ignore + return self._BatchOptimizeTours(self._session, self._host, self._interceptor) # type: ignore @property - def optimize_tours(self) -> Callable[ - [fleet_routing.OptimizeToursRequest], - fleet_routing.OptimizeToursResponse]: + def optimize_tours( + self, + ) -> Callable[ + [fleet_routing.OptimizeToursRequest], fleet_routing.OptimizeToursResponse + ]: # 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._OptimizeTours(self._session, self._host, self._interceptor) # type: ignore + return self._OptimizeTours(self._session, self._host, self._interceptor) # type: ignore @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore class _GetOperation(FleetRoutingRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. @@ -535,30 +584,30 @@ def __call__(self, operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, ] request, metadata = self._interceptor.pre_get_operation(request, metadata) request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), @@ -585,6 +634,4 @@ def close(self): self._session.close() -__all__=( - 'FleetRoutingRestTransport', -) +__all__ = ("FleetRoutingRestTransport",) diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index a52613e..0000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/optimization/__init__.py - google/cloud/optimization/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 12730a7..0000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/optimization *.py -recursive-include google/cloud/optimization_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 9742358..0000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Optimization 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 Optimization 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 da0ad31..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-optimization 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-optimization" -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-optimization-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-optimization.tex", - u"google-cloud-optimization 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-optimization", - u"Google Cloud Optimization 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-optimization", - u"google-cloud-optimization Documentation", - author, - "google-cloud-optimization", - "GAPIC library for Google Cloud Optimization 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 ccbb913..0000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - optimization_v1/services - optimization_v1/types diff --git a/owl-bot-staging/v1/docs/optimization_v1/fleet_routing.rst b/owl-bot-staging/v1/docs/optimization_v1/fleet_routing.rst deleted file mode 100644 index ce97b29..0000000 --- a/owl-bot-staging/v1/docs/optimization_v1/fleet_routing.rst +++ /dev/null @@ -1,6 +0,0 @@ -FleetRouting ------------------------------- - -.. automodule:: google.cloud.optimization_v1.services.fleet_routing - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/optimization_v1/services.rst b/owl-bot-staging/v1/docs/optimization_v1/services.rst deleted file mode 100644 index 2fb17d5..0000000 --- a/owl-bot-staging/v1/docs/optimization_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Optimization v1 API -============================================= -.. toctree:: - :maxdepth: 2 - - fleet_routing diff --git a/owl-bot-staging/v1/docs/optimization_v1/types.rst b/owl-bot-staging/v1/docs/optimization_v1/types.rst deleted file mode 100644 index bc2dcf0..0000000 --- a/owl-bot-staging/v1/docs/optimization_v1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Optimization v1 API -========================================== - -.. automodule:: google.cloud.optimization_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/optimization/__init__.py b/owl-bot-staging/v1/google/cloud/optimization/__init__.py deleted file mode 100644 index f91a3bb..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization/__init__.py +++ /dev/null @@ -1,83 +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.optimization import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.optimization_v1.services.fleet_routing.client import FleetRoutingClient -from google.cloud.optimization_v1.services.fleet_routing.async_client import FleetRoutingAsyncClient - -from google.cloud.optimization_v1.types.async_model import AsyncModelMetadata -from google.cloud.optimization_v1.types.async_model import GcsDestination -from google.cloud.optimization_v1.types.async_model import GcsSource -from google.cloud.optimization_v1.types.async_model import InputConfig -from google.cloud.optimization_v1.types.async_model import OutputConfig -from google.cloud.optimization_v1.types.async_model import DataFormat -from google.cloud.optimization_v1.types.fleet_routing import AggregatedMetrics -from google.cloud.optimization_v1.types.fleet_routing import BatchOptimizeToursRequest -from google.cloud.optimization_v1.types.fleet_routing import BatchOptimizeToursResponse -from google.cloud.optimization_v1.types.fleet_routing import BreakRule -from google.cloud.optimization_v1.types.fleet_routing import CapacityQuantity -from google.cloud.optimization_v1.types.fleet_routing import CapacityQuantityInterval -from google.cloud.optimization_v1.types.fleet_routing import DistanceLimit -from google.cloud.optimization_v1.types.fleet_routing import InjectedSolutionConstraint -from google.cloud.optimization_v1.types.fleet_routing import Location -from google.cloud.optimization_v1.types.fleet_routing import OptimizeToursRequest -from google.cloud.optimization_v1.types.fleet_routing import OptimizeToursResponse -from google.cloud.optimization_v1.types.fleet_routing import OptimizeToursValidationError -from google.cloud.optimization_v1.types.fleet_routing import Shipment -from google.cloud.optimization_v1.types.fleet_routing import ShipmentModel -from google.cloud.optimization_v1.types.fleet_routing import ShipmentRoute -from google.cloud.optimization_v1.types.fleet_routing import ShipmentTypeIncompatibility -from google.cloud.optimization_v1.types.fleet_routing import ShipmentTypeRequirement -from google.cloud.optimization_v1.types.fleet_routing import SkippedShipment -from google.cloud.optimization_v1.types.fleet_routing import TimeWindow -from google.cloud.optimization_v1.types.fleet_routing import TransitionAttributes -from google.cloud.optimization_v1.types.fleet_routing import Vehicle -from google.cloud.optimization_v1.types.fleet_routing import Waypoint - -__all__ = ('FleetRoutingClient', - 'FleetRoutingAsyncClient', - 'AsyncModelMetadata', - 'GcsDestination', - 'GcsSource', - 'InputConfig', - 'OutputConfig', - 'DataFormat', - 'AggregatedMetrics', - 'BatchOptimizeToursRequest', - 'BatchOptimizeToursResponse', - 'BreakRule', - 'CapacityQuantity', - 'CapacityQuantityInterval', - 'DistanceLimit', - 'InjectedSolutionConstraint', - 'Location', - 'OptimizeToursRequest', - 'OptimizeToursResponse', - 'OptimizeToursValidationError', - 'Shipment', - 'ShipmentModel', - 'ShipmentRoute', - 'ShipmentTypeIncompatibility', - 'ShipmentTypeRequirement', - 'SkippedShipment', - 'TimeWindow', - 'TransitionAttributes', - 'Vehicle', - 'Waypoint', -) diff --git a/owl-bot-staging/v1/google/cloud/optimization/gapic_version.py b/owl-bot-staging/v1/google/cloud/optimization/gapic_version.py deleted file mode 100644 index 405b1ce..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization/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/optimization/py.typed b/owl-bot-staging/v1/google/cloud/optimization/py.typed deleted file mode 100644 index 5157828..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-optimization package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/__init__.py b/owl-bot-staging/v1/google/cloud/optimization_v1/__init__.py deleted file mode 100644 index a8ee01e..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/__init__.py +++ /dev/null @@ -1,84 +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.optimization_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.fleet_routing import FleetRoutingClient -from .services.fleet_routing import FleetRoutingAsyncClient - -from .types.async_model import AsyncModelMetadata -from .types.async_model import GcsDestination -from .types.async_model import GcsSource -from .types.async_model import InputConfig -from .types.async_model import OutputConfig -from .types.async_model import DataFormat -from .types.fleet_routing import AggregatedMetrics -from .types.fleet_routing import BatchOptimizeToursRequest -from .types.fleet_routing import BatchOptimizeToursResponse -from .types.fleet_routing import BreakRule -from .types.fleet_routing import CapacityQuantity -from .types.fleet_routing import CapacityQuantityInterval -from .types.fleet_routing import DistanceLimit -from .types.fleet_routing import InjectedSolutionConstraint -from .types.fleet_routing import Location -from .types.fleet_routing import OptimizeToursRequest -from .types.fleet_routing import OptimizeToursResponse -from .types.fleet_routing import OptimizeToursValidationError -from .types.fleet_routing import Shipment -from .types.fleet_routing import ShipmentModel -from .types.fleet_routing import ShipmentRoute -from .types.fleet_routing import ShipmentTypeIncompatibility -from .types.fleet_routing import ShipmentTypeRequirement -from .types.fleet_routing import SkippedShipment -from .types.fleet_routing import TimeWindow -from .types.fleet_routing import TransitionAttributes -from .types.fleet_routing import Vehicle -from .types.fleet_routing import Waypoint - -__all__ = ( - 'FleetRoutingAsyncClient', -'AggregatedMetrics', -'AsyncModelMetadata', -'BatchOptimizeToursRequest', -'BatchOptimizeToursResponse', -'BreakRule', -'CapacityQuantity', -'CapacityQuantityInterval', -'DataFormat', -'DistanceLimit', -'FleetRoutingClient', -'GcsDestination', -'GcsSource', -'InjectedSolutionConstraint', -'InputConfig', -'Location', -'OptimizeToursRequest', -'OptimizeToursResponse', -'OptimizeToursValidationError', -'OutputConfig', -'Shipment', -'ShipmentModel', -'ShipmentRoute', -'ShipmentTypeIncompatibility', -'ShipmentTypeRequirement', -'SkippedShipment', -'TimeWindow', -'TransitionAttributes', -'Vehicle', -'Waypoint', -) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/optimization_v1/gapic_metadata.json deleted file mode 100644 index c9c5016..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/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.optimization_v1", - "protoPackage": "google.cloud.optimization.v1", - "schema": "1.0", - "services": { - "FleetRouting": { - "clients": { - "grpc": { - "libraryClient": "FleetRoutingClient", - "rpcs": { - "BatchOptimizeTours": { - "methods": [ - "batch_optimize_tours" - ] - }, - "OptimizeTours": { - "methods": [ - "optimize_tours" - ] - } - } - }, - "grpc-async": { - "libraryClient": "FleetRoutingAsyncClient", - "rpcs": { - "BatchOptimizeTours": { - "methods": [ - "batch_optimize_tours" - ] - }, - "OptimizeTours": { - "methods": [ - "optimize_tours" - ] - } - } - }, - "rest": { - "libraryClient": "FleetRoutingClient", - "rpcs": { - "BatchOptimizeTours": { - "methods": [ - "batch_optimize_tours" - ] - }, - "OptimizeTours": { - "methods": [ - "optimize_tours" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/optimization_v1/gapic_version.py deleted file mode 100644 index 405b1ce..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_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/optimization_v1/py.typed b/owl-bot-staging/v1/google/cloud/optimization_v1/py.typed deleted file mode 100644 index 5157828..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-optimization package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/__init__.py deleted file mode 100644 index e8e1c38..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_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/optimization_v1/services/fleet_routing/__init__.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/__init__.py deleted file mode 100644 index eee0bb0..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/__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 FleetRoutingClient -from .async_client import FleetRoutingAsyncClient - -__all__ = ( - 'FleetRoutingClient', - 'FleetRoutingAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/async_client.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/async_client.py deleted file mode 100644 index 1370625..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/async_client.py +++ /dev/null @@ -1,500 +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.optimization_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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.optimization_v1.types import async_model -from google.cloud.optimization_v1.types import fleet_routing -from google.longrunning import operations_pb2 -from .transports.base import FleetRoutingTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import FleetRoutingGrpcAsyncIOTransport -from .client import FleetRoutingClient - - -class FleetRoutingAsyncClient: - """A service for optimizing vehicle tours. - - Validity of certain types of fields: - - - ``google.protobuf.Timestamp`` - - - Times are in Unix time: seconds since - 1970-01-01T00:00:00+00:00. - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.protobuf.Duration`` - - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.type.LatLng`` - - - latitude must be in [-90.0, 90.0]. - - longitude must be in [-180.0, 180.0]. - - at least one of latitude and longitude must be non-zero. - """ - - _client: FleetRoutingClient - - DEFAULT_ENDPOINT = FleetRoutingClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = FleetRoutingClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(FleetRoutingClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(FleetRoutingClient.parse_common_billing_account_path) - common_folder_path = staticmethod(FleetRoutingClient.common_folder_path) - parse_common_folder_path = staticmethod(FleetRoutingClient.parse_common_folder_path) - common_organization_path = staticmethod(FleetRoutingClient.common_organization_path) - parse_common_organization_path = staticmethod(FleetRoutingClient.parse_common_organization_path) - common_project_path = staticmethod(FleetRoutingClient.common_project_path) - parse_common_project_path = staticmethod(FleetRoutingClient.parse_common_project_path) - common_location_path = staticmethod(FleetRoutingClient.common_location_path) - parse_common_location_path = staticmethod(FleetRoutingClient.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: - FleetRoutingAsyncClient: The constructed client. - """ - return FleetRoutingClient.from_service_account_info.__func__(FleetRoutingAsyncClient, 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: - FleetRoutingAsyncClient: The constructed client. - """ - return FleetRoutingClient.from_service_account_file.__func__(FleetRoutingAsyncClient, 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 FleetRoutingClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> FleetRoutingTransport: - """Returns the transport used by the client instance. - - Returns: - FleetRoutingTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(FleetRoutingClient).get_transport_class, type(FleetRoutingClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, FleetRoutingTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the fleet routing 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, ~.FleetRoutingTransport]): 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 = FleetRoutingClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def optimize_tours(self, - request: Optional[Union[fleet_routing.OptimizeToursRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> fleet_routing.OptimizeToursResponse: - r"""Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` - and returns an ``OptimizeToursResponse`` containing - ``ShipmentRoute``\ s, which are a set of routes to be performed - by vehicles minimizing the overall cost. - - A ``ShipmentModel`` model consists mainly of ``Shipment``\ s - that need to be carried out and ``Vehicle``\ s that can be used - to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s - assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, - they assign a series of ``Visit``\ s to each vehicle, where a - ``Visit`` corresponds to a ``VisitRequest``, which is a pickup - or delivery for a ``Shipment``. - - The goal is to provide an assignment of ``ShipmentRoute``\ s to - ``Vehicle``\ s that minimizes the total cost where cost has many - components defined in the ``ShipmentModel``. - - .. 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 optimization_v1 - - async def sample_optimize_tours(): - # Create a client - client = optimization_v1.FleetRoutingAsyncClient() - - # Initialize request argument(s) - request = optimization_v1.OptimizeToursRequest( - parent="parent_value", - ) - - # Make the request - response = await client.optimize_tours(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.optimization_v1.types.OptimizeToursRequest, dict]]): - The request object. Request to be given to a tour - optimization solver which defines the shipment model to - solve as well as optimization parameters. - 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.optimization_v1.types.OptimizeToursResponse: - Response after solving a tour - optimization problem containing the - routes followed by each vehicle, the - shipments which have been skipped and - the overall cost of the solution. - - """ - # Create or coerce a protobuf request object. - request = fleet_routing.OptimizeToursRequest(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.optimize_tours, - default_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=3600.0, - ), - default_timeout=3600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_optimize_tours(self, - request: Optional[Union[fleet_routing.BatchOptimizeToursRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Optimizes vehicle tours for one or more ``OptimizeToursRequest`` - messages as a batch. - - This method is a Long Running Operation (LRO). The inputs for - optimization (``OptimizeToursRequest`` messages) and outputs - (``OptimizeToursResponse`` messages) are read/written from/to - Cloud Storage in user-specified format. Like the - ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains - a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` - containing ``ShipmentRoute``\ s, which are a set of routes to be - performed by vehicles minimizing the overall cost. - - .. 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 optimization_v1 - - async def sample_batch_optimize_tours(): - # Create a client - client = optimization_v1.FleetRoutingAsyncClient() - - # Initialize request argument(s) - model_configs = optimization_v1.AsyncModelConfig() - model_configs.input_config.gcs_source.uri = "uri_value" - model_configs.output_config.gcs_destination.uri = "uri_value" - - request = optimization_v1.BatchOptimizeToursRequest( - parent="parent_value", - model_configs=model_configs, - ) - - # Make the request - operation = client.batch_optimize_tours(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.optimization_v1.types.BatchOptimizeToursRequest, dict]]): - The request object. Request to batch optimize tours as - an asynchronous operation. Each input file should - contain one `OptimizeToursRequest`, and each output file - will contain one `OptimizeToursResponse`. The request - contains information to read/write and parse the files. - All the input and output files should be under the same - project. - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.optimization_v1.types.BatchOptimizeToursResponse` Response to a BatchOptimizeToursRequest. This is returned in - the LRO Operation after the operation is complete. - - """ - # Create or coerce a protobuf request object. - request = fleet_routing.BatchOptimizeToursRequest(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.batch_optimize_tours, - default_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - fleet_routing.BatchOptimizeToursResponse, - metadata_type=async_model.AsyncModelMetadata, - ) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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( - (("name", request.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__ = ( - "FleetRoutingAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/client.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/client.py deleted file mode 100644 index bf608b1..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/client.py +++ /dev/null @@ -1,687 +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.optimization_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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.optimization_v1.types import async_model -from google.cloud.optimization_v1.types import fleet_routing -from google.longrunning import operations_pb2 -from .transports.base import FleetRoutingTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import FleetRoutingGrpcTransport -from .transports.grpc_asyncio import FleetRoutingGrpcAsyncIOTransport -from .transports.rest import FleetRoutingRestTransport - - -class FleetRoutingClientMeta(type): - """Metaclass for the FleetRouting 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[FleetRoutingTransport]] - _transport_registry["grpc"] = FleetRoutingGrpcTransport - _transport_registry["grpc_asyncio"] = FleetRoutingGrpcAsyncIOTransport - _transport_registry["rest"] = FleetRoutingRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[FleetRoutingTransport]: - """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 FleetRoutingClient(metaclass=FleetRoutingClientMeta): - """A service for optimizing vehicle tours. - - Validity of certain types of fields: - - - ``google.protobuf.Timestamp`` - - - Times are in Unix time: seconds since - 1970-01-01T00:00:00+00:00. - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.protobuf.Duration`` - - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.type.LatLng`` - - - latitude must be in [-90.0, 90.0]. - - longitude must be in [-180.0, 180.0]. - - at least one of latitude and longitude must be non-zero. - """ - - @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 = "cloudoptimization.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: - FleetRoutingClient: 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: - FleetRoutingClient: 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) -> FleetRoutingTransport: - """Returns the transport used by the client instance. - - Returns: - FleetRoutingTransport: 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, FleetRoutingTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the fleet routing 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, FleetRoutingTransport]): 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, FleetRoutingTransport): - # transport is a FleetRoutingTransport 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 optimize_tours(self, - request: Optional[Union[fleet_routing.OptimizeToursRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> fleet_routing.OptimizeToursResponse: - r"""Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` - and returns an ``OptimizeToursResponse`` containing - ``ShipmentRoute``\ s, which are a set of routes to be performed - by vehicles minimizing the overall cost. - - A ``ShipmentModel`` model consists mainly of ``Shipment``\ s - that need to be carried out and ``Vehicle``\ s that can be used - to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s - assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, - they assign a series of ``Visit``\ s to each vehicle, where a - ``Visit`` corresponds to a ``VisitRequest``, which is a pickup - or delivery for a ``Shipment``. - - The goal is to provide an assignment of ``ShipmentRoute``\ s to - ``Vehicle``\ s that minimizes the total cost where cost has many - components defined in the ``ShipmentModel``. - - .. 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 optimization_v1 - - def sample_optimize_tours(): - # Create a client - client = optimization_v1.FleetRoutingClient() - - # Initialize request argument(s) - request = optimization_v1.OptimizeToursRequest( - parent="parent_value", - ) - - # Make the request - response = client.optimize_tours(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.optimization_v1.types.OptimizeToursRequest, dict]): - The request object. Request to be given to a tour - optimization solver which defines the shipment model to - solve as well as optimization parameters. - 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.optimization_v1.types.OptimizeToursResponse: - Response after solving a tour - optimization problem containing the - routes followed by each vehicle, the - shipments which have been skipped and - the overall cost of the solution. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a fleet_routing.OptimizeToursRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, fleet_routing.OptimizeToursRequest): - request = fleet_routing.OptimizeToursRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.optimize_tours] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_optimize_tours(self, - request: Optional[Union[fleet_routing.BatchOptimizeToursRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Optimizes vehicle tours for one or more ``OptimizeToursRequest`` - messages as a batch. - - This method is a Long Running Operation (LRO). The inputs for - optimization (``OptimizeToursRequest`` messages) and outputs - (``OptimizeToursResponse`` messages) are read/written from/to - Cloud Storage in user-specified format. Like the - ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains - a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` - containing ``ShipmentRoute``\ s, which are a set of routes to be - performed by vehicles minimizing the overall cost. - - .. 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 optimization_v1 - - def sample_batch_optimize_tours(): - # Create a client - client = optimization_v1.FleetRoutingClient() - - # Initialize request argument(s) - model_configs = optimization_v1.AsyncModelConfig() - model_configs.input_config.gcs_source.uri = "uri_value" - model_configs.output_config.gcs_destination.uri = "uri_value" - - request = optimization_v1.BatchOptimizeToursRequest( - parent="parent_value", - model_configs=model_configs, - ) - - # Make the request - operation = client.batch_optimize_tours(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.optimization_v1.types.BatchOptimizeToursRequest, dict]): - The request object. Request to batch optimize tours as - an asynchronous operation. Each input file should - contain one `OptimizeToursRequest`, and each output file - will contain one `OptimizeToursResponse`. The request - contains information to read/write and parse the files. - All the input and output files should be under the same - project. - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.optimization_v1.types.BatchOptimizeToursResponse` Response to a BatchOptimizeToursRequest. This is returned in - the LRO Operation after the operation is complete. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a fleet_routing.BatchOptimizeToursRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, fleet_routing.BatchOptimizeToursRequest): - request = fleet_routing.BatchOptimizeToursRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_optimize_tours] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - fleet_routing.BatchOptimizeToursResponse, - metadata_type=async_model.AsyncModelMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "FleetRoutingClient": - 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() - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "FleetRoutingClient", -) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/__init__.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/__init__.py deleted file mode 100644 index 6bdd233..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/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 FleetRoutingTransport -from .grpc import FleetRoutingGrpcTransport -from .grpc_asyncio import FleetRoutingGrpcAsyncIOTransport -from .rest import FleetRoutingRestTransport -from .rest import FleetRoutingRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[FleetRoutingTransport]] -_transport_registry['grpc'] = FleetRoutingGrpcTransport -_transport_registry['grpc_asyncio'] = FleetRoutingGrpcAsyncIOTransport -_transport_registry['rest'] = FleetRoutingRestTransport - -__all__ = ( - 'FleetRoutingTransport', - 'FleetRoutingGrpcTransport', - 'FleetRoutingGrpcAsyncIOTransport', - 'FleetRoutingRestTransport', - 'FleetRoutingRestInterceptor', -) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/base.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/base.py deleted file mode 100644 index b8d3bbf..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/base.py +++ /dev/null @@ -1,191 +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.optimization_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.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.optimization_v1.types import fleet_routing -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class FleetRoutingTransport(abc.ABC): - """Abstract transport class for FleetRouting.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'cloudoptimization.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.optimize_tours: gapic_v1.method.wrap_method( - self.optimize_tours, - default_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=3600.0, - ), - default_timeout=3600.0, - client_info=client_info, - ), - self.batch_optimize_tours: gapic_v1.method.wrap_method( - self.batch_optimize_tours, - default_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.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 operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def optimize_tours(self) -> Callable[ - [fleet_routing.OptimizeToursRequest], - Union[ - fleet_routing.OptimizeToursResponse, - Awaitable[fleet_routing.OptimizeToursResponse] - ]]: - raise NotImplementedError() - - @property - def batch_optimize_tours(self) -> Callable[ - [fleet_routing.BatchOptimizeToursRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'FleetRoutingTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc.py deleted file mode 100644 index ffae111..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc.py +++ /dev/null @@ -1,375 +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 operations_v1 -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.optimization_v1.types import fleet_routing -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import FleetRoutingTransport, DEFAULT_CLIENT_INFO - - -class FleetRoutingGrpcTransport(FleetRoutingTransport): - """gRPC backend transport for FleetRouting. - - A service for optimizing vehicle tours. - - Validity of certain types of fields: - - - ``google.protobuf.Timestamp`` - - - Times are in Unix time: seconds since - 1970-01-01T00:00:00+00:00. - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.protobuf.Duration`` - - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.type.LatLng`` - - - latitude must be in [-90.0, 90.0]. - - longitude must be in [-180.0, 180.0]. - - at least one of latitude and longitude must be non-zero. - - 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 = 'cloudoptimization.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] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - 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 = 'cloudoptimization.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 operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def optimize_tours(self) -> Callable[ - [fleet_routing.OptimizeToursRequest], - fleet_routing.OptimizeToursResponse]: - r"""Return a callable for the optimize tours method over gRPC. - - Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` - and returns an ``OptimizeToursResponse`` containing - ``ShipmentRoute``\ s, which are a set of routes to be performed - by vehicles minimizing the overall cost. - - A ``ShipmentModel`` model consists mainly of ``Shipment``\ s - that need to be carried out and ``Vehicle``\ s that can be used - to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s - assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, - they assign a series of ``Visit``\ s to each vehicle, where a - ``Visit`` corresponds to a ``VisitRequest``, which is a pickup - or delivery for a ``Shipment``. - - The goal is to provide an assignment of ``ShipmentRoute``\ s to - ``Vehicle``\ s that minimizes the total cost where cost has many - components defined in the ``ShipmentModel``. - - Returns: - Callable[[~.OptimizeToursRequest], - ~.OptimizeToursResponse]: - 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 'optimize_tours' not in self._stubs: - self._stubs['optimize_tours'] = self.grpc_channel.unary_unary( - '/google.cloud.optimization.v1.FleetRouting/OptimizeTours', - request_serializer=fleet_routing.OptimizeToursRequest.serialize, - response_deserializer=fleet_routing.OptimizeToursResponse.deserialize, - ) - return self._stubs['optimize_tours'] - - @property - def batch_optimize_tours(self) -> Callable[ - [fleet_routing.BatchOptimizeToursRequest], - operations_pb2.Operation]: - r"""Return a callable for the batch optimize tours method over gRPC. - - Optimizes vehicle tours for one or more ``OptimizeToursRequest`` - messages as a batch. - - This method is a Long Running Operation (LRO). The inputs for - optimization (``OptimizeToursRequest`` messages) and outputs - (``OptimizeToursResponse`` messages) are read/written from/to - Cloud Storage in user-specified format. Like the - ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains - a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` - containing ``ShipmentRoute``\ s, which are a set of routes to be - performed by vehicles minimizing the overall cost. - - Returns: - Callable[[~.BatchOptimizeToursRequest], - ~.Operation]: - 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 'batch_optimize_tours' not in self._stubs: - self._stubs['batch_optimize_tours'] = self.grpc_channel.unary_unary( - '/google.cloud.optimization.v1.FleetRouting/BatchOptimizeTours', - request_serializer=fleet_routing.BatchOptimizeToursRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_optimize_tours'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'FleetRoutingGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc_asyncio.py deleted file mode 100644 index b80a34f..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/services/fleet_routing/transports/grpc_asyncio.py +++ /dev/null @@ -1,374 +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.api_core import operations_v1 -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.optimization_v1.types import fleet_routing -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import FleetRoutingTransport, DEFAULT_CLIENT_INFO -from .grpc import FleetRoutingGrpcTransport - - -class FleetRoutingGrpcAsyncIOTransport(FleetRoutingTransport): - """gRPC AsyncIO backend transport for FleetRouting. - - A service for optimizing vehicle tours. - - Validity of certain types of fields: - - - ``google.protobuf.Timestamp`` - - - Times are in Unix time: seconds since - 1970-01-01T00:00:00+00:00. - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.protobuf.Duration`` - - - seconds must be in [0, 253402300799], i.e. in - [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. - - nanos must be unset or set to 0. - - - ``google.type.LatLng`` - - - latitude must be in [-90.0, 90.0]. - - longitude must be in [-180.0, 180.0]. - - at least one of latitude and longitude must be non-zero. - - 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 = 'cloudoptimization.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 = 'cloudoptimization.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] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def optimize_tours(self) -> Callable[ - [fleet_routing.OptimizeToursRequest], - Awaitable[fleet_routing.OptimizeToursResponse]]: - r"""Return a callable for the optimize tours method over gRPC. - - Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` - and returns an ``OptimizeToursResponse`` containing - ``ShipmentRoute``\ s, which are a set of routes to be performed - by vehicles minimizing the overall cost. - - A ``ShipmentModel`` model consists mainly of ``Shipment``\ s - that need to be carried out and ``Vehicle``\ s that can be used - to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s - assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, - they assign a series of ``Visit``\ s to each vehicle, where a - ``Visit`` corresponds to a ``VisitRequest``, which is a pickup - or delivery for a ``Shipment``. - - The goal is to provide an assignment of ``ShipmentRoute``\ s to - ``Vehicle``\ s that minimizes the total cost where cost has many - components defined in the ``ShipmentModel``. - - Returns: - Callable[[~.OptimizeToursRequest], - Awaitable[~.OptimizeToursResponse]]: - 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 'optimize_tours' not in self._stubs: - self._stubs['optimize_tours'] = self.grpc_channel.unary_unary( - '/google.cloud.optimization.v1.FleetRouting/OptimizeTours', - request_serializer=fleet_routing.OptimizeToursRequest.serialize, - response_deserializer=fleet_routing.OptimizeToursResponse.deserialize, - ) - return self._stubs['optimize_tours'] - - @property - def batch_optimize_tours(self) -> Callable[ - [fleet_routing.BatchOptimizeToursRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch optimize tours method over gRPC. - - Optimizes vehicle tours for one or more ``OptimizeToursRequest`` - messages as a batch. - - This method is a Long Running Operation (LRO). The inputs for - optimization (``OptimizeToursRequest`` messages) and outputs - (``OptimizeToursResponse`` messages) are read/written from/to - Cloud Storage in user-specified format. Like the - ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains - a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` - containing ``ShipmentRoute``\ s, which are a set of routes to be - performed by vehicles minimizing the overall cost. - - Returns: - Callable[[~.BatchOptimizeToursRequest], - Awaitable[~.Operation]]: - 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 'batch_optimize_tours' not in self._stubs: - self._stubs['batch_optimize_tours'] = self.grpc_channel.unary_unary( - '/google.cloud.optimization.v1.FleetRouting/BatchOptimizeTours', - request_serializer=fleet_routing.BatchOptimizeToursRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_optimize_tours'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - -__all__ = ( - 'FleetRoutingGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/optimization_v1/types/__init__.py deleted file mode 100644 index a6cc7b6..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/types/__init__.py +++ /dev/null @@ -1,78 +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 .async_model import ( - AsyncModelMetadata, - GcsDestination, - GcsSource, - InputConfig, - OutputConfig, - DataFormat, -) -from .fleet_routing import ( - AggregatedMetrics, - BatchOptimizeToursRequest, - BatchOptimizeToursResponse, - BreakRule, - CapacityQuantity, - CapacityQuantityInterval, - DistanceLimit, - InjectedSolutionConstraint, - Location, - OptimizeToursRequest, - OptimizeToursResponse, - OptimizeToursValidationError, - Shipment, - ShipmentModel, - ShipmentRoute, - ShipmentTypeIncompatibility, - ShipmentTypeRequirement, - SkippedShipment, - TimeWindow, - TransitionAttributes, - Vehicle, - Waypoint, -) - -__all__ = ( - 'AsyncModelMetadata', - 'GcsDestination', - 'GcsSource', - 'InputConfig', - 'OutputConfig', - 'DataFormat', - 'AggregatedMetrics', - 'BatchOptimizeToursRequest', - 'BatchOptimizeToursResponse', - 'BreakRule', - 'CapacityQuantity', - 'CapacityQuantityInterval', - 'DistanceLimit', - 'InjectedSolutionConstraint', - 'Location', - 'OptimizeToursRequest', - 'OptimizeToursResponse', - 'OptimizeToursValidationError', - 'Shipment', - 'ShipmentModel', - 'ShipmentRoute', - 'ShipmentTypeIncompatibility', - 'ShipmentTypeRequirement', - 'SkippedShipment', - 'TimeWindow', - 'TransitionAttributes', - 'Vehicle', - 'Waypoint', -) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/types/async_model.py b/owl-bot-staging/v1/google/cloud/optimization_v1/types/async_model.py deleted file mode 100644 index 8753a33..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/types/async_model.py +++ /dev/null @@ -1,201 +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 typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.optimization.v1', - manifest={ - 'DataFormat', - 'InputConfig', - 'OutputConfig', - 'GcsSource', - 'GcsDestination', - 'AsyncModelMetadata', - }, -) - - -class DataFormat(proto.Enum): - r"""Data formats for input and output files. - - Values: - DATA_FORMAT_UNSPECIFIED (0): - Default value. - JSON (1): - Input data in json format. - STRING (2): - Input data in string format. - """ - DATA_FORMAT_UNSPECIFIED = 0 - JSON = 1 - STRING = 2 - - -class InputConfig(proto.Message): - r"""The desired input location information. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_source (google.cloud.optimization_v1.types.GcsSource): - The Google Cloud Storage location to read the - input from. This must be a single file. - - This field is a member of `oneof`_ ``source``. - data_format (google.cloud.optimization_v1.types.DataFormat): - The input data format that used to store the - model in Cloud Storage. - """ - - gcs_source: 'GcsSource' = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='GcsSource', - ) - data_format: 'DataFormat' = proto.Field( - proto.ENUM, - number=2, - enum='DataFormat', - ) - - -class OutputConfig(proto.Message): - r"""The desired output location. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_destination (google.cloud.optimization_v1.types.GcsDestination): - The Google Cloud Storage location to write - the output to. - - This field is a member of `oneof`_ ``destination``. - data_format (google.cloud.optimization_v1.types.DataFormat): - The output data format that used to store the - results in Cloud Storage. - """ - - gcs_destination: 'GcsDestination' = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message='GcsDestination', - ) - data_format: 'DataFormat' = proto.Field( - proto.ENUM, - number=2, - enum='DataFormat', - ) - - -class GcsSource(proto.Message): - r"""The Google Cloud Storage location where the input file will - be read from. - - Attributes: - uri (str): - Required. URI of the Google Cloud Storage - location. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GcsDestination(proto.Message): - r"""The Google Cloud Storage location where the output file will - be written to. - - Attributes: - uri (str): - Required. URI of the Google Cloud Storage - location. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AsyncModelMetadata(proto.Message): - r"""The long running operation metadata for async model related - methods. - - Attributes: - state (google.cloud.optimization_v1.types.AsyncModelMetadata.State): - The state of the current operation. - state_message (str): - A message providing more details about the - current state of the operation. For example, the - error message if the operation is failed. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The creation time of the operation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update time of the operation. - """ - class State(proto.Enum): - r"""Possible states of the operation. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - RUNNING (1): - Request is being processed. - SUCCEEDED (2): - The operation completed successfully. - CANCELLED (3): - The operation was cancelled. - FAILED (4): - The operation has failed. - """ - STATE_UNSPECIFIED = 0 - RUNNING = 1 - SUCCEEDED = 2 - CANCELLED = 3 - FAILED = 4 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/optimization_v1/types/fleet_routing.py b/owl-bot-staging/v1/google/cloud/optimization_v1/types/fleet_routing.py deleted file mode 100644 index 2d7fa29..0000000 --- a/owl-bot-staging/v1/google/cloud/optimization_v1/types/fleet_routing.py +++ /dev/null @@ -1,4334 +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 typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.optimization_v1.types import async_model -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.optimization.v1', - manifest={ - 'OptimizeToursRequest', - 'OptimizeToursResponse', - 'BatchOptimizeToursRequest', - 'BatchOptimizeToursResponse', - 'ShipmentModel', - 'Shipment', - 'ShipmentTypeIncompatibility', - 'ShipmentTypeRequirement', - 'Vehicle', - 'TimeWindow', - 'CapacityQuantity', - 'CapacityQuantityInterval', - 'DistanceLimit', - 'TransitionAttributes', - 'Waypoint', - 'Location', - 'BreakRule', - 'ShipmentRoute', - 'SkippedShipment', - 'AggregatedMetrics', - 'InjectedSolutionConstraint', - 'OptimizeToursValidationError', - }, -) - - -class OptimizeToursRequest(proto.Message): - r"""Request to be given to a tour optimization solver which - defines the shipment model to solve as well as optimization - parameters. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. Target project and location to make a call. - - Format: ``projects/{project-id}/locations/{location-id}``. - - If no location is specified, a region will be chosen - automatically. - timeout (google.protobuf.duration_pb2.Duration): - If this timeout is set, the server returns a - response before the timeout period has elapsed - or the server deadline for synchronous requests - is reached, whichever is sooner. - - For asynchronous requests, the server will - generate a solution (if possible) before the - timeout has elapsed. - model (google.cloud.optimization_v1.types.ShipmentModel): - Shipment model to solve. - solving_mode (google.cloud.optimization_v1.types.OptimizeToursRequest.SolvingMode): - By default, the solving mode is ``DEFAULT_SOLVE`` (0). - max_validation_errors (int): - Truncates the number of validation errors returned. These - errors are typically attached to an INVALID_ARGUMENT error - payload as a BadRequest error detail - (https://cloud.google.com/apis/design/errors#error_details), - unless solving_mode=VALIDATE_ONLY: see the - [OptimizeToursResponse.validation_errors][google.cloud.optimization.v1.OptimizeToursResponse.validation_errors] - field. This defaults to 100 and is capped at 10,000. - - This field is a member of `oneof`_ ``_max_validation_errors``. - search_mode (google.cloud.optimization_v1.types.OptimizeToursRequest.SearchMode): - Search mode used to solve the request. - injected_first_solution_routes (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute]): - Guide the optimization algorithm in finding a first solution - that is similar to a previous solution. - - The model is constrained when the first solution is built. - Any shipments not performed on a route are implicitly - skipped in the first solution, but they may be performed in - successive solutions. - - The solution must satisfy some basic validity assumptions: - - - for all routes, ``vehicle_index`` must be in range and - not be duplicated. - - for all visits, ``shipment_index`` and - ``visit_request_index`` must be in range. - - a shipment may only be referenced on one route. - - the pickup of a pickup-delivery shipment must be - performed before the delivery. - - no more than one pickup alternative or delivery - alternative of a shipment may be performed. - - for all routes, times are increasing (i.e., - ``vehicle_start_time <= visits[0].start_time <= visits[1].start_time ... <= vehicle_end_time``). - - a shipment may only be performed on a vehicle that is - allowed. A vehicle is allowed if - [Shipment.allowed_vehicle_indices][google.cloud.optimization.v1.Shipment.allowed_vehicle_indices] - is empty or its ``vehicle_index`` is included in - [Shipment.allowed_vehicle_indices][google.cloud.optimization.v1.Shipment.allowed_vehicle_indices]. - - If the injected solution is not feasible, a validation error - is not necessarily returned and an error indicating - infeasibility may be returned instead. - injected_solution_constraint (google.cloud.optimization_v1.types.InjectedSolutionConstraint): - Constrain the optimization algorithm to find - a final solution that is similar to a previous - solution. For example, this may be used to - freeze portions of routes which have already - been completed or which are to be completed but - must not be modified. - - If the injected solution is not feasible, a - validation error is not necessarily returned and - an error indicating infeasibility may be - returned instead. - refresh_details_routes (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute]): - If non-empty, the given routes will be refreshed, without - modifying their underlying sequence of visits or travel - times: only other details will be updated. This does not - solve the model. - - As of 2020/11, this only populates the polylines of - non-empty routes and requires that ``populate_polylines`` is - true. - - The ``route_polyline`` fields of the passed-in routes may be - inconsistent with route ``transitions``. - - This field must not be used together with - ``injected_first_solution_routes`` or - ``injected_solution_constraint``. - - ``Shipment.ignore`` and ``Vehicle.ignore`` have no effect on - the behavior. Polylines are still populated between all - visits in all non-empty routes regardless of whether the - related shipments or vehicles are ignored. - interpret_injected_solutions_using_labels (bool): - If true: - - - uses - [ShipmentRoute.vehicle_label][google.cloud.optimization.v1.ShipmentRoute.vehicle_label] - instead of ``vehicle_index`` to match routes in an - injected solution with vehicles in the request; reuses - the mapping of original - [ShipmentRoute.vehicle_index][google.cloud.optimization.v1.ShipmentRoute.vehicle_index] - to new - [ShipmentRoute.vehicle_index][google.cloud.optimization.v1.ShipmentRoute.vehicle_index] - to update - [ConstraintRelaxation.vehicle_indices][google.cloud.optimization.v1.InjectedSolutionConstraint.ConstraintRelaxation.vehicle_indices] - if non-empty, but the mapping must be unambiguous (i.e., - multiple ``ShipmentRoute``\ s must not share the same - original ``vehicle_index``). - - uses - [ShipmentRoute.Visit.shipment_label][google.cloud.optimization.v1.ShipmentRoute.Visit.shipment_label] - instead of ``shipment_index`` to match visits in an - injected solution with shipments in the request; - - uses - [SkippedShipment.label][google.cloud.optimization.v1.SkippedShipment.label] - instead of - [SkippedShipment.index][google.cloud.optimization.v1.SkippedShipment.index] - to match skipped shipments in the injected solution with - request shipments. - - This interpretation applies to the - ``injected_first_solution_routes``, - ``injected_solution_constraint``, and - ``refresh_details_routes`` fields. It can be used when - shipment or vehicle indices in the request have changed - since the solution was created, perhaps because shipments or - vehicles have been removed from or added to the request. - - If true, labels in the following categories must appear at - most once in their category: - - - [Vehicle.label][google.cloud.optimization.v1.Vehicle.label] - in the request; - - [Shipment.label][google.cloud.optimization.v1.Shipment.label] - in the request; - - [ShipmentRoute.vehicle_label][google.cloud.optimization.v1.ShipmentRoute.vehicle_label] - in the injected solution; - - [SkippedShipment.label][google.cloud.optimization.v1.SkippedShipment.label] - and - [ShipmentRoute.Visit.shipment_label][google.cloud.optimization.v1.ShipmentRoute.Visit.shipment_label] - in the injected solution (except pickup/delivery visit - pairs, whose ``shipment_label`` must appear twice). - - If a ``vehicle_label`` in the injected solution does not - correspond to a request vehicle, the corresponding route is - removed from the solution along with its visits. If a - ``shipment_label`` in the injected solution does not - correspond to a request shipment, the corresponding visit is - removed from the solution. If a - [SkippedShipment.label][google.cloud.optimization.v1.SkippedShipment.label] - in the injected solution does not correspond to a request - shipment, the ``SkippedShipment`` is removed from the - solution. - - Removing route visits or entire routes from an injected - solution may have an effect on the implied constraints, - which may lead to change in solution, validation errors, or - infeasibility. - - NOTE: The caller must ensure that each - [Vehicle.label][google.cloud.optimization.v1.Vehicle.label] - (resp. - [Shipment.label][google.cloud.optimization.v1.Shipment.label]) - uniquely identifies a vehicle (resp. shipment) entity used - across the two relevant requests: the past request that - produced the ``OptimizeToursResponse`` used in the injected - solution and the current request that includes the injected - solution. The uniqueness checks described above are not - enough to guarantee this requirement. - consider_road_traffic (bool): - Consider traffic estimation in calculating ``ShipmentRoute`` - fields - [Transition.travel_duration][google.cloud.optimization.v1.ShipmentRoute.Transition.travel_duration], - [Visit.start_time][google.cloud.optimization.v1.ShipmentRoute.Visit.start_time], - and ``vehicle_end_time``; in setting the - [ShipmentRoute.has_traffic_infeasibilities][google.cloud.optimization.v1.ShipmentRoute.has_traffic_infeasibilities] - field, and in calculating the - [OptimizeToursResponse.total_cost][google.cloud.optimization.v1.OptimizeToursResponse.total_cost] - field. - populate_polylines (bool): - If true, polylines will be populated in response - ``ShipmentRoute``\ s. - populate_transition_polylines (bool): - If true, polylines will be populated in response - [ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions]. - Note that in this case, the polylines will also be populated - in the deprecated ``travel_steps``. - allow_large_deadline_despite_interruption_risk (bool): - If this is set, then the request can have a - deadline (see https://grpc.io/blog/deadlines) of - up to 60 minutes. Otherwise, the maximum - deadline is only 30 minutes. Note that - long-lived requests have a significantly larger - (but still small) risk of interruption. - use_geodesic_distances (bool): - If true, travel distances will be computed using geodesic - distances instead of Google Maps distances, and travel times - will be computed using geodesic distances with a speed - defined by ``geodesic_meters_per_second``. - geodesic_meters_per_second (float): - When ``use_geodesic_distances`` is true, this field must be - set and defines the speed applied to compute travel times. - Its value must be at least 1.0 meters/seconds. - - This field is a member of `oneof`_ ``_geodesic_meters_per_second``. - label (str): - Label that may be used to identify this request, reported - back in the - [OptimizeToursResponse.request_label][google.cloud.optimization.v1.OptimizeToursResponse.request_label]. - populate_travel_step_polylines (bool): - Deprecated: Use - [OptimizeToursRequest.populate_transition_polylines][google.cloud.optimization.v1.OptimizeToursRequest.populate_transition_polylines] - instead. If true, polylines will be populated in response - [ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions]. - Note that in this case, the polylines will also be populated - in the deprecated ``travel_steps``. - """ - class SolvingMode(proto.Enum): - r"""Defines how the solver should handle the request. In all modes but - ``VALIDATE_ONLY``, if the request is invalid, you will receive an - ``INVALID_REQUEST`` error. See - [max_validation_errors][google.cloud.optimization.v1.OptimizeToursRequest.max_validation_errors] - to cap the number of errors returned. - - Values: - DEFAULT_SOLVE (0): - Solve the model. - VALIDATE_ONLY (1): - Only validates the model without solving it: populates as - many - [OptimizeToursResponse.validation_errors][google.cloud.optimization.v1.OptimizeToursResponse.validation_errors] - as possible. - DETECT_SOME_INFEASIBLE_SHIPMENTS (2): - Only populates - [OptimizeToursResponse.skipped_shipments][google.cloud.optimization.v1.OptimizeToursResponse.skipped_shipments], - and doesn't actually solve the rest of the request - (``status`` and ``routes`` are unset in the response). - - *IMPORTANT*: not all infeasible shipments are returned here, - but only the ones that are detected as infeasible as a - preprocessing. - """ - DEFAULT_SOLVE = 0 - VALIDATE_ONLY = 1 - DETECT_SOME_INFEASIBLE_SHIPMENTS = 2 - - class SearchMode(proto.Enum): - r"""Mode defining the behavior of the search, trading off latency - versus solution quality. In all modes, the global request - deadline is enforced. - - Values: - SEARCH_MODE_UNSPECIFIED (0): - Unspecified search mode, equivalent to ``RETURN_FAST``. - RETURN_FAST (1): - Stop the search after finding the first good - solution. - CONSUME_ALL_AVAILABLE_TIME (2): - Spend all the available time to search for - better solutions. - """ - SEARCH_MODE_UNSPECIFIED = 0 - RETURN_FAST = 1 - CONSUME_ALL_AVAILABLE_TIME = 2 - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - model: 'ShipmentModel' = proto.Field( - proto.MESSAGE, - number=3, - message='ShipmentModel', - ) - solving_mode: SolvingMode = proto.Field( - proto.ENUM, - number=4, - enum=SolvingMode, - ) - max_validation_errors: int = proto.Field( - proto.INT32, - number=5, - optional=True, - ) - search_mode: SearchMode = proto.Field( - proto.ENUM, - number=6, - enum=SearchMode, - ) - injected_first_solution_routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='ShipmentRoute', - ) - injected_solution_constraint: 'InjectedSolutionConstraint' = proto.Field( - proto.MESSAGE, - number=8, - message='InjectedSolutionConstraint', - ) - refresh_details_routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='ShipmentRoute', - ) - interpret_injected_solutions_using_labels: bool = proto.Field( - proto.BOOL, - number=10, - ) - consider_road_traffic: bool = proto.Field( - proto.BOOL, - number=11, - ) - populate_polylines: bool = proto.Field( - proto.BOOL, - number=12, - ) - populate_transition_polylines: bool = proto.Field( - proto.BOOL, - number=13, - ) - allow_large_deadline_despite_interruption_risk: bool = proto.Field( - proto.BOOL, - number=14, - ) - use_geodesic_distances: bool = proto.Field( - proto.BOOL, - number=15, - ) - geodesic_meters_per_second: float = proto.Field( - proto.DOUBLE, - number=16, - optional=True, - ) - label: str = proto.Field( - proto.STRING, - number=17, - ) - populate_travel_step_polylines: bool = proto.Field( - proto.BOOL, - number=20, - ) - - -class OptimizeToursResponse(proto.Message): - r"""Response after solving a tour optimization problem containing - the routes followed by each vehicle, the shipments which have - been skipped and the overall cost of the solution. - - Attributes: - routes (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute]): - Routes computed for each vehicle; the i-th - route corresponds to the i-th vehicle in the - model. - request_label (str): - Copy of the - [OptimizeToursRequest.label][google.cloud.optimization.v1.OptimizeToursRequest.label], - if a label was specified in the request. - skipped_shipments (MutableSequence[google.cloud.optimization_v1.types.SkippedShipment]): - The list of all shipments skipped. - validation_errors (MutableSequence[google.cloud.optimization_v1.types.OptimizeToursValidationError]): - List of all the validation errors that we were able to - detect independently. See the "MULTIPLE ERRORS" explanation - for the - [OptimizeToursValidationError][google.cloud.optimization.v1.OptimizeToursValidationError] - message. - metrics (google.cloud.optimization_v1.types.OptimizeToursResponse.Metrics): - Duration, distance and usage metrics for this - solution. - total_cost (float): - Deprecated: Use - [Metrics.total_cost][google.cloud.optimization.v1.OptimizeToursResponse.Metrics.total_cost] - instead. Total cost of the solution. This takes into account - all costs: costs per per hour and travel hour, fixed vehicle - costs, unperformed shipment penalty costs, global duration - cost, etc. - """ - - class Metrics(proto.Message): - r"""Overall metrics, aggregated over all routes. - - Attributes: - aggregated_route_metrics (google.cloud.optimization_v1.types.AggregatedMetrics): - Aggregated over the routes. Each metric is the sum (or max, - for loads) over all - [ShipmentRoute.metrics][google.cloud.optimization.v1.ShipmentRoute.metrics] - fields of the same name. - skipped_mandatory_shipment_count (int): - Number of mandatory shipments skipped. - used_vehicle_count (int): - Number of vehicles used. Note: if a vehicle route is empty - and - [Vehicle.used_if_route_is_empty][google.cloud.optimization.v1.Vehicle.used_if_route_is_empty] - is true, the vehicle is considered used. - earliest_vehicle_start_time (google.protobuf.timestamp_pb2.Timestamp): - The earliest start time for a used vehicle, computed as the - minimum over all used vehicles of - [ShipmentRoute.vehicle_start_time][google.cloud.optimization.v1.ShipmentRoute.vehicle_start_time]. - latest_vehicle_end_time (google.protobuf.timestamp_pb2.Timestamp): - The latest end time for a used vehicle, computed as the - maximum over all used vehicles of - [ShipmentRoute.vehicle_end_time][google.cloud.optimization.v1.ShipmentRoute.vehicle_end_time]. - costs (MutableMapping[str, float]): - Cost of the solution, broken down by cost-related request - fields. The keys are proto paths, relative to the input - OptimizeToursRequest, e.g. "model.shipments.pickups.cost", - and the values are the total cost generated by the - corresponding cost field, aggregated over the whole - solution. In other words, - costs["model.shipments.pickups.cost"] is the sum of all - pickup costs over the solution. All costs defined in the - model are reported in detail here with the exception of - costs related to TransitionAttributes that are only reported - in an aggregated way as of 2022/01. - total_cost (float): - Total cost of the solution. The sum of all - values in the costs map. - """ - - aggregated_route_metrics: 'AggregatedMetrics' = proto.Field( - proto.MESSAGE, - number=1, - message='AggregatedMetrics', - ) - skipped_mandatory_shipment_count: int = proto.Field( - proto.INT32, - number=2, - ) - used_vehicle_count: int = proto.Field( - proto.INT32, - number=3, - ) - earliest_vehicle_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - latest_vehicle_end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - costs: MutableMapping[str, float] = proto.MapField( - proto.STRING, - proto.DOUBLE, - number=10, - ) - total_cost: float = proto.Field( - proto.DOUBLE, - number=6, - ) - - routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ShipmentRoute', - ) - request_label: str = proto.Field( - proto.STRING, - number=3, - ) - skipped_shipments: MutableSequence['SkippedShipment'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='SkippedShipment', - ) - validation_errors: MutableSequence['OptimizeToursValidationError'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='OptimizeToursValidationError', - ) - metrics: Metrics = proto.Field( - proto.MESSAGE, - number=6, - message=Metrics, - ) - total_cost: float = proto.Field( - proto.DOUBLE, - number=2, - ) - - -class BatchOptimizeToursRequest(proto.Message): - r"""Request to batch optimize tours as an asynchronous operation. Each - input file should contain one ``OptimizeToursRequest``, and each - output file will contain one ``OptimizeToursResponse``. The request - contains information to read/write and parse the files. All the - input and output files should be under the same project. - - Attributes: - parent (str): - Required. Target project and location to make a call. - - Format: ``projects/{project-id}/locations/{location-id}``. - - If no location is specified, a region will be chosen - automatically. - model_configs (MutableSequence[google.cloud.optimization_v1.types.BatchOptimizeToursRequest.AsyncModelConfig]): - Required. Input/Output information each - purchase model, such as file paths and data - formats. - """ - - class AsyncModelConfig(proto.Message): - r"""Information for solving one optimization model - asynchronously. - - Attributes: - display_name (str): - User defined model name, can be used as alias - by users to keep track of models. - input_config (google.cloud.optimization_v1.types.InputConfig): - Required. Information about the input model. - output_config (google.cloud.optimization_v1.types.OutputConfig): - Required. The desired output location - information. - enable_checkpoints (bool): - If this is set, the model will be solved in the checkpoint - mode. In this mode, the input model can have a deadline - longer than 30 mins without the risk of interruption. The - model will be solved in multiple short-running stages. Each - stage generates an intermediate checkpoint and stores it in - the user's Cloud Storage buckets. The checkpoint mode should - be preferred over - allow_large_deadline_despite_interruption_risk since it - prevents the risk of interruption. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - input_config: async_model.InputConfig = proto.Field( - proto.MESSAGE, - number=2, - message=async_model.InputConfig, - ) - output_config: async_model.OutputConfig = proto.Field( - proto.MESSAGE, - number=3, - message=async_model.OutputConfig, - ) - enable_checkpoints: bool = proto.Field( - proto.BOOL, - number=4, - ) - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - model_configs: MutableSequence[AsyncModelConfig] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=AsyncModelConfig, - ) - - -class BatchOptimizeToursResponse(proto.Message): - r"""Response to a ``BatchOptimizeToursRequest``. This is returned in the - LRO Operation after the operation is complete. - - """ - - -class ShipmentModel(proto.Message): - r"""A shipment model contains a set of shipments which must be performed - by a set of vehicles, while minimizing the overall cost, which is - the sum of: - - - the cost of routing the vehicles (sum of cost per total time, - cost per travel time, and fixed cost over all vehicles). - - the unperformed shipment penalties. - - the cost of the global duration of the shipments - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - shipments (MutableSequence[google.cloud.optimization_v1.types.Shipment]): - Set of shipments which must be performed in - the model. - vehicles (MutableSequence[google.cloud.optimization_v1.types.Vehicle]): - Set of vehicles which can be used to perform - visits. - max_active_vehicles (int): - Constrains the maximum number of active - vehicles. A vehicle is active if its route - performs at least one shipment. This can be used - to limit the number of routes in the case where - there are fewer drivers than vehicles and that - the fleet of vehicles is heterogeneous. The - optimization will then select the best subset of - vehicles to use. Must be strictly positive. - - This field is a member of `oneof`_ ``_max_active_vehicles``. - global_start_time (google.protobuf.timestamp_pb2.Timestamp): - Global start and end time of the model: no times outside of - this range can be considered valid. - - The model's time span must be less than a year, i.e. the - ``global_end_time`` and the ``global_start_time`` must be - within 31536000 seconds of each other. - - When using ``cost_per_*hour`` fields, you might want to set - this window to a smaller interval to increase performance - (eg. if you model a single day, you should set the global - time limits to that day). If unset, 00:00:00 UTC, January 1, - 1970 (i.e. seconds: 0, nanos: 0) is used as default. - global_end_time (google.protobuf.timestamp_pb2.Timestamp): - If unset, 00:00:00 UTC, January 1, 1971 (i.e. - seconds: 31536000, nanos: 0) is used as default. - global_duration_cost_per_hour (float): - The "global duration" of the overall plan is the difference - between the earliest effective start time and the latest - effective end time of all vehicles. Users can assign a cost - per hour to that quantity to try and optimize for earliest - job completion, for example. This cost must be in the same - unit as - [Shipment.penalty_cost][google.cloud.optimization.v1.Shipment.penalty_cost]. - duration_distance_matrices (MutableSequence[google.cloud.optimization_v1.types.ShipmentModel.DurationDistanceMatrix]): - Specifies duration and distance matrices used in the model. - If this field is empty, Google Maps or geodesic distances - will be used instead, depending on the value of the - ``use_geodesic_distances`` field. If it is not empty, - ``use_geodesic_distances`` cannot be true and neither - ``duration_distance_matrix_src_tags`` nor - ``duration_distance_matrix_dst_tags`` can be empty. - - Usage examples: - - - There are two locations: locA and locB. - - 1 vehicle starting its route at locA and ending it at - locA. - - 1 pickup visit request at locB. - - :: - - model { - vehicles { start_tags: "locA" end_tags: "locA" } - shipments { pickups { tags: "locB" } } - duration_distance_matrix_src_tags: "locA" - duration_distance_matrix_src_tags: "locB" - duration_distance_matrix_dst_tags: "locA" - duration_distance_matrix_dst_tags: "locB" - duration_distance_matrices { - rows { # from: locA - durations { seconds: 0 } meters: 0 # to: locA - durations { seconds: 100 } meters: 1000 # to: locB - } - rows { # from: locB - durations { seconds: 102 } meters: 990 # to: locA - durations { seconds: 0 } meters: 0 # to: locB - } - } - } - - - There are three locations: locA, locB and locC. - - 1 vehicle starting its route at locA and ending it at - locB, using matrix "fast". - - 1 vehicle starting its route at locB and ending it at - locB, using matrix "slow". - - 1 vehicle starting its route at locB and ending it at - locB, using matrix "fast". - - 1 pickup visit request at locC. - - :: - - model { - vehicles { start_tags: "locA" end_tags: "locB" start_tags: "fast" } - vehicles { start_tags: "locB" end_tags: "locB" start_tags: "slow" } - vehicles { start_tags: "locB" end_tags: "locB" start_tags: "fast" } - shipments { pickups { tags: "locC" } } - duration_distance_matrix_src_tags: "locA" - duration_distance_matrix_src_tags: "locB" - duration_distance_matrix_src_tags: "locC" - duration_distance_matrix_dst_tags: "locB" - duration_distance_matrix_dst_tags: "locC" - duration_distance_matrices { - vehicle_start_tag: "fast" - rows { # from: locA - durations { seconds: 1000 } meters: 2000 # to: locB - durations { seconds: 600 } meters: 1000 # to: locC - } - rows { # from: locB - durations { seconds: 0 } meters: 0 # to: locB - durations { seconds: 700 } meters: 1200 # to: locC - } - rows { # from: locC - durations { seconds: 702 } meters: 1190 # to: locB - durations { seconds: 0 } meters: 0 # to: locC - } - } - duration_distance_matrices { - vehicle_start_tag: "slow" - rows { # from: locA - durations { seconds: 1800 } meters: 2001 # to: locB - durations { seconds: 900 } meters: 1002 # to: locC - } - rows { # from: locB - durations { seconds: 0 } meters: 0 # to: locB - durations { seconds: 1000 } meters: 1202 # to: locC - } - rows { # from: locC - durations { seconds: 1001 } meters: 1195 # to: locB - durations { seconds: 0 } meters: 0 # to: locC - } - } - } - duration_distance_matrix_src_tags (MutableSequence[str]): - Tags defining the sources of the duration and distance - matrices; ``duration_distance_matrices(i).rows(j)`` defines - durations and distances from visits with tag - ``duration_distance_matrix_src_tags(j)`` to other visits in - matrix i. - - Tags correspond to - [VisitRequest.tags][google.cloud.optimization.v1.Shipment.VisitRequest.tags] - or - [Vehicle.start_tags][google.cloud.optimization.v1.Vehicle.start_tags]. - A given ``VisitRequest`` or ``Vehicle`` must match exactly - one tag in this field. Note that a ``Vehicle``'s source, - destination and matrix tags may be the same; similarly a - ``VisitRequest``'s source and destination tags may be the - same. All tags must be different and cannot be empty - strings. If this field is not empty, then - ``duration_distance_matrices`` must not be empty. - duration_distance_matrix_dst_tags (MutableSequence[str]): - Tags defining the destinations of the duration and distance - matrices; - ``duration_distance_matrices(i).rows(j).durations(k)`` - (resp. ``duration_distance_matrices(i).rows(j).meters(k))`` - defines the duration (resp. the distance) of the travel from - visits with tag ``duration_distance_matrix_src_tags(j)`` to - visits with tag ``duration_distance_matrix_dst_tags(k)`` in - matrix i. - - Tags correspond to - [VisitRequest.tags][google.cloud.optimization.v1.Shipment.VisitRequest.tags] - or - [Vehicle.start_tags][google.cloud.optimization.v1.Vehicle.start_tags]. - A given ``VisitRequest`` or ``Vehicle`` must match exactly - one tag in this field. Note that a ``Vehicle``'s source, - destination and matrix tags may be the same; similarly a - ``VisitRequest``'s source and destination tags may be the - same. All tags must be different and cannot be empty - strings. If this field is not empty, then - ``duration_distance_matrices`` must not be empty. - transition_attributes (MutableSequence[google.cloud.optimization_v1.types.TransitionAttributes]): - Transition attributes added to the model. - shipment_type_incompatibilities (MutableSequence[google.cloud.optimization_v1.types.ShipmentTypeIncompatibility]): - Sets of incompatible shipment_types (see - ``ShipmentTypeIncompatibility``). - shipment_type_requirements (MutableSequence[google.cloud.optimization_v1.types.ShipmentTypeRequirement]): - Sets of ``shipment_type`` requirements (see - ``ShipmentTypeRequirement``). - precedence_rules (MutableSequence[google.cloud.optimization_v1.types.ShipmentModel.PrecedenceRule]): - Set of precedence rules which must be - enforced in the model. - break_rules (MutableSequence[google.cloud.optimization_v1.types.ShipmentModel.BreakRule]): - Deprecated: No longer used. Set of break rules used in the - model. Each vehicle specifies the ``BreakRule`` that applies - to it via the - [Vehicle.break_rule_indices][google.cloud.optimization.v1.Vehicle.break_rule_indices] - field (which must be a singleton). - """ - - class DurationDistanceMatrix(proto.Message): - r"""Specifies a duration and distance matrix from visit and - vehicle start locations to visit and vehicle end locations. - - Attributes: - rows (MutableSequence[google.cloud.optimization_v1.types.ShipmentModel.DurationDistanceMatrix.Row]): - Specifies the rows of the duration and distance matrix. It - must have as many elements as - [ShipmentModel.duration_distance_matrix_src_tags][google.cloud.optimization.v1.ShipmentModel.duration_distance_matrix_src_tags]. - vehicle_start_tag (str): - Tag defining to which vehicles this duration and distance - matrix applies. If empty, this applies to all vehicles, and - there can only be a single matrix. - - Each vehicle start must match exactly one matrix, i.e. - exactly one of their ``start_tags`` field must match the - ``vehicle_start_tag`` of a matrix (and of that matrix only). - - All matrices must have a different ``vehicle_start_tag``. - """ - - class Row(proto.Message): - r"""Specifies a row of the duration and distance matrix. - - Attributes: - durations (MutableSequence[google.protobuf.duration_pb2.Duration]): - Duration values for a given row. It must have as many - elements as - [ShipmentModel.duration_distance_matrix_dst_tags][google.cloud.optimization.v1.ShipmentModel.duration_distance_matrix_dst_tags]. - meters (MutableSequence[float]): - Distance values for a given row. If no costs or constraints - refer to distances in the model, this can be left empty; - otherwise it must have as many elements as ``durations``. - """ - - durations: MutableSequence[duration_pb2.Duration] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - meters: MutableSequence[float] = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - - rows: MutableSequence['ShipmentModel.DurationDistanceMatrix.Row'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ShipmentModel.DurationDistanceMatrix.Row', - ) - vehicle_start_tag: str = proto.Field( - proto.STRING, - number=2, - ) - - class PrecedenceRule(proto.Message): - r"""A precedence rule between two events (each event is the pickup or - the delivery of a shipment): the "second" event has to start at - least ``offset_duration`` after "first" has started. - - Several precedences can refer to the same (or related) events, e.g., - "pickup of B happens after delivery of A" and "pickup of C happens - after pickup of B". - - Furthermore, precedences only apply when both shipments are - performed and are otherwise ignored. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - first_index (int): - Shipment index of the "first" event. This - field must be specified. - - This field is a member of `oneof`_ ``_first_index``. - first_is_delivery (bool): - Indicates if the "first" event is a delivery. - second_index (int): - Shipment index of the "second" event. This - field must be specified. - - This field is a member of `oneof`_ ``_second_index``. - second_is_delivery (bool): - Indicates if the "second" event is a - delivery. - offset_duration (google.protobuf.duration_pb2.Duration): - The offset between the "first" and "second" - event. It can be negative. - """ - - first_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - first_is_delivery: bool = proto.Field( - proto.BOOL, - number=3, - ) - second_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - second_is_delivery: bool = proto.Field( - proto.BOOL, - number=4, - ) - offset_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - - class BreakRule(proto.Message): - r"""Deprecated: Use top level - [BreakRule][google.cloud.optimization.v1.ShipmentModel.BreakRule] - instead. Rules to generate time breaks for a vehicle (e.g. lunch - breaks). A break is a contiguous period of time during which the - vehicle remains idle at its current position and cannot perform any - visit. A break may occur: - - - during the travel between two visits (which includes the time - right before or right after a visit, but not in the middle of a - visit), in which case it extends the corresponding transit time - between the visits - - before the vehicle start (the vehicle may not start in the middle - of a break), in which case it does not affect the vehicle start - time. - - after the vehicle end (ditto, with the vehicle end time). - - Attributes: - break_requests (MutableSequence[google.cloud.optimization_v1.types.ShipmentModel.BreakRule.BreakRequest]): - Sequence of breaks. See the ``BreakRequest`` message. - frequency_constraints (MutableSequence[google.cloud.optimization_v1.types.ShipmentModel.BreakRule.FrequencyConstraint]): - Several ``FrequencyConstraint`` may apply. They must all be - satisfied by the ``BreakRequest``\ s of this ``BreakRule``. - See ``FrequencyConstraint``. - """ - - class BreakRequest(proto.Message): - r"""The sequence of breaks (i.e. their number and order) that apply to - each vehicle must be known beforehand. The repeated - ``BreakRequest``\ s define that sequence, in the order in which they - must occur. Their time windows (``earliest_start_time`` / - ``latest_start_time``) may overlap, but they must be compatible with - the order (this is checked). - - Attributes: - earliest_start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Lower bound (inclusive) on the - start of the break. - latest_start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Upper bound (inclusive) on the - start of the break. - min_duration (google.protobuf.duration_pb2.Duration): - Required. Minimum duration of the break. Must - be positive. - """ - - earliest_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - latest_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - min_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - - class FrequencyConstraint(proto.Message): - r"""One may further constrain the frequency and duration of the breaks - specified above, by enforcing a minimum break frequency, such as - "There must be a break of at least 1 hour every 12 hours". Assuming - that this can be interpreted as "Within any sliding time window of - 12h, there must be at least one break of at least one hour", that - example would translate to the following ``FrequencyConstraint``: - - :: - - { - min_break_duration { seconds: 3600 } # 1 hour. - max_inter_break_duration { seconds: 39600 } # 11 hours (12 - 1 = 11). - } - - The timing and duration of the breaks in the solution will respect - all such constraints, in addition to the time windows and minimum - durations already specified in the ``BreakRequest``. - - A ``FrequencyConstraint`` may in practice apply to non-consecutive - breaks. For example, the following schedule honors the "1h every - 12h" example: - - :: - - 04:00 vehicle start - .. performing travel and visits .. - 09:00 1 hour break - 10:00 end of the break - .. performing travel and visits .. - 12:00 20-min lunch break - 12:20 end of the break - .. performing travel and visits .. - 21:00 1 hour break - 22:00 end of the break - .. performing travel and visits .. - 23:59 vehicle end - - Attributes: - min_break_duration (google.protobuf.duration_pb2.Duration): - Required. Minimum break duration for this constraint. - Nonnegative. See description of ``FrequencyConstraint``. - max_inter_break_duration (google.protobuf.duration_pb2.Duration): - Required. Maximum allowed span of any interval of time in - the route that does not include at least partially a break - of ``duration >= min_break_duration``. Must be positive. - """ - - min_break_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - max_inter_break_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - break_requests: MutableSequence['ShipmentModel.BreakRule.BreakRequest'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ShipmentModel.BreakRule.BreakRequest', - ) - frequency_constraints: MutableSequence['ShipmentModel.BreakRule.FrequencyConstraint'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ShipmentModel.BreakRule.FrequencyConstraint', - ) - - shipments: MutableSequence['Shipment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Shipment', - ) - vehicles: MutableSequence['Vehicle'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Vehicle', - ) - max_active_vehicles: int = proto.Field( - proto.INT32, - number=4, - optional=True, - ) - global_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - global_end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - global_duration_cost_per_hour: float = proto.Field( - proto.DOUBLE, - number=7, - ) - duration_distance_matrices: MutableSequence[DurationDistanceMatrix] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=DurationDistanceMatrix, - ) - duration_distance_matrix_src_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=9, - ) - duration_distance_matrix_dst_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - transition_attributes: MutableSequence['TransitionAttributes'] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='TransitionAttributes', - ) - shipment_type_incompatibilities: MutableSequence['ShipmentTypeIncompatibility'] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='ShipmentTypeIncompatibility', - ) - shipment_type_requirements: MutableSequence['ShipmentTypeRequirement'] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message='ShipmentTypeRequirement', - ) - precedence_rules: MutableSequence[PrecedenceRule] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=PrecedenceRule, - ) - break_rules: MutableSequence[BreakRule] = proto.RepeatedField( - proto.MESSAGE, - number=15, - message=BreakRule, - ) - - -class Shipment(proto.Message): - r"""The shipment of a single item, from one of its pickups to one - of its deliveries. For the shipment to be considered as - performed, a unique vehicle must visit one of its pickup - locations (and decrease its spare capacities accordingly), then - visit one of its delivery locations later on (and therefore - re-increase its spare capacities accordingly). - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - pickups (MutableSequence[google.cloud.optimization_v1.types.Shipment.VisitRequest]): - Set of pickup alternatives associated to the - shipment. If not specified, the vehicle only - needs to visit a location corresponding to the - deliveries. - deliveries (MutableSequence[google.cloud.optimization_v1.types.Shipment.VisitRequest]): - Set of delivery alternatives associated to - the shipment. If not specified, the vehicle only - needs to visit a location corresponding to the - pickups. - load_demands (MutableMapping[str, google.cloud.optimization_v1.types.Shipment.Load]): - Load demands of the shipment (for example weight, volume, - number of pallets etc). The keys in the map should be - identifiers describing the type of the corresponding load, - ideally also including the units. For example: "weight_kg", - "volume_gallons", "pallet_count", etc. If a given key does - not appear in the map, the corresponding load is considered - as null. - penalty_cost (float): - If the shipment is not completed, this penalty is added to - the overall cost of the routes. A shipment is considered - completed if one of its pickup and delivery alternatives is - visited. The cost may be expressed in the same unit used for - all other cost-related fields in the model and must be - positive. - - *IMPORTANT*: If this penalty is not specified, it is - considered infinite, i.e. the shipment must be completed. - - This field is a member of `oneof`_ ``_penalty_cost``. - allowed_vehicle_indices (MutableSequence[int]): - The set of vehicles that may perform this shipment. If - empty, all vehicles may perform it. Vehicles are given by - their index in the ``ShipmentModel``'s ``vehicles`` list. - costs_per_vehicle (MutableSequence[float]): - Specifies the cost that is incurred when this shipment is - delivered by each vehicle. If specified, it must have - EITHER: - - - the same number of elements as - ``costs_per_vehicle_indices``. ``costs_per_vehicle[i]`` - corresponds to vehicle ``costs_per_vehicle_indices[i]`` - of the model. - - the same number of elements as there are vehicles in the - model. The i-th element corresponds to vehicle #i of the - model. - - These costs must be in the same unit as ``penalty_cost`` and - must not be negative. Leave this field empty, if there are - no such costs. - costs_per_vehicle_indices (MutableSequence[int]): - Indices of the vehicles to which ``costs_per_vehicle`` - applies. If non-empty, it must have the same number of - elements as ``costs_per_vehicle``. A vehicle index may not - be specified more than once. If a vehicle is excluded from - ``costs_per_vehicle_indices``, its cost is zero. - pickup_to_delivery_relative_detour_limit (float): - Specifies the maximum relative detour time compared to the - shortest path from pickup to delivery. If specified, it must - be nonnegative, and the shipment must contain at least a - pickup and a delivery. - - For example, let t be the shortest time taken to go from the - selected pickup alternative directly to the selected - delivery alternative. Then setting - ``pickup_to_delivery_relative_detour_limit`` enforces: - - :: - - start_time(delivery) - start_time(pickup) <= - std::ceil(t * (1.0 + pickup_to_delivery_relative_detour_limit)) - - If both relative and absolute limits are specified on the - same shipment, the more constraining limit is used for each - possible pickup/delivery pair. As of 2017/10, detours are - only supported when travel durations do not depend on - vehicles. - - This field is a member of `oneof`_ ``_pickup_to_delivery_relative_detour_limit``. - pickup_to_delivery_absolute_detour_limit (google.protobuf.duration_pb2.Duration): - Specifies the maximum absolute detour time compared to the - shortest path from pickup to delivery. If specified, it must - be nonnegative, and the shipment must contain at least a - pickup and a delivery. - - For example, let t be the shortest time taken to go from the - selected pickup alternative directly to the selected - delivery alternative. Then setting - ``pickup_to_delivery_absolute_detour_limit`` enforces: - - :: - - start_time(delivery) - start_time(pickup) <= - t + pickup_to_delivery_absolute_detour_limit - - If both relative and absolute limits are specified on the - same shipment, the more constraining limit is used for each - possible pickup/delivery pair. As of 2017/10, detours are - only supported when travel durations do not depend on - vehicles. - pickup_to_delivery_time_limit (google.protobuf.duration_pb2.Duration): - Specifies the maximum duration from start of - pickup to start of delivery of a shipment. If - specified, it must be nonnegative, and the - shipment must contain at least a pickup and a - delivery. This does not depend on which - alternatives are selected for pickup and - delivery, nor on vehicle speed. This can be - specified alongside maximum detour constraints: - the solution will respect both specifications. - shipment_type (str): - Non-empty string specifying a "type" for this shipment. This - feature can be used to define incompatibilities or - requirements between ``shipment_types`` (see - ``shipment_type_incompatibilities`` and - ``shipment_type_requirements`` in ``ShipmentModel``). - - Differs from ``visit_types`` which is specified for a single - visit: All pickup/deliveries belonging to the same shipment - share the same ``shipment_type``. - label (str): - Specifies a label for this shipment. This label is reported - in the response in the ``shipment_label`` of the - corresponding - [ShipmentRoute.Visit][google.cloud.optimization.v1.ShipmentRoute.Visit]. - ignore (bool): - If true, skip this shipment, but don't apply a - ``penalty_cost``. - - Ignoring a shipment results in a validation error when there - are any ``shipment_type_requirements`` in the model. - - Ignoring a shipment that is performed in - ``injected_first_solution_routes`` or - ``injected_solution_constraint`` is permitted; the solver - removes the related pickup/delivery visits from the - performing route. ``precedence_rules`` that reference - ignored shipments will also be ignored. - demands (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): - Deprecated: Use - [Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands] - instead. - """ - - class VisitRequest(proto.Message): - r"""Request for a visit which can be done by a vehicle: it has a - geo-location (or two, see below), opening and closing times - represented by time windows, and a service duration time (time - spent by the vehicle once it has arrived to pickup or drop off - goods). - - Attributes: - arrival_location (google.type.latlng_pb2.LatLng): - The geo-location where the vehicle arrives when performing - this ``VisitRequest``. If the shipment model has duration - distance matrices, ``arrival_location`` must not be - specified. - arrival_waypoint (google.cloud.optimization_v1.types.Waypoint): - The waypoint where the vehicle arrives when performing this - ``VisitRequest``. If the shipment model has duration - distance matrices, ``arrival_waypoint`` must not be - specified. - departure_location (google.type.latlng_pb2.LatLng): - The geo-location where the vehicle departs after completing - this ``VisitRequest``. Can be omitted if it is the same as - ``arrival_location``. If the shipment model has duration - distance matrices, ``departure_location`` must not be - specified. - departure_waypoint (google.cloud.optimization_v1.types.Waypoint): - The waypoint where the vehicle departs after completing this - ``VisitRequest``. Can be omitted if it is the same as - ``arrival_waypoint``. If the shipment model has duration - distance matrices, ``departure_waypoint`` must not be - specified. - tags (MutableSequence[str]): - Specifies tags attached to the visit request. - Empty or duplicate strings are not allowed. - time_windows (MutableSequence[google.cloud.optimization_v1.types.TimeWindow]): - Time windows which constrain the arrival time at a visit. - Note that a vehicle may depart outside of the arrival time - window, i.e. arrival time + duration do not need to be - inside a time window. This can result in waiting time if the - vehicle arrives before - [TimeWindow.start_time][google.cloud.optimization.v1.TimeWindow.start_time]. - - The absence of ``TimeWindow`` means that the vehicle can - perform this visit at any time. - - Time windows must be disjoint, i.e. no time window must - overlap with or be adjacent to another, and they must be in - increasing order. - - ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` - can only be set if there is a single time window. - duration (google.protobuf.duration_pb2.Duration): - Duration of the visit, i.e. time spent by the vehicle - between arrival and departure (to be added to the possible - waiting time; see ``time_windows``). - cost (float): - Cost to service this visit request on a vehicle route. This - can be used to pay different costs for each alternative - pickup or delivery of a shipment. This cost must be in the - same unit as ``Shipment.penalty_cost`` and must not be - negative. - load_demands (MutableMapping[str, google.cloud.optimization_v1.types.Shipment.Load]): - Load demands of this visit request. This is just like - [Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands] - field, except that it only applies to this - [VisitRequest][google.cloud.optimization.v1.Shipment.VisitRequest] - instead of the whole - [Shipment][google.cloud.optimization.v1.Shipment]. The - demands listed here are added to the demands listed in - [Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands]. - visit_types (MutableSequence[str]): - Specifies the types of the visit. This may be used to - allocate additional time required for a vehicle to complete - this visit (see - [Vehicle.extra_visit_duration_for_visit_type][google.cloud.optimization.v1.Vehicle.extra_visit_duration_for_visit_type]). - - A type can only appear once. - label (str): - Specifies a label for this ``VisitRequest``. This label is - reported in the response as ``visit_label`` in the - corresponding - [ShipmentRoute.Visit][google.cloud.optimization.v1.ShipmentRoute.Visit]. - demands (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): - Deprecated: Use - [VisitRequest.load_demands][google.cloud.optimization.v1.Shipment.VisitRequest.load_demands] - instead. - """ - - arrival_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - arrival_waypoint: 'Waypoint' = proto.Field( - proto.MESSAGE, - number=2, - message='Waypoint', - ) - departure_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=3, - message=latlng_pb2.LatLng, - ) - departure_waypoint: 'Waypoint' = proto.Field( - proto.MESSAGE, - number=4, - message='Waypoint', - ) - tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - time_windows: MutableSequence['TimeWindow'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='TimeWindow', - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - cost: float = proto.Field( - proto.DOUBLE, - number=8, - ) - load_demands: MutableMapping[str, 'Shipment.Load'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=12, - message='Shipment.Load', - ) - visit_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - label: str = proto.Field( - proto.STRING, - number=11, - ) - demands: MutableSequence['CapacityQuantity'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='CapacityQuantity', - ) - - class Load(proto.Message): - r"""When performing a visit, a predefined amount may be added to the - vehicle load if it's a pickup, or subtracted if it's a delivery. - This message defines such amount. See - [load_demands][google.cloud.optimization.v1.Shipment.load_demands]. - - Attributes: - amount (int): - The amount by which the load of the vehicle - performing the corresponding visit will vary. - Since it is an integer, users are advised to - choose an appropriate unit to avoid loss of - precision. Must be ≥ 0. - """ - - amount: int = proto.Field( - proto.INT64, - number=2, - ) - - pickups: MutableSequence[VisitRequest] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=VisitRequest, - ) - deliveries: MutableSequence[VisitRequest] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=VisitRequest, - ) - load_demands: MutableMapping[str, Load] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=14, - message=Load, - ) - penalty_cost: float = proto.Field( - proto.DOUBLE, - number=4, - optional=True, - ) - allowed_vehicle_indices: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=5, - ) - costs_per_vehicle: MutableSequence[float] = proto.RepeatedField( - proto.DOUBLE, - number=6, - ) - costs_per_vehicle_indices: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=7, - ) - pickup_to_delivery_relative_detour_limit: float = proto.Field( - proto.DOUBLE, - number=8, - optional=True, - ) - pickup_to_delivery_absolute_detour_limit: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=9, - message=duration_pb2.Duration, - ) - pickup_to_delivery_time_limit: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=10, - message=duration_pb2.Duration, - ) - shipment_type: str = proto.Field( - proto.STRING, - number=11, - ) - label: str = proto.Field( - proto.STRING, - number=12, - ) - ignore: bool = proto.Field( - proto.BOOL, - number=13, - ) - demands: MutableSequence['CapacityQuantity'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='CapacityQuantity', - ) - - -class ShipmentTypeIncompatibility(proto.Message): - r"""Specifies incompatibilties between shipments depending on their - shipment_type. The appearance of incompatible shipments on the same - route is restricted based on the incompatibility mode. - - Attributes: - types (MutableSequence[str]): - List of incompatible types. Two shipments having different - ``shipment_types`` among those listed are "incompatible". - incompatibility_mode (google.cloud.optimization_v1.types.ShipmentTypeIncompatibility.IncompatibilityMode): - Mode applied to the incompatibility. - """ - class IncompatibilityMode(proto.Enum): - r"""Modes defining how the appearance of incompatible shipments - are restricted on the same route. - - Values: - INCOMPATIBILITY_MODE_UNSPECIFIED (0): - Unspecified incompatibility mode. This value - should never be used. - NOT_PERFORMED_BY_SAME_VEHICLE (1): - In this mode, two shipments with incompatible - types can never share the same vehicle. - NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY (2): - For two shipments with incompatible types with the - ``NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY`` incompatibility mode: - - - If both are pickups only (no deliveries) or deliveries - only (no pickups), they cannot share the same vehicle at - all. - - If one of the shipments has a delivery and the other a - pickup, the two shipments can share the same vehicle iff - the former shipment is delivered before the latter is - picked up. - """ - INCOMPATIBILITY_MODE_UNSPECIFIED = 0 - NOT_PERFORMED_BY_SAME_VEHICLE = 1 - NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY = 2 - - types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - incompatibility_mode: IncompatibilityMode = proto.Field( - proto.ENUM, - number=2, - enum=IncompatibilityMode, - ) - - -class ShipmentTypeRequirement(proto.Message): - r"""Specifies requirements between shipments based on their - shipment_type. The specifics of the requirement are defined by the - requirement mode. - - Attributes: - required_shipment_type_alternatives (MutableSequence[str]): - List of alternative shipment types required by the - ``dependent_shipment_types``. - dependent_shipment_types (MutableSequence[str]): - All shipments with a type in the - ``dependent_shipment_types`` field require at least one - shipment of type ``required_shipment_type_alternatives`` to - be visited on the same route. - - NOTE: Chains of requirements such that a ``shipment_type`` - depends on itself are not allowed. - requirement_mode (google.cloud.optimization_v1.types.ShipmentTypeRequirement.RequirementMode): - Mode applied to the requirement. - """ - class RequirementMode(proto.Enum): - r"""Modes defining the appearance of dependent shipments on a - route. - - Values: - REQUIREMENT_MODE_UNSPECIFIED (0): - Unspecified requirement mode. This value - should never be used. - PERFORMED_BY_SAME_VEHICLE (1): - In this mode, all "dependent" shipments must - share the same vehicle as at least one of their - "required" shipments. - IN_SAME_VEHICLE_AT_PICKUP_TIME (2): - With the ``IN_SAME_VEHICLE_AT_PICKUP_TIME`` mode, all - "dependent" shipments need to have at least one "required" - shipment on their vehicle at the time of their pickup. - - A "dependent" shipment pickup must therefore have either: - - - A delivery-only "required" shipment delivered on the - route after, or - - A "required" shipment picked up on the route before it, - and if the "required" shipment has a delivery, this - delivery must be performed after the "dependent" - shipment's pickup. - IN_SAME_VEHICLE_AT_DELIVERY_TIME (3): - Same as before, except the "dependent" shipments need to - have a "required" shipment on their vehicle at the time of - their *delivery*. - """ - REQUIREMENT_MODE_UNSPECIFIED = 0 - PERFORMED_BY_SAME_VEHICLE = 1 - IN_SAME_VEHICLE_AT_PICKUP_TIME = 2 - IN_SAME_VEHICLE_AT_DELIVERY_TIME = 3 - - required_shipment_type_alternatives: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - dependent_shipment_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - requirement_mode: RequirementMode = proto.Field( - proto.ENUM, - number=3, - enum=RequirementMode, - ) - - -class Vehicle(proto.Message): - r"""Models a vehicle in a shipment problem. Solving a shipment problem - will build a route starting from ``start_location`` and ending at - ``end_location`` for this vehicle. A route is a sequence of visits - (see ``ShipmentRoute``). - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - travel_mode (google.cloud.optimization_v1.types.Vehicle.TravelMode): - The travel mode which affects the roads usable by the - vehicle and its speed. See also - ``travel_duration_multiple``. - start_location (google.type.latlng_pb2.LatLng): - Geographic location where the vehicle starts before picking - up any shipments. If not specified, the vehicle starts at - its first pickup. If the shipment model has duration and - distance matrices, ``start_location`` must not be specified. - start_waypoint (google.cloud.optimization_v1.types.Waypoint): - Waypoint representing a geographic location where the - vehicle starts before picking up any shipments. If neither - ``start_waypoint`` nor ``start_location`` is specified, the - vehicle starts at its first pickup. If the shipment model - has duration and distance matrices, ``start_waypoint`` must - not be specified. - end_location (google.type.latlng_pb2.LatLng): - Geographic location where the vehicle ends after it has - completed its last ``VisitRequest``. If not specified the - vehicle's ``ShipmentRoute`` ends immediately when it - completes its last ``VisitRequest``. If the shipment model - has duration and distance matrices, ``end_location`` must - not be specified. - end_waypoint (google.cloud.optimization_v1.types.Waypoint): - Waypoint representing a geographic location where the - vehicle ends after it has completed its last - ``VisitRequest``. If neither ``end_waypoint`` nor - ``end_location`` is specified, the vehicle's - ``ShipmentRoute`` ends immediately when it completes its - last ``VisitRequest``. If the shipment model has duration - and distance matrices, ``end_waypoint`` must not be - specified. - start_tags (MutableSequence[str]): - Specifies tags attached to the start of the - vehicle's route. - Empty or duplicate strings are not allowed. - end_tags (MutableSequence[str]): - Specifies tags attached to the end of the - vehicle's route. - Empty or duplicate strings are not allowed. - start_time_windows (MutableSequence[google.cloud.optimization_v1.types.TimeWindow]): - Time windows during which the vehicle may depart its start - location. They must be within the global time limits (see - [ShipmentModel.global_*][google.cloud.optimization.v1.ShipmentModel.global_start_time] - fields). If unspecified, there is no limitation besides - those global time limits. - - Time windows belonging to the same repeated field must be - disjoint, i.e. no time window can overlap with or be - adjacent to another, and they must be in chronological - order. - - ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` - can only be set if there is a single time window. - end_time_windows (MutableSequence[google.cloud.optimization_v1.types.TimeWindow]): - Time windows during which the vehicle may arrive at its end - location. They must be within the global time limits (see - [ShipmentModel.global_*][google.cloud.optimization.v1.ShipmentModel.global_start_time] - fields). If unspecified, there is no limitation besides - those global time limits. - - Time windows belonging to the same repeated field must be - disjoint, i.e. no time window can overlap with or be - adjacent to another, and they must be in chronological - order. - - ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` - can only be set if there is a single time window. - travel_duration_multiple (float): - Specifies a multiplicative factor that can be used to - increase or decrease travel times of this vehicle. For - example, setting this to 2.0 means that this vehicle is - slower and has travel times that are twice what they are for - standard vehicles. This multiple does not affect visit - durations. It does affect cost if ``cost_per_hour`` or - ``cost_per_traveled_hour`` are specified. This must be in - the range [0.001, 1000.0]. If unset, the vehicle is - standard, and this multiple is considered 1.0. - - WARNING: Travel times will be rounded to the nearest second - after this multiple is applied but before performing any - numerical operations, thus, a small multiple may result in a - loss of precision. - - See also ``extra_visit_duration_for_visit_type`` below. - - This field is a member of `oneof`_ ``_travel_duration_multiple``. - unloading_policy (google.cloud.optimization_v1.types.Vehicle.UnloadingPolicy): - Unloading policy enforced on the vehicle. - load_limits (MutableMapping[str, google.cloud.optimization_v1.types.Vehicle.LoadLimit]): - Capacities of the vehicle (weight, volume, # of pallets for - example). The keys in the map are the identifiers of the - type of load, consistent with the keys of the - [Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands] - field. If a given key is absent from this map, the - corresponding capacity is considered to be limitless. - cost_per_hour (float): - Vehicle costs: all costs add up and must be in the same unit - as - [Shipment.penalty_cost][google.cloud.optimization.v1.Shipment.penalty_cost]. - - Cost per hour of the vehicle route. This cost is applied to - the total time taken by the route, and includes travel time, - waiting time, and visit time. Using ``cost_per_hour`` - instead of just ``cost_per_traveled_hour`` may result in - additional latency. - cost_per_traveled_hour (float): - Cost per traveled hour of the vehicle route. This cost is - applied only to travel time taken by the route (i.e., that - reported in - [ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions]), - and excludes waiting time and visit time. - cost_per_kilometer (float): - Cost per kilometer of the vehicle route. This cost is - applied to the distance reported in the - [ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions] - and does not apply to any distance implicitly traveled from - the ``arrival_location`` to the ``departure_location`` of a - single ``VisitRequest``. - fixed_cost (float): - Fixed cost applied if this vehicle is used to - handle a shipment. - used_if_route_is_empty (bool): - This field only applies to vehicles when their route does - not serve any shipments. It indicates if the vehicle should - be considered as used or not in this case. - - If true, the vehicle goes from its start to its end location - even if it doesn't serve any shipments, and time and - distance costs resulting from its start --> end travel are - taken into account. - - Otherwise, it doesn't travel from its start to its end - location, and no ``break_rule`` or delay (from - ``TransitionAttributes``) are scheduled for this vehicle. In - this case, the vehicle's ``ShipmentRoute`` doesn't contain - any information except for the vehicle index and label. - route_duration_limit (google.cloud.optimization_v1.types.Vehicle.DurationLimit): - Limit applied to the total duration of the vehicle's route. - In a given ``OptimizeToursResponse``, the route duration of - a vehicle is the difference between its ``vehicle_end_time`` - and ``vehicle_start_time``. - travel_duration_limit (google.cloud.optimization_v1.types.Vehicle.DurationLimit): - Limit applied to the travel duration of the vehicle's route. - In a given ``OptimizeToursResponse``, the route travel - duration is the sum of all its - [transitions.travel_duration][google.cloud.optimization.v1.ShipmentRoute.Transition.travel_duration]. - route_distance_limit (google.cloud.optimization_v1.types.DistanceLimit): - Limit applied to the total distance of the vehicle's route. - In a given ``OptimizeToursResponse``, the route distance is - the sum of all its - [transitions.travel_distance_meters][google.cloud.optimization.v1.ShipmentRoute.Transition.travel_distance_meters]. - extra_visit_duration_for_visit_type (MutableMapping[str, google.protobuf.duration_pb2.Duration]): - Specifies a map from visit_types strings to durations. The - duration is time in addition to - [VisitRequest.duration][google.cloud.optimization.v1.Shipment.VisitRequest.duration] - to be taken at visits with the specified ``visit_types``. - This extra visit duration adds cost if ``cost_per_hour`` is - specified. Keys (i.e. ``visit_types``) cannot be empty - strings. - - If a visit request has multiple types, a duration will be - added for each type in the map. - break_rule (google.cloud.optimization_v1.types.BreakRule): - Describes the break schedule to be enforced - on this vehicle. If empty, no breaks will be - scheduled for this vehicle. - label (str): - Specifies a label for this vehicle. This label is reported - in the response as the ``vehicle_label`` of the - corresponding - [ShipmentRoute][google.cloud.optimization.v1.ShipmentRoute]. - ignore (bool): - If true, ``used_if_route_is_empty`` must be false, and this - vehicle will remain unused. - - If a shipment is performed by an ignored vehicle in - ``injected_first_solution_routes``, it is skipped in the - first solution but is free to be performed in the response. - - If a shipment is performed by an ignored vehicle in - ``injected_solution_constraint`` and any related - pickup/delivery is constrained to remain on the vehicle - (i.e., not relaxed to level ``RELAX_ALL_AFTER_THRESHOLD``), - it is skipped in the response. If a shipment has a non-empty - ``allowed_vehicle_indices`` field and all of the allowed - vehicles are ignored, it is skipped in the response. - break_rule_indices (MutableSequence[int]): - Deprecated: No longer used. Indices in the ``break_rule`` - field in the source - [ShipmentModel][google.cloud.optimization.v1.ShipmentModel]. - They correspond to break rules enforced on the vehicle. - - As of 2018/03, at most one rule index per vehicle can be - specified. - capacities (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): - Deprecated: Use - [Vehicle.load_limits][google.cloud.optimization.v1.Vehicle.load_limits] - instead. - start_load_intervals (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantityInterval]): - Deprecated: Use - [Vehicle.LoadLimit.start_load_interval][google.cloud.optimization.v1.Vehicle.LoadLimit.start_load_interval] - instead. - end_load_intervals (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantityInterval]): - Deprecated: Use - [Vehicle.LoadLimit.end_load_interval][google.cloud.optimization.v1.Vehicle.LoadLimit.end_load_interval] - instead. - """ - class TravelMode(proto.Enum): - r"""Travel modes which can be used by vehicles. - - These should be a subset of the Google Maps Platform Routes - Preferred API travel modes, see: - https://developers.google.com/maps/documentation/routes_preferred/reference/rest/Shared.Types/RouteTravelMode. - - Values: - TRAVEL_MODE_UNSPECIFIED (0): - Unspecified travel mode, equivalent to ``DRIVING``. - DRIVING (1): - Travel mode corresponding to driving - directions (car, ...). - """ - TRAVEL_MODE_UNSPECIFIED = 0 - DRIVING = 1 - - class UnloadingPolicy(proto.Enum): - r"""Policy on how a vehicle can be unloaded. Applies only to shipments - having both a pickup and a delivery. - - Other shipments are free to occur anywhere on the route independent - of ``unloading_policy``. - - Values: - UNLOADING_POLICY_UNSPECIFIED (0): - Unspecified unloading policy; deliveries must - just occur after their corresponding pickups. - LAST_IN_FIRST_OUT (1): - Deliveries must occur in reverse order of - pickups - FIRST_IN_FIRST_OUT (2): - Deliveries must occur in the same order as - pickups - """ - UNLOADING_POLICY_UNSPECIFIED = 0 - LAST_IN_FIRST_OUT = 1 - FIRST_IN_FIRST_OUT = 2 - - class LoadLimit(proto.Message): - r"""Defines a load limit applying to a vehicle, e.g. "this truck may - only carry up to 3500 kg". See - [load_limits][google.cloud.optimization.v1.Vehicle.load_limits]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - max_load (int): - The maximum acceptable amount of load. - - This field is a member of `oneof`_ ``_max_load``. - soft_max_load (int): - A soft limit of the load. See - [cost_per_unit_above_soft_max][google.cloud.optimization.v1.Vehicle.LoadLimit.cost_per_unit_above_soft_max]. - cost_per_unit_above_soft_max (float): - If the load ever exceeds - [soft_max_load][google.cloud.optimization.v1.Vehicle.LoadLimit.soft_max_load] - along this vehicle's route, the following cost penalty - applies (only once per vehicle): (load - - [soft_max_load][google.cloud.optimization.v1.Vehicle.LoadLimit.soft_max_load]) - - - [cost_per_unit_above_soft_max][google.cloud.optimization.v1.Vehicle.LoadLimit.cost_per_unit_above_soft_max]. - All costs add up and must be in the same unit as - [Shipment.penalty_cost][google.cloud.optimization.v1.Shipment.penalty_cost]. - start_load_interval (google.cloud.optimization_v1.types.Vehicle.LoadLimit.Interval): - The acceptable load interval of the vehicle - at the start of the route. - end_load_interval (google.cloud.optimization_v1.types.Vehicle.LoadLimit.Interval): - The acceptable load interval of the vehicle - at the end of the route. - """ - - class Interval(proto.Message): - r"""Interval of acceptable load amounts. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - min_ (int): - A minimum acceptable load. Must be ≥ 0. If they're both - specified, - [min][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval.min] - must be ≤ - [max][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval.max]. - max_ (int): - A maximum acceptable load. Must be ≥ 0. If unspecified, the - maximum load is unrestricted by this message. If they're - both specified, - [min][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval.min] - must be ≤ - [max][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval.max]. - - This field is a member of `oneof`_ ``_max``. - """ - - min_: int = proto.Field( - proto.INT64, - number=1, - ) - max_: int = proto.Field( - proto.INT64, - number=2, - optional=True, - ) - - max_load: int = proto.Field( - proto.INT64, - number=1, - optional=True, - ) - soft_max_load: int = proto.Field( - proto.INT64, - number=2, - ) - cost_per_unit_above_soft_max: float = proto.Field( - proto.DOUBLE, - number=3, - ) - start_load_interval: 'Vehicle.LoadLimit.Interval' = proto.Field( - proto.MESSAGE, - number=4, - message='Vehicle.LoadLimit.Interval', - ) - end_load_interval: 'Vehicle.LoadLimit.Interval' = proto.Field( - proto.MESSAGE, - number=5, - message='Vehicle.LoadLimit.Interval', - ) - - class DurationLimit(proto.Message): - r"""A limit defining a maximum duration of the route of a - vehicle. It can be either hard or soft. - - When a soft limit field is defined, both the soft max threshold - and its associated cost must be defined together. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - max_duration (google.protobuf.duration_pb2.Duration): - A hard limit constraining the duration to be at most - max_duration. - soft_max_duration (google.protobuf.duration_pb2.Duration): - A soft limit not enforcing a maximum duration limit, but - when violated makes the route incur a cost. This cost adds - up to other costs defined in the model, with the same unit. - - If defined, ``soft_max_duration`` must be nonnegative. If - max_duration is also defined, ``soft_max_duration`` must be - less than max_duration. - cost_per_hour_after_soft_max (float): - Cost per hour incurred if the ``soft_max_duration`` - threshold is violated. The additional cost is 0 if the - duration is under the threshold, otherwise the cost depends - on the duration as follows: - - :: - - cost_per_hour_after_soft_max * (duration - soft_max_duration) - - The cost must be nonnegative. - - This field is a member of `oneof`_ ``_cost_per_hour_after_soft_max``. - quadratic_soft_max_duration (google.protobuf.duration_pb2.Duration): - A soft limit not enforcing a maximum duration limit, but - when violated makes the route incur a cost, quadratic in the - duration. This cost adds up to other costs defined in the - model, with the same unit. - - If defined, ``quadratic_soft_max_duration`` must be - nonnegative. If ``max_duration`` is also defined, - ``quadratic_soft_max_duration`` must be less than - ``max_duration``, and the difference must be no larger than - one day: - - :: - - `max_duration - quadratic_soft_max_duration <= 86400 seconds` - cost_per_square_hour_after_quadratic_soft_max (float): - Cost per square hour incurred if the - ``quadratic_soft_max_duration`` threshold is violated. - - The additional cost is 0 if the duration is under the - threshold, otherwise the cost depends on the duration as - follows: - - :: - - cost_per_square_hour_after_quadratic_soft_max * - (duration - quadratic_soft_max_duration)^2 - - The cost must be nonnegative. - - This field is a member of `oneof`_ ``_cost_per_square_hour_after_quadratic_soft_max``. - """ - - max_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - soft_max_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - cost_per_hour_after_soft_max: float = proto.Field( - proto.DOUBLE, - number=3, - optional=True, - ) - quadratic_soft_max_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - cost_per_square_hour_after_quadratic_soft_max: float = proto.Field( - proto.DOUBLE, - number=5, - optional=True, - ) - - travel_mode: TravelMode = proto.Field( - proto.ENUM, - number=1, - enum=TravelMode, - ) - start_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=3, - message=latlng_pb2.LatLng, - ) - start_waypoint: 'Waypoint' = proto.Field( - proto.MESSAGE, - number=4, - message='Waypoint', - ) - end_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=5, - message=latlng_pb2.LatLng, - ) - end_waypoint: 'Waypoint' = proto.Field( - proto.MESSAGE, - number=6, - message='Waypoint', - ) - start_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - end_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - start_time_windows: MutableSequence['TimeWindow'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='TimeWindow', - ) - end_time_windows: MutableSequence['TimeWindow'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='TimeWindow', - ) - travel_duration_multiple: float = proto.Field( - proto.DOUBLE, - number=11, - optional=True, - ) - unloading_policy: UnloadingPolicy = proto.Field( - proto.ENUM, - number=12, - enum=UnloadingPolicy, - ) - load_limits: MutableMapping[str, LoadLimit] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=30, - message=LoadLimit, - ) - cost_per_hour: float = proto.Field( - proto.DOUBLE, - number=16, - ) - cost_per_traveled_hour: float = proto.Field( - proto.DOUBLE, - number=17, - ) - cost_per_kilometer: float = proto.Field( - proto.DOUBLE, - number=18, - ) - fixed_cost: float = proto.Field( - proto.DOUBLE, - number=19, - ) - used_if_route_is_empty: bool = proto.Field( - proto.BOOL, - number=20, - ) - route_duration_limit: DurationLimit = proto.Field( - proto.MESSAGE, - number=21, - message=DurationLimit, - ) - travel_duration_limit: DurationLimit = proto.Field( - proto.MESSAGE, - number=22, - message=DurationLimit, - ) - route_distance_limit: 'DistanceLimit' = proto.Field( - proto.MESSAGE, - number=23, - message='DistanceLimit', - ) - extra_visit_duration_for_visit_type: MutableMapping[str, duration_pb2.Duration] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=24, - message=duration_pb2.Duration, - ) - break_rule: 'BreakRule' = proto.Field( - proto.MESSAGE, - number=25, - message='BreakRule', - ) - label: str = proto.Field( - proto.STRING, - number=27, - ) - ignore: bool = proto.Field( - proto.BOOL, - number=28, - ) - break_rule_indices: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=29, - ) - capacities: MutableSequence['CapacityQuantity'] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message='CapacityQuantity', - ) - start_load_intervals: MutableSequence['CapacityQuantityInterval'] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='CapacityQuantityInterval', - ) - end_load_intervals: MutableSequence['CapacityQuantityInterval'] = proto.RepeatedField( - proto.MESSAGE, - number=15, - message='CapacityQuantityInterval', - ) - - -class TimeWindow(proto.Message): - r"""Time windows constrain the time of an event, such as the arrival - time at a visit, or the start and end time of a vehicle. - - Hard time window bounds, ``start_time`` and ``end_time``, enforce - the earliest and latest time of the event, such that - ``start_time <= event_time <= end_time``. The soft time window lower - bound, ``soft_start_time``, expresses a preference for the event to - happen at or after ``soft_start_time`` by incurring a cost - proportional to how long before soft_start_time the event occurs. - The soft time window upper bound, ``soft_end_time``, expresses a - preference for the event to happen at or before ``soft_end_time`` by - incurring a cost proportional to how long after ``soft_end_time`` - the event occurs. ``start_time``, ``end_time``, ``soft_start_time`` - and ``soft_end_time`` should be within the global time limits (see - [ShipmentModel.global_start_time][google.cloud.optimization.v1.ShipmentModel.global_start_time] - and - [ShipmentModel.global_end_time][google.cloud.optimization.v1.ShipmentModel.global_end_time]) - and should respect: - - :: - - 0 <= `start_time` <= `soft_start_time` <= `end_time` and - 0 <= `start_time` <= `soft_end_time` <= `end_time`. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - The hard time window start time. If unspecified it will be - set to ``ShipmentModel.global_start_time``. - end_time (google.protobuf.timestamp_pb2.Timestamp): - The hard time window end time. If unspecified it will be set - to ``ShipmentModel.global_end_time``. - soft_start_time (google.protobuf.timestamp_pb2.Timestamp): - The soft start time of the time window. - soft_end_time (google.protobuf.timestamp_pb2.Timestamp): - The soft end time of the time window. - cost_per_hour_before_soft_start_time (float): - A cost per hour added to other costs in the model if the - event occurs before soft_start_time, computed as: - - :: - - max(0, soft_start_time - t.seconds) - * cost_per_hour_before_soft_start_time / 3600, - t being the time of the event. - - This cost must be positive, and the field can only be set if - soft_start_time has been set. - - This field is a member of `oneof`_ ``_cost_per_hour_before_soft_start_time``. - cost_per_hour_after_soft_end_time (float): - A cost per hour added to other costs in the model if the - event occurs after ``soft_end_time``, computed as: - - :: - - max(0, t.seconds - soft_end_time.seconds) - * cost_per_hour_after_soft_end_time / 3600, - t being the time of the event. - - This cost must be positive, and the field can only be set if - ``soft_end_time`` has been set. - - This field is a member of `oneof`_ ``_cost_per_hour_after_soft_end_time``. - """ - - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - soft_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - soft_end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - cost_per_hour_before_soft_start_time: float = proto.Field( - proto.DOUBLE, - number=5, - optional=True, - ) - cost_per_hour_after_soft_end_time: float = proto.Field( - proto.DOUBLE, - number=6, - optional=True, - ) - - -class CapacityQuantity(proto.Message): - r"""Deprecated: Use - [Vehicle.LoadLimit.Interval][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval] - instead. - - Attributes: - type_ (str): - - value (int): - - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - value: int = proto.Field( - proto.INT64, - number=2, - ) - - -class CapacityQuantityInterval(proto.Message): - r"""Deprecated: Use - [Vehicle.LoadLimit.Interval][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval] - instead. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - type_ (str): - - min_value (int): - - This field is a member of `oneof`_ ``_min_value``. - max_value (int): - - This field is a member of `oneof`_ ``_max_value``. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - min_value: int = proto.Field( - proto.INT64, - number=2, - optional=True, - ) - max_value: int = proto.Field( - proto.INT64, - number=3, - optional=True, - ) - - -class DistanceLimit(proto.Message): - r"""A limit defining a maximum distance which can be traveled. It can be - either hard or soft. - - If a soft limit is defined, both ``soft_max_meters`` and - ``cost_per_kilometer_above_soft_max`` must be defined and be - nonnegative. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - max_meters (int): - A hard limit constraining the distance to be at most - max_meters. The limit must be nonnegative. - - This field is a member of `oneof`_ ``_max_meters``. - soft_max_meters (int): - A soft limit not enforcing a maximum distance limit, but - when violated results in a cost which adds up to other costs - defined in the model, with the same unit. - - If defined soft_max_meters must be less than max_meters and - must be nonnegative. - - This field is a member of `oneof`_ ``_soft_max_meters``. - cost_per_kilometer_above_soft_max (float): - Cost per kilometer incurred if distance is above - ``soft_max_meters`` limit. The additional cost is 0 if the - distance is under the limit, otherwise the formula used to - compute the cost is the following: - - :: - - (distance_meters - soft_max_meters) / 1000.0 * - cost_per_kilometer_above_soft_max. - - The cost must be nonnegative. - - This field is a member of `oneof`_ ``_cost_per_kilometer_above_soft_max``. - """ - - max_meters: int = proto.Field( - proto.INT64, - number=1, - optional=True, - ) - soft_max_meters: int = proto.Field( - proto.INT64, - number=2, - optional=True, - ) - cost_per_kilometer_above_soft_max: float = proto.Field( - proto.DOUBLE, - number=3, - optional=True, - ) - - -class TransitionAttributes(proto.Message): - r"""Specifies attributes of transitions between two consecutive visits - on a route. Several ``TransitionAttributes`` may apply to the same - transition: in that case, all extra costs add up and the strictest - constraint or limit applies (following natural "AND" semantics). - - Attributes: - src_tag (str): - Tags defining the set of (src->dst) transitions these - attributes apply to. - - A source visit or vehicle start matches iff its - [VisitRequest.tags][google.cloud.optimization.v1.Shipment.VisitRequest.tags] - or - [Vehicle.start_tags][google.cloud.optimization.v1.Vehicle.start_tags] - either contains ``src_tag`` or does not contain - ``excluded_src_tag`` (depending on which of these two fields - is non-empty). - excluded_src_tag (str): - See ``src_tag``. Exactly one of ``src_tag`` and - ``excluded_src_tag`` must be non-empty. - dst_tag (str): - A destination visit or vehicle end matches iff its - [VisitRequest.tags][google.cloud.optimization.v1.Shipment.VisitRequest.tags] - or - [Vehicle.end_tags][google.cloud.optimization.v1.Vehicle.end_tags] - either contains ``dst_tag`` or does not contain - ``excluded_dst_tag`` (depending on which of these two fields - is non-empty). - excluded_dst_tag (str): - See ``dst_tag``. Exactly one of ``dst_tag`` and - ``excluded_dst_tag`` must be non-empty. - cost (float): - Specifies a cost for performing this - transition. This is in the same unit as all - other costs in the model and must not be - negative. It is applied on top of all other - existing costs. - cost_per_kilometer (float): - Specifies a cost per kilometer applied to the distance - traveled while performing this transition. It adds up to any - [Vehicle.cost_per_kilometer][google.cloud.optimization.v1.Vehicle.cost_per_kilometer] - specified on vehicles. - distance_limit (google.cloud.optimization_v1.types.DistanceLimit): - Specifies a limit on the distance traveled - while performing this transition. - - As of 2021/06, only soft limits are supported. - delay (google.protobuf.duration_pb2.Duration): - Specifies a delay incurred when performing this transition. - - This delay always occurs *after* finishing the source visit - and *before* starting the destination visit. - """ - - src_tag: str = proto.Field( - proto.STRING, - number=1, - ) - excluded_src_tag: str = proto.Field( - proto.STRING, - number=2, - ) - dst_tag: str = proto.Field( - proto.STRING, - number=3, - ) - excluded_dst_tag: str = proto.Field( - proto.STRING, - number=4, - ) - cost: float = proto.Field( - proto.DOUBLE, - number=5, - ) - cost_per_kilometer: float = proto.Field( - proto.DOUBLE, - number=6, - ) - distance_limit: 'DistanceLimit' = proto.Field( - proto.MESSAGE, - number=7, - message='DistanceLimit', - ) - delay: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - - -class Waypoint(proto.Message): - r"""Encapsulates a waypoint. Waypoints mark arrival and departure - locations of VisitRequests, and start and end locations of - Vehicles. - - 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: - location (google.cloud.optimization_v1.types.Location): - A point specified using geographic - coordinates, including an optional heading. - - This field is a member of `oneof`_ ``location_type``. - place_id (str): - The POI Place ID associated with the - waypoint. - - This field is a member of `oneof`_ ``location_type``. - side_of_road (bool): - Indicates that the location of this waypoint is meant to - have a preference for the vehicle to stop at a particular - side of road. When you set this value, the route will pass - through the location so that the vehicle can stop at the - side of road that the location is biased towards from the - center of the road. This option works only for the 'DRIVING' - travel mode, and when the 'location_type' is set to - 'location'. - """ - - location: 'Location' = proto.Field( - proto.MESSAGE, - number=1, - oneof='location_type', - message='Location', - ) - place_id: str = proto.Field( - proto.STRING, - number=2, - oneof='location_type', - ) - side_of_road: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class Location(proto.Message): - r"""Encapsulates a location (a geographic point, and an optional - heading). - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - lat_lng (google.type.latlng_pb2.LatLng): - The waypoint's geographic coordinates. - heading (int): - The compass heading associated with the - direction of the flow of traffic. This value is - used to specify the side of the road to use for - pickup and drop-off. Heading values can be from - 0 to 360, where 0 specifies a heading of due - North, 90 specifies a heading of due East, etc. - - This field is a member of `oneof`_ ``_heading``. - """ - - lat_lng: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - heading: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - - -class BreakRule(proto.Message): - r"""Rules to generate time breaks for a vehicle (e.g. lunch breaks). A - break is a contiguous period of time during which the vehicle - remains idle at its current position and cannot perform any visit. A - break may occur: - - - during the travel between two visits (which includes the time - right before or right after a visit, but not in the middle of a - visit), in which case it extends the corresponding transit time - between the visits, - - or before the vehicle start (the vehicle may not start in the - middle of a break), in which case it does not affect the vehicle - start time. - - or after the vehicle end (ditto, with the vehicle end time). - - Attributes: - break_requests (MutableSequence[google.cloud.optimization_v1.types.BreakRule.BreakRequest]): - Sequence of breaks. See the ``BreakRequest`` message. - frequency_constraints (MutableSequence[google.cloud.optimization_v1.types.BreakRule.FrequencyConstraint]): - Several ``FrequencyConstraint`` may apply. They must all be - satisfied by the ``BreakRequest``\ s of this ``BreakRule``. - See ``FrequencyConstraint``. - """ - - class BreakRequest(proto.Message): - r"""The sequence of breaks (i.e. their number and order) that apply to - each vehicle must be known beforehand. The repeated - ``BreakRequest``\ s define that sequence, in the order in which they - must occur. Their time windows (``earliest_start_time`` / - ``latest_start_time``) may overlap, but they must be compatible with - the order (this is checked). - - Attributes: - earliest_start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Lower bound (inclusive) on the - start of the break. - latest_start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Upper bound (inclusive) on the - start of the break. - min_duration (google.protobuf.duration_pb2.Duration): - Required. Minimum duration of the break. Must - be positive. - """ - - earliest_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - latest_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - min_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - - class FrequencyConstraint(proto.Message): - r"""One may further constrain the frequency and duration of the breaks - specified above, by enforcing a minimum break frequency, such as - "There must be a break of at least 1 hour every 12 hours". Assuming - that this can be interpreted as "Within any sliding time window of - 12h, there must be at least one break of at least one hour", that - example would translate to the following ``FrequencyConstraint``: - - :: - - { - min_break_duration { seconds: 3600 } # 1 hour. - max_inter_break_duration { seconds: 39600 } # 11 hours (12 - 1 = 11). - } - - The timing and duration of the breaks in the solution will respect - all such constraints, in addition to the time windows and minimum - durations already specified in the ``BreakRequest``. - - A ``FrequencyConstraint`` may in practice apply to non-consecutive - breaks. For example, the following schedule honors the "1h every - 12h" example: - - :: - - 04:00 vehicle start - .. performing travel and visits .. - 09:00 1 hour break - 10:00 end of the break - .. performing travel and visits .. - 12:00 20-min lunch break - 12:20 end of the break - .. performing travel and visits .. - 21:00 1 hour break - 22:00 end of the break - .. performing travel and visits .. - 23:59 vehicle end - - Attributes: - min_break_duration (google.protobuf.duration_pb2.Duration): - Required. Minimum break duration for this constraint. - Nonnegative. See description of ``FrequencyConstraint``. - max_inter_break_duration (google.protobuf.duration_pb2.Duration): - Required. Maximum allowed span of any interval of time in - the route that does not include at least partially a break - of ``duration >= min_break_duration``. Must be positive. - """ - - min_break_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - max_inter_break_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - break_requests: MutableSequence[BreakRequest] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=BreakRequest, - ) - frequency_constraints: MutableSequence[FrequencyConstraint] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=FrequencyConstraint, - ) - - -class ShipmentRoute(proto.Message): - r"""A vehicle's route can be decomposed, along the time axis, like this - (we assume there are n visits): - - :: - - | | | | | T[2], | | | - | Transition | Visit #0 | | | V[2], | | | - | #0 | aka | T[1] | V[1] | ... | V[n-1] | T[n] | - | aka T[0] | V[0] | | | V[n-2],| | | - | | | | | T[n-1] | | | - ^ ^ ^ ^ ^ ^ ^ ^ - vehicle V[0].start V[0].end V[1]. V[1]. V[n]. V[n]. vehicle - start (arrival) (departure) start end start end end - - Note that we make a difference between: - - - "punctual events", such as the vehicle start and end and each - visit's start and end (aka arrival and departure). They happen at - a given second. - - "time intervals", such as the visits themselves, and the - transition between visits. Though time intervals can sometimes - have zero duration, i.e. start and end at the same second, they - often have a positive duration. - - Invariants: - - - If there are n visits, there are n+1 transitions. - - A visit is always surrounded by a transition before it (same - index) and a transition after it (index + 1). - - The vehicle start is always followed by transition #0. - - The vehicle end is always preceded by transition #n. - - Zooming in, here is what happens during a ``Transition`` and a - ``Visit``: - - :: - - ---+-------------------------------------+-----------------------------+--> - | TRANSITION[i] | VISIT[i] | - | | | - | * TRAVEL: the vehicle moves from | PERFORM the visit: | - | VISIT[i-1].departure_location to | | - | VISIT[i].arrival_location, which | * Spend some time: | - | takes a given travel duration | the "visit duration". | - | and distance | | - | | * Load or unload | - | * BREAKS: the driver may have | some quantities from the | - | breaks (e.g. lunch break). | vehicle: the "demand". | - | | | - | * WAIT: the driver/vehicle does | | - | nothing. This can happen for | | - | many reasons, for example when | | - | the vehicle reaches the next | | - | event's destination before the | | - | start of its time window | | - | | | - | * DELAY: *right before* the next | | - | arrival. E.g. the vehicle and/or | | - | driver spends time unloading. | | - | | | - ---+-------------------------------------+-----------------------------+--> - ^ ^ ^ - V[i-1].end V[i].start V[i].end - - Lastly, here is how the TRAVEL, BREAKS, DELAY and WAIT can be - arranged during a transition. - - - They don't overlap. - - The DELAY is unique and *must* be a contiguous period of time - right before the next visit (or vehicle end). Thus, it suffice to - know the delay duration to know its start and end time. - - The BREAKS are contiguous, non-overlapping periods of time. The - response specifies the start time and duration of each break. - - TRAVEL and WAIT are "preemptable": they can be interrupted - several times during this transition. Clients can assume that - travel happens "as soon as possible" and that "wait" fills the - remaining time. - - A (complex) example: - - :: - - TRANSITION[i] - --++-----+-----------------------------------------------------------++--> - || | | | | | | || - || T | B | T | | B | | D || - || r | r | r | W | r | W | e || - || a | e | a | a | e | a | l || - || v | a | v | i | a | i | a || - || e | k | e | t | k | t | y || - || l | | l | | | | || - || | | | | | | || - --++-----------------------------------------------------------------++--> - - Attributes: - vehicle_index (int): - Vehicle performing the route, identified by its index in the - source ``ShipmentModel``. - vehicle_label (str): - Label of the vehicle performing this route, equal to - ``ShipmentModel.vehicles(vehicle_index).label``, if - specified. - vehicle_start_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the vehicle starts its route. - vehicle_end_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the vehicle finishes its route. - visits (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute.Visit]): - Ordered sequence of visits representing a route. visits[i] - is the i-th visit in the route. If this field is empty, the - vehicle is considered as unused. - transitions (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute.Transition]): - Ordered list of transitions for the route. - has_traffic_infeasibilities (bool): - When - [OptimizeToursRequest.consider_road_traffic][google.cloud.optimization.v1.OptimizeToursRequest.consider_road_traffic], - is set to true, this field indicates that inconsistencies in - route timings are predicted using traffic-based travel - duration estimates. There may be insufficient time to - complete traffic-adjusted travel, delays, and breaks between - visits, before the first visit, or after the last visit, - while still satisfying the visit and vehicle time windows. - For example, - - :: - - start_time(previous_visit) + duration(previous_visit) + - travel_duration(previous_visit, next_visit) > start_time(next_visit) - - Arrival at next_visit will likely happen later than its - current time window due the increased estimate of travel - time ``travel_duration(previous_visit, next_visit)`` due to - traffic. Also, a break may be forced to overlap with a visit - due to an increase in travel time estimates and visit or - break time window restrictions. - route_polyline (google.cloud.optimization_v1.types.ShipmentRoute.EncodedPolyline): - The encoded polyline representation of the route. This field - is only populated if - [OptimizeToursRequest.populate_polylines][google.cloud.optimization.v1.OptimizeToursRequest.populate_polylines] - is set to true. - breaks (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute.Break]): - Breaks scheduled for the vehicle performing this route. The - ``breaks`` sequence represents time intervals, each starting - at the corresponding ``start_time`` and lasting ``duration`` - seconds. - metrics (google.cloud.optimization_v1.types.AggregatedMetrics): - Duration, distance and load metrics for this route. The - fields of - [AggregatedMetrics][google.cloud.optimization.v1.AggregatedMetrics] - are summed over all - [ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions] - or - [ShipmentRoute.visits][google.cloud.optimization.v1.ShipmentRoute.visits], - depending on the context. - route_costs (MutableMapping[str, float]): - Cost of the route, broken down by cost-related request - fields. The keys are proto paths, relative to the input - OptimizeToursRequest, e.g. "model.shipments.pickups.cost", - and the values are the total cost generated by the - corresponding cost field, aggregated over the whole route. - In other words, costs["model.shipments.pickups.cost"] is the - sum of all pickup costs over the route. All costs defined in - the model are reported in detail here with the exception of - costs related to TransitionAttributes that are only reported - in an aggregated way as of 2022/01. - route_total_cost (float): - Total cost of the route. The sum of all costs - in the cost map. - end_loads (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): - Deprecated: Use - [Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads] - instead. Vehicle loads upon arrival at its end location, for - each type specified in - [Vehicle.capacities][google.cloud.optimization.v1.Vehicle.capacities], - ``start_load_intervals``, ``end_load_intervals`` or demands. - Exception: we omit loads for quantity types unconstrained by - intervals and that don't have any non-zero demand on the - route. - travel_steps (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute.TravelStep]): - Deprecated: Use - [ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions] - instead. Ordered list of travel steps for the route. - vehicle_detour (google.protobuf.duration_pb2.Duration): - Deprecated: No longer used. This field will only be - populated at the - [ShipmentRoute.Visit][google.cloud.optimization.v1.ShipmentRoute.Visit] - level. - - This field is the extra detour time due to the shipments - visited on the route. - - It is equal to ``vehicle_end_time`` - ``vehicle_start_time`` - - travel duration from the vehicle's start_location to its - ``end_location``. - delay_before_vehicle_end (google.cloud.optimization_v1.types.ShipmentRoute.Delay): - Deprecated: Delay occurring before the vehicle end. See - [TransitionAttributes.delay][google.cloud.optimization.v1.TransitionAttributes.delay]. - """ - - class Delay(proto.Message): - r"""Deprecated: Use - [ShipmentRoute.Transition.delay_duration][google.cloud.optimization.v1.ShipmentRoute.Transition.delay_duration] - instead. Time interval spent on the route resulting from a - [TransitionAttributes.delay][google.cloud.optimization.v1.TransitionAttributes.delay]. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start of the delay. - duration (google.protobuf.duration_pb2.Duration): - Duration of the delay. - """ - - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - class Visit(proto.Message): - r"""A visit performed during a route. This visit corresponds to a pickup - or a delivery of a ``Shipment``. - - Attributes: - shipment_index (int): - Index of the ``shipments`` field in the source - [ShipmentModel][google.cloud.optimization.v1.ShipmentModel]. - is_pickup (bool): - If true the visit corresponds to a pickup of a ``Shipment``. - Otherwise, it corresponds to a delivery. - visit_request_index (int): - Index of ``VisitRequest`` in either the pickup or delivery - field of the ``Shipment`` (see ``is_pickup``). - start_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the visit starts. Note that the vehicle may - arrive earlier than this at the visit location. Times are - consistent with the ``ShipmentModel``. - load_demands (MutableMapping[str, google.cloud.optimization_v1.types.Shipment.Load]): - Total visit load demand as the sum of the shipment and the - visit request ``load_demands``. The values are negative if - the visit is a delivery. Demands are reported for the same - types as the - [Transition.loads][google.cloud.optimization.v1.ShipmentRoute.Transition] - (see this field). - detour (google.protobuf.duration_pb2.Duration): - Extra detour time due to the shipments visited on the route - before the visit and to the potential waiting time induced - by time windows. If the visit is a delivery, the detour is - computed from the corresponding pickup visit and is equal - to: - - :: - - start_time(delivery) - start_time(pickup) - - (duration(pickup) + travel duration from the pickup location - to the delivery location). - - Otherwise, it is computed from the vehicle - ``start_location`` and is equal to: - - :: - - start_time - vehicle_start_time - travel duration from - the vehicle's `start_location` to the visit. - shipment_label (str): - Copy of the corresponding ``Shipment.label``, if specified - in the ``Shipment``. - visit_label (str): - Copy of the corresponding - [VisitRequest.label][google.cloud.optimization.v1.Shipment.VisitRequest.label], - if specified in the ``VisitRequest``. - arrival_loads (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): - Deprecated: Use - [Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads] - instead. Vehicle loads upon arrival at the visit location, - for each type specified in - [Vehicle.capacities][google.cloud.optimization.v1.Vehicle.capacities], - ``start_load_intervals``, ``end_load_intervals`` or - ``demands``. - - Exception: we omit loads for quantity types unconstrained by - intervals and that don't have any non-zero demand on the - route. - delay_before_start (google.cloud.optimization_v1.types.ShipmentRoute.Delay): - Deprecated: Use - [ShipmentRoute.Transition.delay_duration][google.cloud.optimization.v1.ShipmentRoute.Transition.delay_duration] - instead. Delay occurring before the visit starts. - demands (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): - Deprecated: Use - [Visit.load_demands][google.cloud.optimization.v1.ShipmentRoute.Visit.load_demands] - instead. - """ - - shipment_index: int = proto.Field( - proto.INT32, - number=1, - ) - is_pickup: bool = proto.Field( - proto.BOOL, - number=2, - ) - visit_request_index: int = proto.Field( - proto.INT32, - number=3, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - load_demands: MutableMapping[str, 'Shipment.Load'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=11, - message='Shipment.Load', - ) - detour: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - shipment_label: str = proto.Field( - proto.STRING, - number=7, - ) - visit_label: str = proto.Field( - proto.STRING, - number=8, - ) - arrival_loads: MutableSequence['CapacityQuantity'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='CapacityQuantity', - ) - delay_before_start: 'ShipmentRoute.Delay' = proto.Field( - proto.MESSAGE, - number=10, - message='ShipmentRoute.Delay', - ) - demands: MutableSequence['CapacityQuantity'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='CapacityQuantity', - ) - - class Transition(proto.Message): - r"""Transition between two events on the route. See the description of - [ShipmentRoute][google.cloud.optimization.v1.ShipmentRoute]. - - If the vehicle does not have a ``start_location`` and/or - ``end_location``, the corresponding travel metrics are 0. - - Attributes: - travel_duration (google.protobuf.duration_pb2.Duration): - Travel duration during this transition. - travel_distance_meters (float): - Distance traveled during the transition. - traffic_info_unavailable (bool): - When traffic is requested via - [OptimizeToursRequest.consider_road_traffic] - [google.cloud.optimization.v1.OptimizeToursRequest.consider_road_traffic], - and the traffic info couldn't be retrieved for a - ``Transition``, this boolean is set to true. This may be - temporary (rare hiccup in the realtime traffic servers) or - permanent (no data for this location). - delay_duration (google.protobuf.duration_pb2.Duration): - Sum of the delay durations applied to this transition. If - any, the delay starts exactly ``delay_duration`` seconds - before the next event (visit or vehicle end). See - [TransitionAttributes.delay][google.cloud.optimization.v1.TransitionAttributes.delay]. - break_duration (google.protobuf.duration_pb2.Duration): - Sum of the duration of the breaks occurring during this - transition, if any. Details about each break's start time - and duration are stored in - [ShipmentRoute.breaks][google.cloud.optimization.v1.ShipmentRoute.breaks]. - wait_duration (google.protobuf.duration_pb2.Duration): - Time spent waiting during this transition. - Wait duration corresponds to idle time and does - not include break time. Also note that this wait - time may be split into several non-contiguous - intervals. - total_duration (google.protobuf.duration_pb2.Duration): - Total duration of the transition, provided for convenience. - It is equal to: - - - next visit ``start_time`` (or ``vehicle_end_time`` if - this is the last transition) - this transition's - ``start_time``; - - if ``ShipmentRoute.has_traffic_infeasibilities`` is - false, the following additionally holds: \`total_duration - = travel_duration + delay_duration - - - break_duration + wait_duration`. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start time of this transition. - route_polyline (google.cloud.optimization_v1.types.ShipmentRoute.EncodedPolyline): - The encoded polyline representation of the route followed - during the transition. This field is only populated if - [populate_transition_polylines] - [google.cloud.optimization.v1.OptimizeToursRequest.populate_transition_polylines] - is set to true. - vehicle_loads (MutableMapping[str, google.cloud.optimization_v1.types.ShipmentRoute.VehicleLoad]): - Vehicle loads during this transition, for each type that - either appears in this vehicle's - [Vehicle.load_limits][google.cloud.optimization.v1.Vehicle.load_limits], - or that have non-zero - [Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands] - on some shipment performed on this route. - - The loads during the first transition are the starting loads - of the vehicle route. Then, after each visit, the visit's - ``load_demands`` are either added or subtracted to get the - next transition's loads, depending on whether the visit was - a pickup or a delivery. - loads (MutableSequence[google.cloud.optimization_v1.types.CapacityQuantity]): - Deprecated: Use - [Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads] - instead. - """ - - travel_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - travel_distance_meters: float = proto.Field( - proto.DOUBLE, - number=2, - ) - traffic_info_unavailable: bool = proto.Field( - proto.BOOL, - number=3, - ) - delay_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - break_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - wait_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - total_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - route_polyline: 'ShipmentRoute.EncodedPolyline' = proto.Field( - proto.MESSAGE, - number=9, - message='ShipmentRoute.EncodedPolyline', - ) - vehicle_loads: MutableMapping[str, 'ShipmentRoute.VehicleLoad'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=11, - message='ShipmentRoute.VehicleLoad', - ) - loads: MutableSequence['CapacityQuantity'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='CapacityQuantity', - ) - - class VehicleLoad(proto.Message): - r"""Reports the actual load of the vehicle at some point along the - route, for a given type (see - [Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads]). - - Attributes: - amount (int): - The amount of load on the vehicle, for the given type. The - unit of load is usually indicated by the type. See - [Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads]. - """ - - amount: int = proto.Field( - proto.INT64, - number=1, - ) - - class EncodedPolyline(proto.Message): - r"""The encoded representation of a polyline. More information on - polyline encoding can be found here: - https://developers.google.com/maps/documentation/utilities/polylinealgorithm - https://developers.google.com/maps/documentation/javascript/reference/geometry#encoding. - - Attributes: - points (str): - String representing encoded points of the - polyline. - """ - - points: str = proto.Field( - proto.STRING, - number=1, - ) - - class Break(proto.Message): - r"""Data representing the execution of a break. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start time of a break. - duration (google.protobuf.duration_pb2.Duration): - Duration of a break. - """ - - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - class TravelStep(proto.Message): - r"""Deprecated: Use - [ShipmentRoute.Transition][google.cloud.optimization.v1.ShipmentRoute.Transition] - instead. Travel between each visit along the route: from the - vehicle's ``start_location`` to the first visit's - ``arrival_location``, then from the first visit's - ``departure_location`` to the second visit's ``arrival_location``, - and so on until the vehicle's ``end_location``. This accounts only - for the actual travel between visits, not counting the waiting time, - the time spent performing a visit, nor the distance covered during a - visit. - - Invariant: ``travel_steps_size() == visits_size() + 1``. - - If the vehicle does not have a start\_ and/or end_location, the - corresponding travel metrics are 0 and/or empty. - - Attributes: - duration (google.protobuf.duration_pb2.Duration): - Duration of the travel step. - distance_meters (float): - Distance traveled during the step. - traffic_info_unavailable (bool): - When traffic is requested via - [OptimizeToursRequest.consider_road_traffic][google.cloud.optimization.v1.OptimizeToursRequest.consider_road_traffic], - and the traffic info couldn't be retrieved for a TravelStep, - this boolean is set to true. This may be temporary (rare - hiccup in the realtime traffic servers) or permanent (no - data for this location). - route_polyline (google.cloud.optimization_v1.types.ShipmentRoute.EncodedPolyline): - The encoded polyline representation of the route followed - during the step. - - This field is only populated if - [OptimizeToursRequest.populate_travel_step_polylines][google.cloud.optimization.v1.OptimizeToursRequest.populate_travel_step_polylines] - is set to true. - """ - - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - distance_meters: float = proto.Field( - proto.DOUBLE, - number=2, - ) - traffic_info_unavailable: bool = proto.Field( - proto.BOOL, - number=3, - ) - route_polyline: 'ShipmentRoute.EncodedPolyline' = proto.Field( - proto.MESSAGE, - number=4, - message='ShipmentRoute.EncodedPolyline', - ) - - vehicle_index: int = proto.Field( - proto.INT32, - number=1, - ) - vehicle_label: str = proto.Field( - proto.STRING, - number=2, - ) - vehicle_start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - vehicle_end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - visits: MutableSequence[Visit] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Visit, - ) - transitions: MutableSequence[Transition] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=Transition, - ) - has_traffic_infeasibilities: bool = proto.Field( - proto.BOOL, - number=9, - ) - route_polyline: EncodedPolyline = proto.Field( - proto.MESSAGE, - number=10, - message=EncodedPolyline, - ) - breaks: MutableSequence[Break] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=Break, - ) - metrics: 'AggregatedMetrics' = proto.Field( - proto.MESSAGE, - number=12, - message='AggregatedMetrics', - ) - route_costs: MutableMapping[str, float] = proto.MapField( - proto.STRING, - proto.DOUBLE, - number=17, - ) - route_total_cost: float = proto.Field( - proto.DOUBLE, - number=18, - ) - end_loads: MutableSequence['CapacityQuantity'] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message='CapacityQuantity', - ) - travel_steps: MutableSequence[TravelStep] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=TravelStep, - ) - vehicle_detour: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=15, - message=duration_pb2.Duration, - ) - delay_before_vehicle_end: Delay = proto.Field( - proto.MESSAGE, - number=16, - message=Delay, - ) - - -class SkippedShipment(proto.Message): - r"""Specifies details of unperformed shipments in a solution. For - trivial cases and/or if we are able to identify the cause for - skipping, we report the reason here. - - Attributes: - index (int): - The index corresponds to the index of the shipment in the - source ``ShipmentModel``. - label (str): - Copy of the corresponding - [Shipment.label][google.cloud.optimization.v1.Shipment.label], - if specified in the ``Shipment``. - reasons (MutableSequence[google.cloud.optimization_v1.types.SkippedShipment.Reason]): - A list of reasons that explain why the shipment was skipped. - See comment above ``Reason``. - """ - - class Reason(proto.Message): - r"""If we can explain why the shipment was skipped, reasons will be - listed here. If the reason is not the same for all vehicles, - ``reason`` will have more than 1 element. A skipped shipment cannot - have duplicate reasons, i.e. where all fields are the same except - for ``example_vehicle_index``. Example: - - :: - - reasons { - code: DEMAND_EXCEEDS_VEHICLE_CAPACITY - example_vehicle_index: 1 - example_exceeded_capacity_type: "Apples" - } - reasons { - code: DEMAND_EXCEEDS_VEHICLE_CAPACITY - example_vehicle_index: 3 - example_exceeded_capacity_type: "Pears" - } - reasons { - code: CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT - example_vehicle_index: 1 - } - - The skipped shipment is incompatible with all vehicles. The reasons - may be different for all vehicles but at least one vehicle's - "Apples" capacity would be exceeded (including vehicle 1), at least - one vehicle's "Pears" capacity would be exceeded (including vehicle - 3) and at least one vehicle's distance limit would be exceeded - (including vehicle 1). - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - code (google.cloud.optimization_v1.types.SkippedShipment.Reason.Code): - Refer to the comments of Code. - example_vehicle_index (int): - If the reason is related to a - shipment-vehicle incompatibility, this field - provides the index of one relevant vehicle. - - This field is a member of `oneof`_ ``_example_vehicle_index``. - example_exceeded_capacity_type (str): - If the reason code is ``DEMAND_EXCEEDS_VEHICLE_CAPACITY``, - documents one capacity type that is exceeded. - """ - class Code(proto.Enum): - r"""Code identifying the reason type. The order here is - meaningless. In particular, it gives no indication of whether a - given reason will appear before another in the solution, if both - apply. - - Values: - CODE_UNSPECIFIED (0): - This should never be used. If we are unable - to understand why a shipment was skipped, we - simply return an empty set of reasons. - NO_VEHICLE (1): - There is no vehicle in the model making all - shipments infeasible. - DEMAND_EXCEEDS_VEHICLE_CAPACITY (2): - The demand of the shipment exceeds a vehicle's capacity for - some capacity types, one of which is - ``example_exceeded_capacity_type``. - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT (3): - The minimum distance necessary to perform this shipment, - i.e. from the vehicle's ``start_location`` to the shipment's - pickup and/or delivery locations and to the vehicle's end - location exceeds the vehicle's ``route_distance_limit``. - - Note that for this computation we use the geodesic - distances. - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT (4): - The minimum time necessary to perform this shipment, - including travel time, wait time and service time exceeds - the vehicle's ``route_duration_limit``. - - Note: travel time is computed in the best-case scenario, - namely as geodesic distance x 36 m/s (roughly 130 km/hour). - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TRAVEL_DURATION_LIMIT (5): - Same as above but we only compare minimum travel time and - the vehicle's ``travel_duration_limit``. - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TIME_WINDOWS (6): - The vehicle cannot perform this shipment in the best-case - scenario (see - ``CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT`` for - time computation) if it starts at its earliest start time: - the total time would make the vehicle end after its latest - end time. - VEHICLE_NOT_ALLOWED (7): - The ``allowed_vehicle_indices`` field of the shipment is not - empty and this vehicle does not belong to it. - """ - CODE_UNSPECIFIED = 0 - NO_VEHICLE = 1 - DEMAND_EXCEEDS_VEHICLE_CAPACITY = 2 - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT = 3 - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT = 4 - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TRAVEL_DURATION_LIMIT = 5 - CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TIME_WINDOWS = 6 - VEHICLE_NOT_ALLOWED = 7 - - code: 'SkippedShipment.Reason.Code' = proto.Field( - proto.ENUM, - number=1, - enum='SkippedShipment.Reason.Code', - ) - example_vehicle_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - example_exceeded_capacity_type: str = proto.Field( - proto.STRING, - number=3, - ) - - index: int = proto.Field( - proto.INT32, - number=1, - ) - label: str = proto.Field( - proto.STRING, - number=2, - ) - reasons: MutableSequence[Reason] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=Reason, - ) - - -class AggregatedMetrics(proto.Message): - r"""Aggregated metrics for - [ShipmentRoute][google.cloud.optimization.v1.ShipmentRoute] (resp. - for - [OptimizeToursResponse][google.cloud.optimization.v1.OptimizeToursResponse] - over all - [Transition][google.cloud.optimization.v1.ShipmentRoute.Transition] - and/or [Visit][google.cloud.optimization.v1.ShipmentRoute.Visit] - (resp. over all - [ShipmentRoute][google.cloud.optimization.v1.ShipmentRoute]) - elements. - - Attributes: - performed_shipment_count (int): - Number of shipments performed. Note that a - pickup and delivery pair only counts once. - travel_duration (google.protobuf.duration_pb2.Duration): - Total travel duration for a route or a - solution. - wait_duration (google.protobuf.duration_pb2.Duration): - Total wait duration for a route or a - solution. - delay_duration (google.protobuf.duration_pb2.Duration): - Total delay duration for a route or a - solution. - break_duration (google.protobuf.duration_pb2.Duration): - Total break duration for a route or a - solution. - visit_duration (google.protobuf.duration_pb2.Duration): - Total visit duration for a route or a - solution. - total_duration (google.protobuf.duration_pb2.Duration): - The total duration should be equal to the sum of all durations above. For routes, it also corresponds to [ShipmentRoute.vehicle_end_time][google.cloud.optimization.v1.ShipmentRoute.vehicle_end_time] - ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ - - [ShipmentRoute.vehicle_start_time][google.cloud.optimization.v1.ShipmentRoute.vehicle_start_time]. - travel_distance_meters (float): - Total travel distance for a route or a - solution. - max_loads (MutableMapping[str, google.cloud.optimization_v1.types.ShipmentRoute.VehicleLoad]): - Maximum load achieved over the entire route (resp. - solution), for each of the quantities on this route (resp. - solution), computed as the maximum over all - [Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads] - (resp. - [ShipmentRoute.metrics.max_loads][google.cloud.optimization.v1.AggregatedMetrics.max_loads]. - costs (MutableMapping[str, float]): - Deprecated: Use - [ShipmentRoute.route_costs][google.cloud.optimization.v1.ShipmentRoute.route_costs] - and - [OptimizeToursResponse.Metrics.costs][google.cloud.optimization.v1.OptimizeToursResponse.Metrics.costs] - instead. - total_cost (float): - Deprecated: Use - [ShipmentRoute.route_total_cost][google.cloud.optimization.v1.ShipmentRoute.route_total_cost] - and - [OptimizeToursResponse.Metrics.total_cost][google.cloud.optimization.v1.OptimizeToursResponse.Metrics.total_cost] - instead. - """ - - performed_shipment_count: int = proto.Field( - proto.INT32, - number=1, - ) - travel_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - wait_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - delay_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - break_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - visit_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - total_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - travel_distance_meters: float = proto.Field( - proto.DOUBLE, - number=8, - ) - max_loads: MutableMapping[str, 'ShipmentRoute.VehicleLoad'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=9, - message='ShipmentRoute.VehicleLoad', - ) - costs: MutableMapping[str, float] = proto.MapField( - proto.STRING, - proto.DOUBLE, - number=10, - ) - total_cost: float = proto.Field( - proto.DOUBLE, - number=11, - ) - - -class InjectedSolutionConstraint(proto.Message): - r"""Solution injected in the request including information about - which visits must be constrained and how they must be - constrained. - - Attributes: - routes (MutableSequence[google.cloud.optimization_v1.types.ShipmentRoute]): - Routes of the solution to inject. Some routes may be omitted - from the original solution. The routes and skipped shipments - must satisfy the basic validity assumptions listed for - ``injected_first_solution_routes``. - skipped_shipments (MutableSequence[google.cloud.optimization_v1.types.SkippedShipment]): - Skipped shipments of the solution to inject. Some may be - omitted from the original solution. See the ``routes`` - field. - constraint_relaxations (MutableSequence[google.cloud.optimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation]): - For zero or more groups of vehicles, - specifies when and how much to relax - constraints. If this field is empty, all - non-empty vehicle routes are fully constrained. - """ - - class ConstraintRelaxation(proto.Message): - r"""For a group of vehicles, specifies at what threshold(s) constraints - on visits will be relaxed and to which level. Shipments listed in - the ``skipped_shipment`` field are constrained to be skipped; i.e., - they cannot be performed. - - Attributes: - relaxations (MutableSequence[google.cloud.optimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation.Relaxation]): - All the visit constraint relaxations that will apply to - visits on routes with vehicles in ``vehicle_indices``. - vehicle_indices (MutableSequence[int]): - Specifies the vehicle indices to which the visit constraint - ``relaxations`` apply. If empty, this is considered the - default and the ``relaxations`` apply to all vehicles that - are not specified in other ``constraint_relaxations``. There - can be at most one default, i.e., at most one constraint - relaxation field is allowed empty ``vehicle_indices``. A - vehicle index can only be listed once, even within several - ``constraint_relaxations``. - - A vehicle index is mapped the same as - [ShipmentRoute.vehicle_index][google.cloud.optimization.v1.ShipmentRoute.vehicle_index], - if ``interpret_injected_solutions_using_labels`` is true - (see ``fields`` comment). - """ - - class Relaxation(proto.Message): - r"""If ``relaxations`` is empty, the start time and sequence of all - visits on ``routes`` are fully constrained and no new visits may be - inserted or added to those routes. Also, a vehicle's start and end - time in ``routes`` is fully constrained, unless the vehicle is empty - (i.e., has no visits and has ``used_if_route_is_empty`` set to false - in the model). - - ``relaxations(i).level`` specifies the constraint relaxation level - applied to a visit #j that satisfies: - - - ``route.visits(j).start_time >= relaxations(i).threshold_time`` - AND - - ``j + 1 >= relaxations(i).threshold_visit_count`` - - Similarly, the vehicle start is relaxed to ``relaxations(i).level`` - if it satisfies: - - - ``vehicle_start_time >= relaxations(i).threshold_time`` AND - - ``relaxations(i).threshold_visit_count == 0`` and the vehicle end - is relaxed to ``relaxations(i).level`` if it satisfies: - - ``vehicle_end_time >= relaxations(i).threshold_time`` AND - - ``route.visits_size() + 1 >= relaxations(i).threshold_visit_count`` - - To apply a relaxation level if a visit meets the - ``threshold_visit_count`` OR the ``threshold_time`` add two - ``relaxations`` with the same ``level``: one with only - ``threshold_visit_count`` set and the other with only - ``threshold_time`` set. If a visit satisfies the conditions of - multiple ``relaxations``, the most relaxed level applies. As a - result, from the vehicle start through the route visits in order to - the vehicle end, the relaxation level becomes more relaxed: i.e., - the relaxation level is non-decreasing as the route progresses. - - The timing and sequence of route visits that do not satisfy the - threshold conditions of any ``relaxations`` are fully constrained - and no visits may be inserted into these sequences. Also, if a - vehicle start or end does not satisfy the conditions of any - relaxation the time is fixed, unless the vehicle is empty. - - Attributes: - level (google.cloud.optimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level): - The constraint relaxation level that applies when the - conditions at or after ``threshold_time`` AND at least - ``threshold_visit_count`` are satisfied. - threshold_time (google.protobuf.timestamp_pb2.Timestamp): - The time at or after which the relaxation ``level`` may be - applied. - threshold_visit_count (int): - The number of visits at or after which the relaxation - ``level`` may be applied. If ``threshold_visit_count`` is 0 - (or unset), the ``level`` may be applied directly at the - vehicle start. - - If it is ``route.visits_size() + 1``, the ``level`` may only - be applied to the vehicle end. If it is more than - ``route.visits_size() + 1``, ``level`` is not applied at all - for that route. - """ - class Level(proto.Enum): - r"""Expresses the different constraint relaxation levels, which - are applied for a visit and those that follow when it satisfies - the threshold conditions. - - The enumeration below is in order of increasing relaxation. - - Values: - LEVEL_UNSPECIFIED (0): - Implicit default relaxation level: no constraints are - relaxed, i.e., all visits are fully constrained. - - This value must not be explicitly used in ``level``. - RELAX_VISIT_TIMES_AFTER_THRESHOLD (1): - Visit start times and vehicle start/end times - will be relaxed, but each visit remains bound to - the same vehicle and the visit sequence must be - observed: no visit can be inserted between them - or before them. - RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD (2): - Same as ``RELAX_VISIT_TIMES_AFTER_THRESHOLD``, but the visit - sequence is also relaxed: visits remain simply bound to - their vehicle. - RELAX_ALL_AFTER_THRESHOLD (3): - Same as ``RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD``, - but the vehicle is also relaxed: visits are completely free - at or after the threshold time and can potentially become - unperformed. - """ - LEVEL_UNSPECIFIED = 0 - RELAX_VISIT_TIMES_AFTER_THRESHOLD = 1 - RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD = 2 - RELAX_ALL_AFTER_THRESHOLD = 3 - - level: 'InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level' = proto.Field( - proto.ENUM, - number=1, - enum='InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level', - ) - threshold_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - threshold_visit_count: int = proto.Field( - proto.INT32, - number=3, - ) - - relaxations: MutableSequence['InjectedSolutionConstraint.ConstraintRelaxation.Relaxation'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='InjectedSolutionConstraint.ConstraintRelaxation.Relaxation', - ) - vehicle_indices: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=2, - ) - - routes: MutableSequence['ShipmentRoute'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ShipmentRoute', - ) - skipped_shipments: MutableSequence['SkippedShipment'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SkippedShipment', - ) - constraint_relaxations: MutableSequence[ConstraintRelaxation] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=ConstraintRelaxation, - ) - - -class OptimizeToursValidationError(proto.Message): - r"""Describes an error encountered when validating an - ``OptimizeToursRequest``. - - Attributes: - code (int): - A validation error is defined by the pair (``code``, - ``display_name``) which are always present. - - Other fields (below) provide more context about the error. - - *MULTIPLE ERRORS*: When there are multiple errors, the - validation process tries to output several of them. Much - like a compiler, this is an imperfect process. Some - validation errors will be "fatal", meaning that they stop - the entire validation process. This is the case for - ``display_name="UNSPECIFIED"`` errors, among others. Some - may cause the validation process to skip other errors. - - *STABILITY*: ``code`` and ``display_name`` should be very - stable. But new codes and display names may appear over - time, which may cause a given (invalid) request to yield a - different (``code``, ``display_name``) pair because the new - error hid the old one (see "MULTIPLE ERRORS"). - - *REFERENCE*: A list of all (code, name) pairs: - - - UNSPECIFIED = 0; - - - VALIDATION_TIMEOUT_ERROR = 10; Validation couldn't be - completed within the deadline. - - - REQUEST_OPTIONS_ERROR = 12; - - - REQUEST_OPTIONS_INVALID_SOLVING_MODE = 1201; - - REQUEST_OPTIONS_INVALID_MAX_VALIDATION_ERRORS = 1203; - - REQUEST_OPTIONS_INVALID_GEODESIC_METERS_PER_SECOND = - 1204; - - REQUEST_OPTIONS_GEODESIC_METERS_PER_SECOND_TOO_SMALL = - 1205; - - REQUEST_OPTIONS_MISSING_GEODESIC_METERS_PER_SECOND = - 1206; - - REQUEST_OPTIONS_POPULATE_PATHFINDER_TRIPS_AND_GEODESIC_DISTANCE - = 1207; - - REQUEST_OPTIONS_COST_MODEL_OPTIONS_AND_GEODESIC_DISTANCE - = 1208; - - REQUEST_OPTIONS_TRAVEL_MODE_INCOMPATIBLE_WITH_TRAFFIC - = 1211; - - REQUEST_OPTIONS_MULTIPLE_TRAFFIC_FLAVORS = 1212; - - REQUEST_OPTIONS_INVALID_TRAFFIC_FLAVOR = 1213; - - REQUEST_OPTIONS_TRAFFIC_ENABLED_WITHOUT_GLOBAL_START_TIME - = 1214; - - REQUEST_OPTIONS_TRAFFIC_ENABLED_WITH_PRECEDENCES = - 1215; - - REQUEST_OPTIONS_TRAFFIC_PREFILL_MODE_INVALID = 1216; - - REQUEST_OPTIONS_TRAFFIC_PREFILL_ENABLED_WITHOUT_TRAFFIC - = 1217; - - - INJECTED_SOLUTION_ERROR = 20; - - - INJECTED_SOLUTION_MISSING_LABEL = 2000; - - INJECTED_SOLUTION_DUPLICATE_LABEL = 2001; - - INJECTED_SOLUTION_AMBIGUOUS_INDEX = 2002; - - INJECTED_SOLUTION_INFEASIBLE_AFTER_GETTING_TRAVEL_TIMES - = 2003; - - INJECTED_SOLUTION_TRANSITION_INCONSISTENT_WITH_ACTUAL_TRAVEL - = 2004; - - INJECTED_SOLUTION_CONCURRENT_SOLUTION_TYPES = 2005; - - INJECTED_SOLUTION_MORE_THAN_ONE_PER_TYPE = 2006; - - INJECTED_SOLUTION_REFRESH_WITHOUT_POPULATE = 2008; - - - SHIPMENT_MODEL_ERROR = 22; - - - SHIPMENT_MODEL_TOO_LARGE = 2200; - - SHIPMENT_MODEL_TOO_MANY_CAPACITY_TYPES = 2201; - - SHIPMENT_MODEL_GLOBAL_START_TIME_NEGATIVE_OR_NAN = - 2202; - - SHIPMENT_MODEL_GLOBAL_END_TIME_TOO_LARGE_OR_NAN = - 2203; - - SHIPMENT_MODEL_GLOBAL_START_TIME_AFTER_GLOBAL_END_TIME - = 2204; - - SHIPMENT_MODEL_GLOBAL_DURATION_TOO_LONG = 2205; - - SHIPMENT_MODEL_MAX_ACTIVE_VEHICLES_NOT_POSITIVE = - 2206; - - SHIPMENT_MODEL_DURATION_MATRIX_TOO_LARGE = 2207; - - - INDEX_ERROR = 24; - - - TAG_ERROR = 26; - - - TIME_WINDOW_ERROR = 28; - - - TIME_WINDOW_INVALID_START_TIME = 2800; - - TIME_WINDOW_INVALID_END_TIME = 2801; - - TIME_WINDOW_INVALID_SOFT_START_TIME = 2802; - - TIME_WINDOW_INVALID_SOFT_END_TIME = 2803; - - TIME_WINDOW_OUTSIDE_GLOBAL_TIME_WINDOW = 2804; - - TIME_WINDOW_START_TIME_AFTER_END_TIME = 2805; - - TIME_WINDOW_INVALID_COST_PER_HOUR_BEFORE_SOFT_START_TIME - = 2806; - - TIME_WINDOW_INVALID_COST_PER_HOUR_AFTER_SOFT_END_TIME - = 2807; - - TIME_WINDOW_COST_BEFORE_SOFT_START_TIME_WITHOUT_SOFT_START_TIME - = 2808; - - TIME_WINDOW_COST_AFTER_SOFT_END_TIME_WITHOUT_SOFT_END_TIME - = 2809; - - TIME_WINDOW_SOFT_START_TIME_WITHOUT_COST_BEFORE_SOFT_START_TIME - = 2810; - - TIME_WINDOW_SOFT_END_TIME_WITHOUT_COST_AFTER_SOFT_END_TIME - = 2811; - - TIME_WINDOW_OVERLAPPING_ADJACENT_OR_EARLIER_THAN_PREVIOUS - = 2812; - - TIME_WINDOW_START_TIME_AFTER_SOFT_START_TIME = 2813; - - TIME_WINDOW_SOFT_START_TIME_AFTER_END_TIME = 2814; - - TIME_WINDOW_START_TIME_AFTER_SOFT_END_TIME = 2815; - - TIME_WINDOW_SOFT_END_TIME_AFTER_END_TIME = 2816; - - TIME_WINDOW_COST_BEFORE_SOFT_START_TIME_SET_AND_MULTIPLE_WINDOWS - = 2817; - - TIME_WINDOW_COST_AFTER_SOFT_END_TIME_SET_AND_MULTIPLE_WINDOWS - = 2818; - - TRANSITION_ATTRIBUTES_ERROR = 30; - - TRANSITION_ATTRIBUTES_INVALID_COST = 3000; - - TRANSITION_ATTRIBUTES_INVALID_COST_PER_KILOMETER = - 3001; - - TRANSITION_ATTRIBUTES_DUPLICATE_TAG_PAIR = 3002; - - TRANSITION_ATTRIBUTES_DISTANCE_LIMIT_MAX_METERS_UNSUPPORTED - = 3003; - - TRANSITION_ATTRIBUTES_UNSPECIFIED_SOURCE_TAGS = 3004; - - TRANSITION_ATTRIBUTES_CONFLICTING_SOURCE_TAGS_FIELDS = - 3005; - - TRANSITION_ATTRIBUTES_UNSPECIFIED_DESTINATION_TAGS = - 3006; - - TRANSITION_ATTRIBUTES_CONFLICTING_DESTINATION_TAGS_FIELDS - = 3007; - - TRANSITION_ATTRIBUTES_DELAY_DURATION_NEGATIVE_OR_NAN = - 3008; - - TRANSITION_ATTRIBUTES_DELAY_DURATION_EXCEEDS_GLOBAL_DURATION - = 3009; - - - AMOUNT_ERROR = 31; - - - AMOUNT_NEGATIVE_VALUE = 3100; - - - LOAD_LIMIT_ERROR = 33; - - - LOAD_LIMIT_INVALID_COST_ABOVE_SOFT_MAX = 3303; - - LOAD_LIMIT_SOFT_MAX_WITHOUT_COST_ABOVE_SOFT_MAX = - 3304; - - LOAD_LIMIT_COST_ABOVE_SOFT_MAX_WITHOUT_SOFT_MAX = - 3305; - - LOAD_LIMIT_NEGATIVE_SOFT_MAX = 3306; - - LOAD_LIMIT_MIXED_DEMAND_TYPE = 3307; - - LOAD_LIMIT_MAX_LOAD_NEGATIVE_VALUE = 3308; - - LOAD_LIMIT_SOFT_MAX_ABOVE_MAX = 3309; - - - INTERVAL_ERROR = 34; - - - INTERVAL_MIN_EXCEEDS_MAX = 3401; - - INTERVAL_NEGATIVE_MIN = 3402; - - INTERVAL_NEGATIVE_MAX = 3403; - - INTERVAL_MIN_EXCEEDS_CAPACITY = 3404; - - INTERVAL_MAX_EXCEEDS_CAPACITY = 3405; - - - DISTANCE_LIMIT_ERROR = 36; - - - DISTANCE_LIMIT_INVALID_COST_AFTER_SOFT_MAX = 3601; - - DISTANCE_LIMIT_SOFT_MAX_WITHOUT_COST_AFTER_SOFT_MAX = - 3602; - - DISTANCE_LIMIT_COST_AFTER_SOFT_MAX_WITHOUT_SOFT_MAX = - 3603; - - DISTANCE_LIMIT_NEGATIVE_MAX = 3604; - - DISTANCE_LIMIT_NEGATIVE_SOFT_MAX = 3605; - - DISTANCE_LIMIT_SOFT_MAX_LARGER_THAN_MAX = 3606; - - - DURATION_LIMIT_ERROR = 38; - - - DURATION_LIMIT_MAX_DURATION_NEGATIVE_OR_NAN = 3800; - - DURATION_LIMIT_SOFT_MAX_DURATION_NEGATIVE_OR_NAN = - 3801; - - DURATION_LIMIT_INVALID_COST_PER_HOUR_AFTER_SOFT_MAX = - 3802; - - DURATION_LIMIT_SOFT_MAX_WITHOUT_COST_AFTER_SOFT_MAX = - 3803; - - DURATION_LIMIT_COST_AFTER_SOFT_MAX_WITHOUT_SOFT_MAX = - 3804; - - DURATION_LIMIT_QUADRATIC_SOFT_MAX_DURATION_NEGATIVE_OR_NAN - = 3805; - - DURATION_LIMIT_INVALID_COST_AFTER_QUADRATIC_SOFT_MAX = - 3806; - - DURATION_LIMIT_QUADRATIC_SOFT_MAX_WITHOUT_COST_PER_SQUARE_HOUR - = 3807; - - DURATION_LIMIT_COST_PER_SQUARE_HOUR_WITHOUT_QUADRATIC_SOFT_MAX - = 3808; - - DURATION_LIMIT_QUADRATIC_SOFT_MAX_WITHOUT_MAX = 3809; - - DURATION_LIMIT_SOFT_MAX_LARGER_THAN_MAX = 3810; - - DURATION_LIMIT_QUADRATIC_SOFT_MAX_LARGER_THAN_MAX = - 3811; - - DURATION_LIMIT_DIFF_BETWEEN_MAX_AND_QUADRATIC_SOFT_MAX_TOO_LARGE - = 3812; - - DURATION_LIMIT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION = - 3813; - - DURATION_LIMIT_SOFT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION - = 3814; - - DURATION_LIMIT_QUADRATIC_SOFT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION - = 3815; - - - SHIPMENT_ERROR = 40; - - - SHIPMENT_PD_LIMIT_WITHOUT_PICKUP_AND_DELIVERY = 4014; - - SHIPMENT_PD_ABSOLUTE_DETOUR_LIMIT_DURATION_NEGATIVE_OR_NAN - = 4000; - - SHIPMENT_PD_ABSOLUTE_DETOUR_LIMIT_DURATION_EXCEEDS_GLOBAL_DURATION - = 4001; - - SHIPMENT_PD_RELATIVE_DETOUR_LIMIT_INVALID = 4015; - - SHIPMENT_PD_DETOUR_LIMIT_AND_EXTRA_VISIT_DURATION = - 4016; - - SHIPMENT_PD_TIME_LIMIT_DURATION_NEGATIVE_OR_NAN = - 4002; - - SHIPMENT_PD_TIME_LIMIT_DURATION_EXCEEDS_GLOBAL_DURATION - = 4003; - - SHIPMENT_EMPTY_SHIPMENT_TYPE = 4004; - - SHIPMENT_NO_PICKUP_NO_DELIVERY = 4005; - - SHIPMENT_INVALID_PENALTY_COST = 4006; - - SHIPMENT_ALLOWED_VEHICLE_INDEX_OUT_OF_BOUNDS = 4007; - - SHIPMENT_DUPLICATE_ALLOWED_VEHICLE_INDEX = 4008; - - SHIPMENT_INCONSISTENT_COST_FOR_VEHICLE_SIZE_WITHOUT_INDEX - = 4009; - - SHIPMENT_INCONSISTENT_COST_FOR_VEHICLE_SIZE_WITH_INDEX - = 4010; - - SHIPMENT_INVALID_COST_FOR_VEHICLE = 4011; - - SHIPMENT_COST_FOR_VEHICLE_INDEX_OUT_OF_BOUNDS = 4012; - - SHIPMENT_DUPLICATE_COST_FOR_VEHICLE_INDEX = 4013; - - - VEHICLE_ERROR = 42; - - - VEHICLE_EMPTY_REQUIRED_OPERATOR_TYPE = 4200; - - VEHICLE_DUPLICATE_REQUIRED_OPERATOR_TYPE = 4201; - - VEHICLE_NO_OPERATOR_WITH_REQUIRED_OPERATOR_TYPE = - 4202; - - VEHICLE_EMPTY_START_TAG = 4203; - - VEHICLE_DUPLICATE_START_TAG = 4204; - - VEHICLE_EMPTY_END_TAG = 4205; - - VEHICLE_DUPLICATE_END_TAG = 4206; - - VEHICLE_EXTRA_VISIT_DURATION_NEGATIVE_OR_NAN = 4207; - - VEHICLE_EXTRA_VISIT_DURATION_EXCEEDS_GLOBAL_DURATION = - 4208; - - VEHICLE_EXTRA_VISIT_DURATION_EMPTY_KEY = 4209; - - VEHICLE_FIRST_SHIPMENT_INDEX_OUT_OF_BOUNDS = 4210; - - VEHICLE_FIRST_SHIPMENT_IGNORED = 4211; - - VEHICLE_FIRST_SHIPMENT_NOT_BOUND = 4212; - - VEHICLE_LAST_SHIPMENT_INDEX_OUT_OF_BOUNDS = 4213; - - VEHICLE_LAST_SHIPMENT_IGNORED = 4214; - - VEHICLE_LAST_SHIPMENT_NOT_BOUND = 4215; - - VEHICLE_IGNORED_WITH_USED_IF_ROUTE_IS_EMPTY = 4216; - - VEHICLE_INVALID_COST_PER_KILOMETER = 4217; - - VEHICLE_INVALID_COST_PER_HOUR = 4218; - - VEHICLE_INVALID_COST_PER_TRAVELED_HOUR = 4219; - - VEHICLE_INVALID_FIXED_COST = 4220; - - VEHICLE_INVALID_TRAVEL_DURATION_MULTIPLE = 4221; - - VEHICLE_TRAVEL_DURATION_MULTIPLE_WITH_SHIPMENT_PD_DETOUR_LIMITS - = 4223; - - VEHICLE_MATRIX_INDEX_WITH_SHIPMENT_PD_DETOUR_LIMITS = - 4224; - - VEHICLE_MINIMUM_DURATION_LONGER_THAN_DURATION_LIMIT = - 4222; - - - VISIT_REQUEST_ERROR = 44; - - - VISIT_REQUEST_EMPTY_TAG = 4400; - - VISIT_REQUEST_DUPLICATE_TAG = 4401; - - VISIT_REQUEST_DURATION_NEGATIVE_OR_NAN = 4404; - - VISIT_REQUEST_DURATION_EXCEEDS_GLOBAL_DURATION = 4405; - - - PRECEDENCE_ERROR = 46; - - - BREAK_ERROR = 48; - - - BREAK_RULE_EMPTY = 4800; - - BREAK_REQUEST_UNSPECIFIED_DURATION = 4801; - - BREAK_REQUEST_UNSPECIFIED_EARLIEST_START_TIME = 4802; - - BREAK_REQUEST_UNSPECIFIED_LATEST_START_TIME = 4803; - - BREAK_REQUEST_DURATION_NEGATIVE_OR_NAN = 4804; = 4804; - - BREAK_REQUEST_LATEST_START_TIME_BEFORE_EARLIEST_START_TIME - = 4805; - - BREAK_REQUEST_EARLIEST_START_TIME_BEFORE_GLOBAL_START_TIME - = 4806; - - BREAK_REQUEST_LATEST_END_TIME_AFTER_GLOBAL_END_TIME = - 4807; - - BREAK_REQUEST_NON_SCHEDULABLE = 4808; - - BREAK_FREQUENCY_MAX_INTER_BREAK_DURATION_NEGATIVE_OR_NAN - = 4809; - - BREAK_FREQUENCY_MIN_BREAK_DURATION_NEGATIVE_OR_NAN = - 4810; - - BREAK_FREQUENCY_MIN_BREAK_DURATION_EXCEEDS_GLOBAL_DURATION - = 4811; - - BREAK_FREQUENCY_MAX_INTER_BREAK_DURATION_EXCEEDS_GLOBAL_DURATION - = 4812; - - BREAK_REQUEST_DURATION_EXCEEDS_GLOBAL_DURATION = 4813; - - BREAK_FREQUENCY_MISSING_MAX_INTER_BREAK_DURATION = - 4814; - - BREAK_FREQUENCY_MISSING_MIN_BREAK_DURATION = 4815; - - - SHIPMENT_TYPE_INCOMPATIBILITY_ERROR = 50; - - - SHIPMENT_TYPE_INCOMPATIBILITY_EMPTY_TYPE = 5001; - - SHIPMENT_TYPE_INCOMPATIBILITY_LESS_THAN_TWO_TYPES = - 5002; - - SHIPMENT_TYPE_INCOMPATIBILITY_DUPLICATE_TYPE = 5003; - - SHIPMENT_TYPE_INCOMPATIBILITY_INVALID_INCOMPATIBILITY_MODE - = 5004; - - SHIPMENT_TYPE_INCOMPATIBILITY_TOO_MANY_INCOMPATIBILITIES - = 5005; - - - SHIPMENT_TYPE_REQUIREMENT_ERROR = 52; - - - SHIPMENT_TYPE_REQUIREMENT_NO_REQUIRED_TYPE = 52001; - - SHIPMENT_TYPE_REQUIREMENT_NO_DEPENDENT_TYPE = 52002; - - SHIPMENT_TYPE_REQUIREMENT_INVALID_REQUIREMENT_MODE = - 52003; - - SHIPMENT_TYPE_REQUIREMENT_TOO_MANY_REQUIREMENTS = - 52004; - - SHIPMENT_TYPE_REQUIREMENT_EMPTY_REQUIRED_TYPE = 52005; - - SHIPMENT_TYPE_REQUIREMENT_DUPLICATE_REQUIRED_TYPE = - 52006; - - SHIPMENT_TYPE_REQUIREMENT_NO_REQUIRED_TYPE_FOUND = - 52007; - - SHIPMENT_TYPE_REQUIREMENT_EMPTY_DEPENDENT_TYPE = - 52008; - - SHIPMENT_TYPE_REQUIREMENT_DUPLICATE_DEPENDENT_TYPE = - 52009; - - SHIPMENT_TYPE_REQUIREMENT_SELF_DEPENDENT_TYPE = 52010; - - SHIPMENT_TYPE_REQUIREMENT_GRAPH_HAS_CYCLES = 52011; - - - VEHICLE_OPERATOR_ERROR = 54; - - - VEHICLE_OPERATOR_EMPTY_TYPE = 5400; - - VEHICLE_OPERATOR_MULTIPLE_START_TIME_WINDOWS = 5401; - - VEHICLE_OPERATOR_SOFT_START_TIME_WINDOW = 5402; - - VEHICLE_OPERATOR_MULTIPLE_END_TIME_WINDOWS = 5403; - - VEHICLE_OPERATOR_SOFT_END_TIME_WINDOW = 5404; - - - DURATION_SECONDS_MATRIX_ERROR = 56; - - - DURATION_SECONDS_MATRIX_DURATION_NEGATIVE_OR_NAN = - 5600; - - DURATION_SECONDS_MATRIX_DURATION_EXCEEDS_GLOBAL_DURATION - = 5601; - display_name (str): - The error display name. - fields (MutableSequence[google.cloud.optimization_v1.types.OptimizeToursValidationError.FieldReference]): - An error context may involve 0, 1 (most of the time) or more - fields. For example, referring to vehicle #4 and shipment - #2's first pickup can be done as follows: - - :: - - fields { name: "vehicles" index: 4} - fields { name: "shipments" index: 2 sub_field {name: "pickups" index: 0} } - - Note, however, that the cardinality of ``fields`` should not - change for a given error code. - error_message (str): - Human-readable string describing the error. There is a 1:1 - mapping between ``code`` and ``error_message`` (when code != - "UNSPECIFIED"). - - *STABILITY*: Not stable: the error message associated to a - given ``code`` may change (hopefully to clarify it) over - time. Please rely on the ``display_name`` and ``code`` - instead. - offending_values (str): - May contain the value(s) of the field(s). - This is not always available. You should - absolutely not rely on it and use it only for - manual model debugging. - """ - - class FieldReference(proto.Message): - r"""Specifies a context for the validation error. A ``FieldReference`` - always refers to a given field in this file and follows the same - hierarchical structure. For example, we may specify element #2 of - ``start_time_windows`` of vehicle #5 using: - - :: - - name: "vehicles" index: 5 sub_field { name: "end_time_windows" index: 2 } - - We however omit top-level entities such as ``OptimizeToursRequest`` - or ``ShipmentModel`` to avoid crowding the message. - - 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): - Name of the field, e.g., "vehicles". - index (int): - Index of the field if repeated. - - This field is a member of `oneof`_ ``index_or_key``. - key (str): - Key if the field is a map. - - This field is a member of `oneof`_ ``index_or_key``. - sub_field (google.cloud.optimization_v1.types.OptimizeToursValidationError.FieldReference): - Recursively nested sub-field, if needed. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - index: int = proto.Field( - proto.INT32, - number=2, - oneof='index_or_key', - ) - key: str = proto.Field( - proto.STRING, - number=4, - oneof='index_or_key', - ) - sub_field: 'OptimizeToursValidationError.FieldReference' = proto.Field( - proto.MESSAGE, - number=3, - message='OptimizeToursValidationError.FieldReference', - ) - - code: int = proto.Field( - proto.INT32, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - fields: MutableSequence[FieldReference] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=FieldReference, - ) - error_message: str = proto.Field( - proto.STRING, - number=4, - ) - offending_values: str = proto.Field( - proto.STRING, - number=5, - ) - - -__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 67a0b27..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/optimization_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/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_async.py deleted file mode 100644 index f091826..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_async.py +++ /dev/null @@ -1,61 +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 BatchOptimizeTours -# 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-optimization - - -# [START cloudoptimization_v1_generated_FleetRouting_BatchOptimizeTours_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 optimization_v1 - - -async def sample_batch_optimize_tours(): - # Create a client - client = optimization_v1.FleetRoutingAsyncClient() - - # Initialize request argument(s) - model_configs = optimization_v1.AsyncModelConfig() - model_configs.input_config.gcs_source.uri = "uri_value" - model_configs.output_config.gcs_destination.uri = "uri_value" - - request = optimization_v1.BatchOptimizeToursRequest( - parent="parent_value", - model_configs=model_configs, - ) - - # Make the request - operation = client.batch_optimize_tours(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudoptimization_v1_generated_FleetRouting_BatchOptimizeTours_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_sync.py deleted file mode 100644 index 7750123..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_sync.py +++ /dev/null @@ -1,61 +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 BatchOptimizeTours -# 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-optimization - - -# [START cloudoptimization_v1_generated_FleetRouting_BatchOptimizeTours_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 optimization_v1 - - -def sample_batch_optimize_tours(): - # Create a client - client = optimization_v1.FleetRoutingClient() - - # Initialize request argument(s) - model_configs = optimization_v1.AsyncModelConfig() - model_configs.input_config.gcs_source.uri = "uri_value" - model_configs.output_config.gcs_destination.uri = "uri_value" - - request = optimization_v1.BatchOptimizeToursRequest( - parent="parent_value", - model_configs=model_configs, - ) - - # Make the request - operation = client.batch_optimize_tours(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudoptimization_v1_generated_FleetRouting_BatchOptimizeTours_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_async.py deleted file mode 100644 index 1ff26eb..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_async.py +++ /dev/null @@ -1,52 +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 OptimizeTours -# 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-optimization - - -# [START cloudoptimization_v1_generated_FleetRouting_OptimizeTours_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 optimization_v1 - - -async def sample_optimize_tours(): - # Create a client - client = optimization_v1.FleetRoutingAsyncClient() - - # Initialize request argument(s) - request = optimization_v1.OptimizeToursRequest( - parent="parent_value", - ) - - # Make the request - response = await client.optimize_tours(request=request) - - # Handle the response - print(response) - -# [END cloudoptimization_v1_generated_FleetRouting_OptimizeTours_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_sync.py deleted file mode 100644 index a0e4335..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudoptimization_v1_generated_fleet_routing_optimize_tours_sync.py +++ /dev/null @@ -1,52 +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 OptimizeTours -# 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-optimization - - -# [START cloudoptimization_v1_generated_FleetRouting_OptimizeTours_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 optimization_v1 - - -def sample_optimize_tours(): - # Create a client - client = optimization_v1.FleetRoutingClient() - - # Initialize request argument(s) - request = optimization_v1.OptimizeToursRequest( - parent="parent_value", - ) - - # Make the request - response = client.optimize_tours(request=request) - - # Handle the response - print(response) - -# [END cloudoptimization_v1_generated_FleetRouting_OptimizeTours_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.optimization.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.optimization.v1.json deleted file mode 100644 index d38082d..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.optimization.v1.json +++ /dev/null @@ -1,321 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.optimization.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-optimization", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.optimization_v1.FleetRoutingAsyncClient", - "shortName": "FleetRoutingAsyncClient" - }, - "fullName": "google.cloud.optimization_v1.FleetRoutingAsyncClient.batch_optimize_tours", - "method": { - "fullName": "google.cloud.optimization.v1.FleetRouting.BatchOptimizeTours", - "service": { - "fullName": "google.cloud.optimization.v1.FleetRouting", - "shortName": "FleetRouting" - }, - "shortName": "BatchOptimizeTours" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.optimization_v1.types.BatchOptimizeToursRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_optimize_tours" - }, - "description": "Sample for BatchOptimizeTours", - "file": "cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudoptimization_v1_generated_FleetRouting_BatchOptimizeTours_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.optimization_v1.FleetRoutingClient", - "shortName": "FleetRoutingClient" - }, - "fullName": "google.cloud.optimization_v1.FleetRoutingClient.batch_optimize_tours", - "method": { - "fullName": "google.cloud.optimization.v1.FleetRouting.BatchOptimizeTours", - "service": { - "fullName": "google.cloud.optimization.v1.FleetRouting", - "shortName": "FleetRouting" - }, - "shortName": "BatchOptimizeTours" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.optimization_v1.types.BatchOptimizeToursRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_optimize_tours" - }, - "description": "Sample for BatchOptimizeTours", - "file": "cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudoptimization_v1_generated_FleetRouting_BatchOptimizeTours_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudoptimization_v1_generated_fleet_routing_batch_optimize_tours_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.optimization_v1.FleetRoutingAsyncClient", - "shortName": "FleetRoutingAsyncClient" - }, - "fullName": "google.cloud.optimization_v1.FleetRoutingAsyncClient.optimize_tours", - "method": { - "fullName": "google.cloud.optimization.v1.FleetRouting.OptimizeTours", - "service": { - "fullName": "google.cloud.optimization.v1.FleetRouting", - "shortName": "FleetRouting" - }, - "shortName": "OptimizeTours" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.optimization_v1.types.OptimizeToursRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.optimization_v1.types.OptimizeToursResponse", - "shortName": "optimize_tours" - }, - "description": "Sample for OptimizeTours", - "file": "cloudoptimization_v1_generated_fleet_routing_optimize_tours_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudoptimization_v1_generated_FleetRouting_OptimizeTours_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudoptimization_v1_generated_fleet_routing_optimize_tours_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.optimization_v1.FleetRoutingClient", - "shortName": "FleetRoutingClient" - }, - "fullName": "google.cloud.optimization_v1.FleetRoutingClient.optimize_tours", - "method": { - "fullName": "google.cloud.optimization.v1.FleetRouting.OptimizeTours", - "service": { - "fullName": "google.cloud.optimization.v1.FleetRouting", - "shortName": "FleetRouting" - }, - "shortName": "OptimizeTours" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.optimization_v1.types.OptimizeToursRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.optimization_v1.types.OptimizeToursResponse", - "shortName": "optimize_tours" - }, - "description": "Sample for OptimizeTours", - "file": "cloudoptimization_v1_generated_fleet_routing_optimize_tours_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudoptimization_v1_generated_FleetRouting_OptimizeTours_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudoptimization_v1_generated_fleet_routing_optimize_tours_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1/scripts/fixup_optimization_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_optimization_v1_keywords.py deleted file mode 100644 index 514f7ab..0000000 --- a/owl-bot-staging/v1/scripts/fixup_optimization_v1_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 optimizationCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_optimize_tours': ('parent', 'model_configs', ), - 'optimize_tours': ('parent', 'timeout', 'model', 'solving_mode', 'max_validation_errors', 'search_mode', 'injected_first_solution_routes', 'injected_solution_constraint', 'refresh_details_routes', 'interpret_injected_solutions_using_labels', 'consider_road_traffic', 'populate_polylines', 'populate_transition_polylines', 'allow_large_deadline_despite_interruption_risk', 'use_geodesic_distances', 'geodesic_meters_per_second', 'label', 'populate_travel_step_polylines', ), - } - - 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=optimizationCallTransformer(), -): - """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 optimization 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 bb1428d..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-optimization' - - -description = "Google Cloud Optimization API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/optimization/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-optimization" - -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/optimization_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/optimization_v1/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/optimization_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/optimization_v1/test_fleet_routing.py b/owl-bot-staging/v1/tests/unit/gapic/optimization_v1/test_fleet_routing.py deleted file mode 100644 index 1c94671..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/optimization_v1/test_fleet_routing.py +++ /dev/null @@ -1,2104 +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 future -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 operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.optimization_v1.services.fleet_routing import FleetRoutingAsyncClient -from google.cloud.optimization_v1.services.fleet_routing import FleetRoutingClient -from google.cloud.optimization_v1.services.fleet_routing import transports -from google.cloud.optimization_v1.types import async_model -from google.cloud.optimization_v1.types import fleet_routing -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import latlng_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 FleetRoutingClient._get_default_mtls_endpoint(None) is None - assert FleetRoutingClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert FleetRoutingClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert FleetRoutingClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert FleetRoutingClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert FleetRoutingClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (FleetRoutingClient, "grpc"), - (FleetRoutingAsyncClient, "grpc_asyncio"), - (FleetRoutingClient, "rest"), -]) -def test_fleet_routing_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 == ( - 'cloudoptimization.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudoptimization.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.FleetRoutingGrpcTransport, "grpc"), - (transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.FleetRoutingRestTransport, "rest"), -]) -def test_fleet_routing_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", [ - (FleetRoutingClient, "grpc"), - (FleetRoutingAsyncClient, "grpc_asyncio"), - (FleetRoutingClient, "rest"), -]) -def test_fleet_routing_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 == ( - 'cloudoptimization.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudoptimization.googleapis.com' - ) - - -def test_fleet_routing_client_get_transport_class(): - transport = FleetRoutingClient.get_transport_class() - available_transports = [ - transports.FleetRoutingGrpcTransport, - transports.FleetRoutingRestTransport, - ] - assert transport in available_transports - - transport = FleetRoutingClient.get_transport_class("grpc") - assert transport == transports.FleetRoutingGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FleetRoutingClient, transports.FleetRoutingGrpcTransport, "grpc"), - (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio"), - (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest"), -]) -@mock.patch.object(FleetRoutingClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FleetRoutingClient)) -@mock.patch.object(FleetRoutingAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FleetRoutingAsyncClient)) -def test_fleet_routing_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(FleetRoutingClient, '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(FleetRoutingClient, '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", [ - (FleetRoutingClient, transports.FleetRoutingGrpcTransport, "grpc", "true"), - (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (FleetRoutingClient, transports.FleetRoutingGrpcTransport, "grpc", "false"), - (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest", "true"), - (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest", "false"), -]) -@mock.patch.object(FleetRoutingClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FleetRoutingClient)) -@mock.patch.object(FleetRoutingAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FleetRoutingAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_fleet_routing_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", [ - FleetRoutingClient, FleetRoutingAsyncClient -]) -@mock.patch.object(FleetRoutingClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FleetRoutingClient)) -@mock.patch.object(FleetRoutingAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FleetRoutingAsyncClient)) -def test_fleet_routing_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", [ - (FleetRoutingClient, transports.FleetRoutingGrpcTransport, "grpc"), - (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio"), - (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest"), -]) -def test_fleet_routing_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", [ - (FleetRoutingClient, transports.FleetRoutingGrpcTransport, "grpc", grpc_helpers), - (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest", None), -]) -def test_fleet_routing_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_fleet_routing_client_client_options_from_dict(): - with mock.patch('google.cloud.optimization_v1.services.fleet_routing.transports.FleetRoutingGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = FleetRoutingClient( - 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", [ - (FleetRoutingClient, transports.FleetRoutingGrpcTransport, "grpc", grpc_helpers), - (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_fleet_routing_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( - "cloudoptimization.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="cloudoptimization.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - fleet_routing.OptimizeToursRequest, - dict, -]) -def test_optimize_tours(request_type, transport: str = 'grpc'): - client = FleetRoutingClient( - 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.optimize_tours), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = fleet_routing.OptimizeToursResponse( - request_label='request_label_value', - total_cost=0.10840000000000001, - ) - response = client.optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == fleet_routing.OptimizeToursRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, fleet_routing.OptimizeToursResponse) - assert response.request_label == 'request_label_value' - assert math.isclose(response.total_cost, 0.10840000000000001, rel_tol=1e-6) - - -def test_optimize_tours_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 = FleetRoutingClient( - 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.optimize_tours), - '__call__') as call: - client.optimize_tours() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == fleet_routing.OptimizeToursRequest() - -@pytest.mark.asyncio -async def test_optimize_tours_async(transport: str = 'grpc_asyncio', request_type=fleet_routing.OptimizeToursRequest): - client = FleetRoutingAsyncClient( - 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.optimize_tours), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(fleet_routing.OptimizeToursResponse( - request_label='request_label_value', - total_cost=0.10840000000000001, - )) - response = await client.optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == fleet_routing.OptimizeToursRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, fleet_routing.OptimizeToursResponse) - assert response.request_label == 'request_label_value' - assert math.isclose(response.total_cost, 0.10840000000000001, rel_tol=1e-6) - - -@pytest.mark.asyncio -async def test_optimize_tours_async_from_dict(): - await test_optimize_tours_async(request_type=dict) - - -def test_optimize_tours_field_headers(): - client = FleetRoutingClient( - 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 = fleet_routing.OptimizeToursRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.optimize_tours), - '__call__') as call: - call.return_value = fleet_routing.OptimizeToursResponse() - client.optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_optimize_tours_field_headers_async(): - client = FleetRoutingAsyncClient( - 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 = fleet_routing.OptimizeToursRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.optimize_tours), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fleet_routing.OptimizeToursResponse()) - await client.optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - fleet_routing.BatchOptimizeToursRequest, - dict, -]) -def test_batch_optimize_tours(request_type, transport: str = 'grpc'): - client = FleetRoutingClient( - 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.batch_optimize_tours), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.batch_optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == fleet_routing.BatchOptimizeToursRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_batch_optimize_tours_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 = FleetRoutingClient( - 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.batch_optimize_tours), - '__call__') as call: - client.batch_optimize_tours() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == fleet_routing.BatchOptimizeToursRequest() - -@pytest.mark.asyncio -async def test_batch_optimize_tours_async(transport: str = 'grpc_asyncio', request_type=fleet_routing.BatchOptimizeToursRequest): - client = FleetRoutingAsyncClient( - 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.batch_optimize_tours), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.batch_optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == fleet_routing.BatchOptimizeToursRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_optimize_tours_async_from_dict(): - await test_batch_optimize_tours_async(request_type=dict) - - -def test_batch_optimize_tours_field_headers(): - client = FleetRoutingClient( - 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 = fleet_routing.BatchOptimizeToursRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_optimize_tours), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.batch_optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_batch_optimize_tours_field_headers_async(): - client = FleetRoutingAsyncClient( - 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 = fleet_routing.BatchOptimizeToursRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_optimize_tours), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.batch_optimize_tours(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - fleet_routing.OptimizeToursRequest, - dict, -]) -def test_optimize_tours_rest(request_type): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - 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 = fleet_routing.OptimizeToursResponse( - request_label='request_label_value', - total_cost=0.10840000000000001, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = fleet_routing.OptimizeToursResponse.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.optimize_tours(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, fleet_routing.OptimizeToursResponse) - assert response.request_label == 'request_label_value' - assert math.isclose(response.total_cost, 0.10840000000000001, rel_tol=1e-6) - - -def test_optimize_tours_rest_required_fields(request_type=fleet_routing.OptimizeToursRequest): - transport_class = transports.FleetRoutingRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).optimize_tours._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).optimize_tours._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = fleet_routing.OptimizeToursResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = fleet_routing.OptimizeToursResponse.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.optimize_tours(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_optimize_tours_rest_unset_required_fields(): - transport = transports.FleetRoutingRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.optimize_tours._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_optimize_tours_rest_interceptors(null_interceptor): - transport = transports.FleetRoutingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FleetRoutingRestInterceptor(), - ) - client = FleetRoutingClient(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.FleetRoutingRestInterceptor, "post_optimize_tours") as post, \ - mock.patch.object(transports.FleetRoutingRestInterceptor, "pre_optimize_tours") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = fleet_routing.OptimizeToursRequest.pb(fleet_routing.OptimizeToursRequest()) - 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 = fleet_routing.OptimizeToursResponse.to_json(fleet_routing.OptimizeToursResponse()) - - request = fleet_routing.OptimizeToursRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = fleet_routing.OptimizeToursResponse() - - client.optimize_tours(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_optimize_tours_rest_bad_request(transport: str = 'rest', request_type=fleet_routing.OptimizeToursRequest): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - 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.optimize_tours(request) - - -def test_optimize_tours_rest_error(): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - fleet_routing.BatchOptimizeToursRequest, - dict, -]) -def test_batch_optimize_tours_rest(request_type): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - 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 = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_optimize_tours(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_optimize_tours_rest_required_fields(request_type=fleet_routing.BatchOptimizeToursRequest): - transport_class = transports.FleetRoutingRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_optimize_tours._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_optimize_tours._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_optimize_tours(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_optimize_tours_rest_unset_required_fields(): - transport = transports.FleetRoutingRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_optimize_tours._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "modelConfigs", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_optimize_tours_rest_interceptors(null_interceptor): - transport = transports.FleetRoutingRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FleetRoutingRestInterceptor(), - ) - client = FleetRoutingClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.FleetRoutingRestInterceptor, "post_batch_optimize_tours") as post, \ - mock.patch.object(transports.FleetRoutingRestInterceptor, "pre_batch_optimize_tours") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = fleet_routing.BatchOptimizeToursRequest.pb(fleet_routing.BatchOptimizeToursRequest()) - 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 = json_format.MessageToJson(operations_pb2.Operation()) - - request = fleet_routing.BatchOptimizeToursRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_optimize_tours(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_optimize_tours_rest_bad_request(transport: str = 'rest', request_type=fleet_routing.BatchOptimizeToursRequest): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - 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.batch_optimize_tours(request) - - -def test_batch_optimize_tours_rest_error(): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.FleetRoutingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.FleetRoutingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FleetRoutingClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.FleetRoutingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = FleetRoutingClient( - 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 = FleetRoutingClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.FleetRoutingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FleetRoutingClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.FleetRoutingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = FleetRoutingClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.FleetRoutingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.FleetRoutingGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.FleetRoutingGrpcTransport, - transports.FleetRoutingGrpcAsyncIOTransport, - transports.FleetRoutingRestTransport, -]) -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 = FleetRoutingClient.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 = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.FleetRoutingGrpcTransport, - ) - -def test_fleet_routing_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.FleetRoutingTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_fleet_routing_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.optimization_v1.services.fleet_routing.transports.FleetRoutingTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.FleetRoutingTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'optimize_tours', - 'batch_optimize_tours', - 'get_operation', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_fleet_routing_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.optimization_v1.services.fleet_routing.transports.FleetRoutingTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FleetRoutingTransport( - 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', -), - quota_project_id="octopus", - ) - - -def test_fleet_routing_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.optimization_v1.services.fleet_routing.transports.FleetRoutingTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FleetRoutingTransport() - adc.assert_called_once() - - -def test_fleet_routing_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) - FleetRoutingClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.FleetRoutingGrpcTransport, - transports.FleetRoutingGrpcAsyncIOTransport, - ], -) -def test_fleet_routing_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',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.FleetRoutingGrpcTransport, - transports.FleetRoutingGrpcAsyncIOTransport, - transports.FleetRoutingRestTransport, - ], -) -def test_fleet_routing_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.FleetRoutingGrpcTransport, grpc_helpers), - (transports.FleetRoutingGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_fleet_routing_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( - "cloudoptimization.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="cloudoptimization.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.FleetRoutingGrpcTransport, transports.FleetRoutingGrpcAsyncIOTransport]) -def test_fleet_routing_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_fleet_routing_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.FleetRoutingRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_fleet_routing_rest_lro_client(): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_fleet_routing_host_no_port(transport_name): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudoptimization.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudoptimization.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudoptimization.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_fleet_routing_host_with_port(transport_name): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudoptimization.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudoptimization.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudoptimization.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_fleet_routing_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = FleetRoutingClient( - credentials=creds1, - transport=transport_name, - ) - client2 = FleetRoutingClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.optimize_tours._session - session2 = client2.transport.optimize_tours._session - assert session1 != session2 - session1 = client1.transport.batch_optimize_tours._session - session2 = client2.transport.batch_optimize_tours._session - assert session1 != session2 -def test_fleet_routing_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.FleetRoutingGrpcTransport( - 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_fleet_routing_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.FleetRoutingGrpcAsyncIOTransport( - 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.FleetRoutingGrpcTransport, transports.FleetRoutingGrpcAsyncIOTransport]) -def test_fleet_routing_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.FleetRoutingGrpcTransport, transports.FleetRoutingGrpcAsyncIOTransport]) -def test_fleet_routing_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_fleet_routing_grpc_lro_client(): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_fleet_routing_grpc_lro_async_client(): - client = FleetRoutingAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = FleetRoutingClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = FleetRoutingClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = FleetRoutingClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = FleetRoutingClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = FleetRoutingClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = FleetRoutingClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = FleetRoutingClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = FleetRoutingClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = FleetRoutingClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = FleetRoutingClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = FleetRoutingClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = FleetRoutingClient.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 = FleetRoutingClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = FleetRoutingClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = FleetRoutingClient.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.FleetRoutingTransport, '_prep_wrapped_messages') as prep: - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.FleetRoutingTransport, '_prep_wrapped_messages') as prep: - transport_class = FleetRoutingClient.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 = FleetRoutingAsyncClient( - 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_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # 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.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_get_operation(transport: str = "grpc"): - client = FleetRoutingClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = FleetRoutingAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = FleetRoutingClient( - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = FleetRoutingAsyncClient( - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = FleetRoutingClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = FleetRoutingAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = FleetRoutingClient( - 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 = FleetRoutingClient( - 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", [ - (FleetRoutingClient, transports.FleetRoutingGrpcTransport), - (FleetRoutingAsyncClient, transports.FleetRoutingGrpcAsyncIOTransport), -]) -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/tests/unit/gapic/optimization_v1/test_fleet_routing.py b/tests/unit/gapic/optimization_v1/test_fleet_routing.py index 648af90..77764ba 100644 --- a/tests/unit/gapic/optimization_v1/test_fleet_routing.py +++ b/tests/unit/gapic/optimization_v1/test_fleet_routing.py @@ -24,10 +24,17 @@ 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 @@ -100,6 +107,7 @@ def test__get_default_mtls_endpoint(): [ (FleetRoutingClient, "grpc"), (FleetRoutingAsyncClient, "grpc_asyncio"), + (FleetRoutingClient, "rest"), ], ) def test_fleet_routing_client_from_service_account_info(client_class, transport_name): @@ -113,7 +121,11 @@ def test_fleet_routing_client_from_service_account_info(client_class, transport_ assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("cloudoptimization.googleapis.com:443") + assert client.transport._host == ( + "cloudoptimization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudoptimization.googleapis.com" + ) @pytest.mark.parametrize( @@ -121,6 +133,7 @@ def test_fleet_routing_client_from_service_account_info(client_class, transport_ [ (transports.FleetRoutingGrpcTransport, "grpc"), (transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.FleetRoutingRestTransport, "rest"), ], ) def test_fleet_routing_client_service_account_always_use_jwt( @@ -146,6 +159,7 @@ def test_fleet_routing_client_service_account_always_use_jwt( [ (FleetRoutingClient, "grpc"), (FleetRoutingAsyncClient, "grpc_asyncio"), + (FleetRoutingClient, "rest"), ], ) def test_fleet_routing_client_from_service_account_file(client_class, transport_name): @@ -166,13 +180,18 @@ def test_fleet_routing_client_from_service_account_file(client_class, transport_ assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("cloudoptimization.googleapis.com:443") + assert client.transport._host == ( + "cloudoptimization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudoptimization.googleapis.com" + ) def test_fleet_routing_client_get_transport_class(): transport = FleetRoutingClient.get_transport_class() available_transports = [ transports.FleetRoutingGrpcTransport, + transports.FleetRoutingRestTransport, ] assert transport in available_transports @@ -189,6 +208,7 @@ def test_fleet_routing_client_get_transport_class(): transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio", ), + (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest"), ], ) @mock.patch.object( @@ -332,6 +352,8 @@ def test_fleet_routing_client_client_options( "grpc_asyncio", "false", ), + (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest", "true"), + (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -525,6 +547,7 @@ def test_fleet_routing_client_get_mtls_endpoint_and_cert_source(client_class): transports.FleetRoutingGrpcAsyncIOTransport, "grpc_asyncio", ), + (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest"), ], ) def test_fleet_routing_client_client_options_scopes( @@ -565,6 +588,7 @@ def test_fleet_routing_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (FleetRoutingClient, transports.FleetRoutingRestTransport, "rest", None), ], ) def test_fleet_routing_client_client_options_credentials_file( @@ -984,6 +1008,438 @@ async def test_batch_optimize_tours_field_headers_async(): ) in kw["metadata"] +@pytest.mark.parametrize( + "request_type", + [ + fleet_routing.OptimizeToursRequest, + dict, + ], +) +def test_optimize_tours_rest(request_type): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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 = fleet_routing.OptimizeToursResponse( + request_label="request_label_value", + total_cost=0.10840000000000001, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = fleet_routing.OptimizeToursResponse.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.optimize_tours(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet_routing.OptimizeToursResponse) + assert response.request_label == "request_label_value" + assert math.isclose(response.total_cost, 0.10840000000000001, rel_tol=1e-6) + + +def test_optimize_tours_rest_required_fields( + request_type=fleet_routing.OptimizeToursRequest, +): + transport_class = transports.FleetRoutingRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).optimize_tours._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).optimize_tours._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = fleet_routing.OptimizeToursResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = fleet_routing.OptimizeToursResponse.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.optimize_tours(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_optimize_tours_rest_unset_required_fields(): + transport = transports.FleetRoutingRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.optimize_tours._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_optimize_tours_rest_interceptors(null_interceptor): + transport = transports.FleetRoutingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FleetRoutingRestInterceptor(), + ) + client = FleetRoutingClient(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.FleetRoutingRestInterceptor, "post_optimize_tours" + ) as post, mock.patch.object( + transports.FleetRoutingRestInterceptor, "pre_optimize_tours" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = fleet_routing.OptimizeToursRequest.pb( + fleet_routing.OptimizeToursRequest() + ) + 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 = fleet_routing.OptimizeToursResponse.to_json( + fleet_routing.OptimizeToursResponse() + ) + + request = fleet_routing.OptimizeToursRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = fleet_routing.OptimizeToursResponse() + + client.optimize_tours( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_optimize_tours_rest_bad_request( + transport: str = "rest", request_type=fleet_routing.OptimizeToursRequest +): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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.optimize_tours(request) + + +def test_optimize_tours_rest_error(): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + fleet_routing.BatchOptimizeToursRequest, + dict, + ], +) +def test_batch_optimize_tours_rest(request_type): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.batch_optimize_tours(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_optimize_tours_rest_required_fields( + request_type=fleet_routing.BatchOptimizeToursRequest, +): + transport_class = transports.FleetRoutingRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_optimize_tours._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_optimize_tours._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.batch_optimize_tours(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_optimize_tours_rest_unset_required_fields(): + transport = transports.FleetRoutingRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_optimize_tours._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "modelConfigs", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_optimize_tours_rest_interceptors(null_interceptor): + transport = transports.FleetRoutingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FleetRoutingRestInterceptor(), + ) + client = FleetRoutingClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.FleetRoutingRestInterceptor, "post_batch_optimize_tours" + ) as post, mock.patch.object( + transports.FleetRoutingRestInterceptor, "pre_batch_optimize_tours" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = fleet_routing.BatchOptimizeToursRequest.pb( + fleet_routing.BatchOptimizeToursRequest() + ) + 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 = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = fleet_routing.BatchOptimizeToursRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_optimize_tours( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_optimize_tours_rest_bad_request( + transport: str = "rest", request_type=fleet_routing.BatchOptimizeToursRequest +): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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.batch_optimize_tours(request) + + +def test_batch_optimize_tours_rest_error(): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.FleetRoutingGrpcTransport( @@ -1065,6 +1521,7 @@ def test_transport_get_channel(): [ transports.FleetRoutingGrpcTransport, transports.FleetRoutingGrpcAsyncIOTransport, + transports.FleetRoutingRestTransport, ], ) def test_transport_adc(transport_class): @@ -1079,6 +1536,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1215,6 +1673,7 @@ def test_fleet_routing_transport_auth_adc(transport_class): [ transports.FleetRoutingGrpcTransport, transports.FleetRoutingGrpcAsyncIOTransport, + transports.FleetRoutingRestTransport, ], ) def test_fleet_routing_transport_auth_gdch_credentials(transport_class): @@ -1309,11 +1768,40 @@ def test_fleet_routing_grpc_transport_client_cert_source_for_mtls(transport_clas ) +def test_fleet_routing_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.FleetRoutingRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_fleet_routing_rest_lro_client(): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_fleet_routing_host_no_port(transport_name): @@ -1324,7 +1812,11 @@ def test_fleet_routing_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("cloudoptimization.googleapis.com:443") + assert client.transport._host == ( + "cloudoptimization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudoptimization.googleapis.com" + ) @pytest.mark.parametrize( @@ -1332,6 +1824,7 @@ def test_fleet_routing_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_fleet_routing_host_with_port(transport_name): @@ -1342,7 +1835,36 @@ def test_fleet_routing_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("cloudoptimization.googleapis.com:8000") + assert client.transport._host == ( + "cloudoptimization.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudoptimization.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_fleet_routing_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = FleetRoutingClient( + credentials=creds1, + transport=transport_name, + ) + client2 = FleetRoutingClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.optimize_tours._session + session2 = client2.transport.optimize_tours._session + assert session1 != session2 + session1 = client1.transport.batch_optimize_tours._session + session2 = client2.transport.batch_optimize_tours._session + assert session1 != session2 def test_fleet_routing_grpc_transport_channel(): @@ -1637,6 +2159,64 @@ async def test_transport_close_async(): close.assert_called_once() +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/sample2"}, request + ) + + # 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.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = FleetRoutingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/operations/sample2"} + 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 = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + def test_get_operation(transport: str = "grpc"): client = FleetRoutingClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1784,6 +2364,7 @@ async def test_get_operation_from_dict_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -1801,6 +2382,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: