From 4b107613b0fcf139569504e9d44fa4a0793b4fd0 Mon Sep 17 00:00:00 2001 From: Danny Hermes Date: Wed, 22 Nov 2017 12:59:00 -0800 Subject: [PATCH] Pub/Sub autogen refresh (#4438) --- pubsub/.coveragerc | 3 + pubsub/google/cloud/gapic/__init__.py | 1 - pubsub/google/cloud/gapic/pubsub/__init__.py | 1 - .../cloud/gapic/pubsub/v1/publisher_client.py | 565 -------- .../pubsub/v1/publisher_client_config.json | 98 -- .../gapic/pubsub/v1/subscriber_client.py | 1063 -------------- .../pubsub/v1/subscriber_client_config.json | 138 -- pubsub/google/cloud/proto/__init__.py | 1 - pubsub/google/cloud/proto/pubsub/__init__.py | 1 - .../google/cloud/proto/pubsub/v1/__init__.py | 1 - pubsub/google/cloud/pubsub.py | 3 +- pubsub/google/cloud/pubsub_v1/__init__.py | 15 +- .../pubsub/v1 => pubsub_v1/gapic}/__init__.py | 0 .../cloud/pubsub_v1/gapic/publisher_client.py | 681 +++++++++ .../gapic/publisher_client_config.py | 93 ++ .../pubsub_v1/gapic/subscriber_client.py | 1239 +++++++++++++++++ .../gapic/subscriber_client_config.py | 135 ++ .../google/cloud/pubsub_v1/proto/__init__.py | 0 .../v1 => pubsub_v1/proto}/pubsub_pb2.py | 86 +- .../v1 => pubsub_v1/proto}/pubsub_pb2_grpc.py | 156 +-- .../cloud/pubsub_v1/publisher/client.py | 15 +- .../cloud/pubsub_v1/subscriber/_consumer.py | 3 +- .../cloud/pubsub_v1/subscriber/client.py | 15 +- .../pubsub_v1/subscriber/policy/thread.py | 4 +- pubsub/google/cloud/pubsub_v1/types.py | 43 +- pubsub/setup.py | 9 +- .../unit/gapic/v1/test_publisher_client_v1.py | 415 ++++++ .../gapic/v1/test_subscriber_client_v1.py | 712 ++++++++++ .../publisher/test_publisher_client.py | 27 +- .../pubsub_v1/subscriber/test_consumer.py | 6 +- .../subscriber/test_helper_threads.py | 2 +- .../unit/pubsub_v1/subscriber/test_message.py | 2 +- .../subscriber/test_policy_thread.py | 6 +- .../subscriber/test_subscriber_client.py | 13 +- 34 files changed, 3480 insertions(+), 2072 deletions(-) delete mode 100644 pubsub/google/cloud/gapic/__init__.py delete mode 100644 pubsub/google/cloud/gapic/pubsub/__init__.py delete mode 100644 pubsub/google/cloud/gapic/pubsub/v1/publisher_client.py delete mode 100644 pubsub/google/cloud/gapic/pubsub/v1/publisher_client_config.json delete mode 100644 pubsub/google/cloud/gapic/pubsub/v1/subscriber_client.py delete mode 100644 pubsub/google/cloud/gapic/pubsub/v1/subscriber_client_config.json delete mode 100644 pubsub/google/cloud/proto/__init__.py delete mode 100644 pubsub/google/cloud/proto/pubsub/__init__.py delete mode 100644 pubsub/google/cloud/proto/pubsub/v1/__init__.py rename pubsub/google/cloud/{gapic/pubsub/v1 => pubsub_v1/gapic}/__init__.py (100%) create mode 100644 pubsub/google/cloud/pubsub_v1/gapic/publisher_client.py create mode 100644 pubsub/google/cloud/pubsub_v1/gapic/publisher_client_config.py create mode 100644 pubsub/google/cloud/pubsub_v1/gapic/subscriber_client.py create mode 100644 pubsub/google/cloud/pubsub_v1/gapic/subscriber_client_config.py create mode 100644 pubsub/google/cloud/pubsub_v1/proto/__init__.py rename pubsub/google/cloud/{proto/pubsub/v1 => pubsub_v1/proto}/pubsub_pb2.py (98%) rename pubsub/google/cloud/{proto/pubsub/v1 => pubsub_v1/proto}/pubsub_pb2_grpc.py (65%) create mode 100644 pubsub/tests/unit/gapic/v1/test_publisher_client_v1.py create mode 100644 pubsub/tests/unit/gapic/v1/test_subscriber_client_v1.py diff --git a/pubsub/.coveragerc b/pubsub/.coveragerc index 41ca7428e2ee..4bea65589ecb 100644 --- a/pubsub/.coveragerc +++ b/pubsub/.coveragerc @@ -6,6 +6,9 @@ source = tests.unit [report] +omit = + */gapic/* + */proto/* show_missing = True exclude_lines = diff --git a/pubsub/google/cloud/gapic/__init__.py b/pubsub/google/cloud/gapic/__init__.py deleted file mode 100644 index de40ea7ca058..000000000000 --- a/pubsub/google/cloud/gapic/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__import__('pkg_resources').declare_namespace(__name__) diff --git a/pubsub/google/cloud/gapic/pubsub/__init__.py b/pubsub/google/cloud/gapic/pubsub/__init__.py deleted file mode 100644 index de40ea7ca058..000000000000 --- a/pubsub/google/cloud/gapic/pubsub/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__import__('pkg_resources').declare_namespace(__name__) diff --git a/pubsub/google/cloud/gapic/pubsub/v1/publisher_client.py b/pubsub/google/cloud/gapic/pubsub/v1/publisher_client.py deleted file mode 100644 index 176f27b22f95..000000000000 --- a/pubsub/google/cloud/gapic/pubsub/v1/publisher_client.py +++ /dev/null @@ -1,565 +0,0 @@ -# Copyright 2017, Google LLC All rights reserved. -# -# Licensed under the Apache License, Version 2.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. -# -# EDITING INSTRUCTIONS -# This file was generated from the file -# https://github.com/google/googleapis/blob/master/google/pubsub/v1/pubsub.proto, -# and updates to that file get reflected here through a refresh process. -# For the short term, the refresh process will only be runnable by Google engineers. -# -# The only allowed edits are to method and file documentation. A 3-way -# merge preserves those additions if the generated source changes. -"""Accesses the google.pubsub.v1 Publisher API.""" - -import collections -import json -import os -import pkg_resources -import platform - -from google.gax import api_callable -from google.gax import config -from google.gax import path_template -import google.gax - -from google.cloud.proto.pubsub.v1 import pubsub_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import policy_pb2 - -_PageDesc = google.gax.PageDescriptor - - -class PublisherClient(object): - """ - The service that an application uses to manipulate topics, and to send - messages to a topic. - """ - - SERVICE_ADDRESS = 'pubsub.googleapis.com' - """The default address of the service.""" - - DEFAULT_SERVICE_PORT = 443 - """The default port of the service.""" - - _PAGE_DESCRIPTORS = { - 'list_topics': - _PageDesc('page_token', 'next_page_token', 'topics'), - 'list_topic_subscriptions': - _PageDesc('page_token', 'next_page_token', 'subscriptions') - } - - # The scopes needed to make gRPC calls to all of the methods defined in - # this service - _ALL_SCOPES = ('https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', ) - - _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}') - _TOPIC_PATH_TEMPLATE = path_template.PathTemplate( - 'projects/{project}/topics/{topic}') - - @classmethod - def project_path(cls, project): - """Returns a fully-qualified project resource name string.""" - return cls._PROJECT_PATH_TEMPLATE.render({ - 'project': project, - }) - - @classmethod - def topic_path(cls, project, topic): - """Returns a fully-qualified topic resource name string.""" - return cls._TOPIC_PATH_TEMPLATE.render({ - 'project': project, - 'topic': topic, - }) - - @classmethod - def match_project_from_project_name(cls, project_name): - """Parses the project from a project resource. - - Args: - project_name (string): A fully-qualified path representing a project - resource. - - Returns: - A string representing the project. - """ - return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project') - - @classmethod - def match_project_from_topic_name(cls, topic_name): - """Parses the project from a topic resource. - - Args: - topic_name (string): A fully-qualified path representing a topic - resource. - - Returns: - A string representing the project. - """ - return cls._TOPIC_PATH_TEMPLATE.match(topic_name).get('project') - - @classmethod - def match_topic_from_topic_name(cls, topic_name): - """Parses the topic from a topic resource. - - Args: - topic_name (string): A fully-qualified path representing a topic - resource. - - Returns: - A string representing the topic. - """ - return cls._TOPIC_PATH_TEMPLATE.match(topic_name).get('topic') - - def __init__(self, - service_path=SERVICE_ADDRESS, - port=DEFAULT_SERVICE_PORT, - channel=None, - credentials=None, - ssl_credentials=None, - scopes=None, - client_config=None, - app_name=None, - app_version='', - lib_name=None, - lib_version='', - metrics_headers=()): - """Constructor. - - Args: - service_path (string): The domain name of the API remote host. - port (int): The port on which to connect to the remote host. - channel (:class:`grpc.Channel`): A ``Channel`` instance through - which to make calls. - credentials (object): The authorization credentials to attach to - requests. These credentials identify this application to the - service. - ssl_credentials (:class:`grpc.ChannelCredentials`): A - ``ChannelCredentials`` instance for use with an SSL-enabled - channel. - scopes (list[string]): A list of OAuth2 scopes to attach to requests. - client_config (dict): - A dictionary for call options for each method. See - :func:`google.gax.construct_settings` for the structure of - this data. Falls back to the default config if not specified - or the specified config is missing data points. - app_name (string): The name of the application calling - the service. Recommended for analytics purposes. - app_version (string): The version of the application calling - the service. Recommended for analytics purposes. - lib_name (string): The API library software used for calling - the service. (Unless you are writing an API client itself, - leave this as default.) - lib_version (string): The API library software version used - for calling the service. (Unless you are writing an API client - itself, leave this as default.) - metrics_headers (dict): A dictionary of values for tracking - client library metrics. Ultimately serializes to a string - (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be - considered private. - - Returns: - A PublisherClient object. - """ - # Unless the calling application specifically requested - # OAuth scopes, request everything. - if scopes is None: - scopes = self._ALL_SCOPES - - # Initialize an empty client config, if none is set. - if client_config is None: - client_config = {} - - # Initialize metrics_headers as an ordered dictionary - # (cuts down on cardinality of the resulting string slightly). - metrics_headers = collections.OrderedDict(metrics_headers) - metrics_headers['gl-python'] = platform.python_version() - - # The library may or may not be set, depending on what is - # calling this client. Newer client libraries set the library name - # and version. - if lib_name: - metrics_headers[lib_name] = lib_version - - # Finally, track the GAPIC package version. - metrics_headers['gapic'] = pkg_resources.get_distribution( - 'google-cloud-pubsub', ).version - - # Load the configuration defaults. - default_client_config = json.loads( - pkg_resources.resource_string( - __name__, 'publisher_client_config.json').decode()) - defaults = api_callable.construct_settings( - 'google.pubsub.v1.Publisher', - default_client_config, - client_config, - config.STATUS_CODE_NAMES, - metrics_headers=metrics_headers, - page_descriptors=self._PAGE_DESCRIPTORS, ) - self.iam_policy_stub = config.create_stub( - iam_policy_pb2.IAMPolicyStub, - channel=channel, - service_path=service_path, - service_port=port, - credentials=credentials, - scopes=scopes, - ssl_credentials=ssl_credentials) - self.publisher_stub = config.create_stub( - pubsub_pb2.PublisherStub, - channel=channel, - service_path=service_path, - service_port=port, - credentials=credentials, - scopes=scopes, - ssl_credentials=ssl_credentials) - - self._create_topic = api_callable.create_api_call( - self.publisher_stub.CreateTopic, settings=defaults['create_topic']) - self._publish = api_callable.create_api_call( - self.publisher_stub.Publish, settings=defaults['publish']) - self._get_topic = api_callable.create_api_call( - self.publisher_stub.GetTopic, settings=defaults['get_topic']) - self._list_topics = api_callable.create_api_call( - self.publisher_stub.ListTopics, settings=defaults['list_topics']) - self._list_topic_subscriptions = api_callable.create_api_call( - self.publisher_stub.ListTopicSubscriptions, - settings=defaults['list_topic_subscriptions']) - self._delete_topic = api_callable.create_api_call( - self.publisher_stub.DeleteTopic, settings=defaults['delete_topic']) - self._set_iam_policy = api_callable.create_api_call( - self.iam_policy_stub.SetIamPolicy, - settings=defaults['set_iam_policy']) - self._get_iam_policy = api_callable.create_api_call( - self.iam_policy_stub.GetIamPolicy, - settings=defaults['get_iam_policy']) - self._test_iam_permissions = api_callable.create_api_call( - self.iam_policy_stub.TestIamPermissions, - settings=defaults['test_iam_permissions']) - - # Service calls - def create_topic(self, name, options=None): - """ - Creates the given topic with the given name. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import publisher_client - >>> client = publisher_client.PublisherClient() - >>> name = client.topic_path('[PROJECT]', '[TOPIC]') - >>> response = client.create_topic(name) - - Args: - name (string): The name of the topic. It must have the format - ``\"projects/{project}/topics/{topic}\"``. ``{topic}`` must start with a letter, - and contain only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), - underscores (``_``), periods (``.``), tildes (``~``), plus (``+``) or percent - signs (``%``). It must be between 3 and 255 characters in length, and it - must not start with ``\"goog\"``. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Topic` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.Topic(name=name) - return self._create_topic(request, options) - - def publish(self, topic, messages, options=None): - """ - Adds one or more messages to the topic. Returns ``NOT_FOUND`` if the topic - does not exist. The message payload must not be empty; it must contain - either a non-empty data field, or at least one attribute. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import publisher_client - >>> from google.cloud.proto.pubsub.v1 import pubsub_pb2 - >>> client = publisher_client.PublisherClient() - >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') - >>> data = b'' - >>> messages_element = pubsub_pb2.PubsubMessage(data=data) - >>> messages = [messages_element] - >>> response = client.publish(topic, messages) - - Args: - topic (string): The messages in the request will be published on this topic. - Format is ``projects/{project}/topics/{topic}``. - messages (list[:class:`google.cloud.proto.pubsub.v1.pubsub_pb2.PubsubMessage`]): The messages to publish. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.PublishResponse` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.PublishRequest(topic=topic, messages=messages) - return self._publish(request, options) - - def get_topic(self, topic, options=None): - """ - Gets the configuration of a topic. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import publisher_client - >>> client = publisher_client.PublisherClient() - >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') - >>> response = client.get_topic(topic) - - Args: - topic (string): The name of the topic to get. - Format is ``projects/{project}/topics/{topic}``. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Topic` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.GetTopicRequest(topic=topic) - return self._get_topic(request, options) - - def list_topics(self, project, page_size=None, options=None): - """ - Lists matching topics. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import publisher_client - >>> from google.gax import CallOptions, INITIAL_PAGE - >>> client = publisher_client.PublisherClient() - >>> project = client.project_path('[PROJECT]') - >>> - >>> # Iterate over all results - >>> for element in client.list_topics(project): - >>> # process element - >>> pass - >>> - >>> # Or iterate over results one page at a time - >>> for page in client.list_topics(project, options=CallOptions(page_token=INITIAL_PAGE)): - >>> for element in page: - >>> # process element - >>> pass - - Args: - project (string): The name of the cloud project that topics belong to. - Format is ``projects/{project}``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.gax.PageIterator` instance. By default, this - is an iterable of :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Topic` instances. - This object can also be configured to iterate over the pages - of the response through the `CallOptions` parameter. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.ListTopicsRequest( - project=project, page_size=page_size) - return self._list_topics(request, options) - - def list_topic_subscriptions(self, topic, page_size=None, options=None): - """ - Lists the name of the subscriptions for this topic. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import publisher_client - >>> from google.gax import CallOptions, INITIAL_PAGE - >>> client = publisher_client.PublisherClient() - >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') - >>> - >>> # Iterate over all results - >>> for element in client.list_topic_subscriptions(topic): - >>> # process element - >>> pass - >>> - >>> # Or iterate over results one page at a time - >>> for page in client.list_topic_subscriptions(topic, options=CallOptions(page_token=INITIAL_PAGE)): - >>> for element in page: - >>> # process element - >>> pass - - Args: - topic (string): The name of the topic that subscriptions are attached to. - Format is ``projects/{project}/topics/{topic}``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.gax.PageIterator` instance. By default, this - is an iterable of string instances. - This object can also be configured to iterate over the pages - of the response through the `CallOptions` parameter. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.ListTopicSubscriptionsRequest( - topic=topic, page_size=page_size) - return self._list_topic_subscriptions(request, options) - - def delete_topic(self, topic, options=None): - """ - Deletes the topic with the given name. Returns ``NOT_FOUND`` if the topic - does not exist. After a topic is deleted, a new topic may be created with - the same name; this is an entirely new topic with none of the old - configuration or subscriptions. Existing subscriptions to this topic are - not deleted, but their ``topic`` field is set to ``_deleted-topic_``. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import publisher_client - >>> client = publisher_client.PublisherClient() - >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') - >>> client.delete_topic(topic) - - Args: - topic (string): Name of the topic to delete. - Format is ``projects/{project}/topics/{topic}``. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.DeleteTopicRequest(topic=topic) - self._delete_topic(request, options) - - def set_iam_policy(self, resource, policy, options=None): - """ - Sets the access control policy on the specified resource. Replaces any - existing policy. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import publisher_client - >>> from google.iam.v1 import policy_pb2 - >>> client = publisher_client.PublisherClient() - >>> resource = client.topic_path('[PROJECT]', '[TOPIC]') - >>> policy = policy_pb2.Policy() - >>> response = client.set_iam_policy(resource, policy) - - Args: - resource (string): REQUIRED: The resource for which the policy is being specified. - ``resource`` is usually specified as a path. For example, a Project - resource is specified as ``projects/{project}``. - policy (:class:`google.iam.v1.policy_pb2.Policy`): REQUIRED: The complete policy to be applied to the ``resource``. The size of - the policy is limited to a few 10s of KB. An empty policy is a - valid policy but certain Cloud Platform services (such as Projects) - might reject them. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.iam.v1.policy_pb2.Policy` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = iam_policy_pb2.SetIamPolicyRequest( - resource=resource, policy=policy) - return self._set_iam_policy(request, options) - - def get_iam_policy(self, resource, options=None): - """ - Gets the access control policy for a resource. - Returns an empty policy if the resource exists and does not have a policy - set. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import publisher_client - >>> client = publisher_client.PublisherClient() - >>> resource = client.topic_path('[PROJECT]', '[TOPIC]') - >>> response = client.get_iam_policy(resource) - - Args: - resource (string): REQUIRED: The resource for which the policy is being requested. - ``resource`` is usually specified as a path. For example, a Project - resource is specified as ``projects/{project}``. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.iam.v1.policy_pb2.Policy` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - return self._get_iam_policy(request, options) - - def test_iam_permissions(self, resource, permissions, options=None): - """ - Returns permissions that a caller has on the specified resource. - If the resource does not exist, this will return an empty set of - permissions, not a NOT_FOUND error. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import publisher_client - >>> client = publisher_client.PublisherClient() - >>> resource = client.topic_path('[PROJECT]', '[TOPIC]') - >>> permissions = [] - >>> response = client.test_iam_permissions(resource, permissions) - - Args: - resource (string): REQUIRED: The resource for which the policy detail is being requested. - ``resource`` is usually specified as a path. For example, a Project - resource is specified as ``projects/{project}``. - permissions (list[string]): The set of permissions to check for the ``resource``. Permissions with - wildcards (such as '*' or 'storage.*') are not allowed. For more - information see - `IAM Overview `_. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions) - return self._test_iam_permissions(request, options) diff --git a/pubsub/google/cloud/gapic/pubsub/v1/publisher_client_config.json b/pubsub/google/cloud/gapic/pubsub/v1/publisher_client_config.json deleted file mode 100644 index 7e8a723499e6..000000000000 --- a/pubsub/google/cloud/gapic/pubsub/v1/publisher_client_config.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "interfaces": { - "google.pubsub.v1.Publisher": { - "retry_codes": { - "idempotent": [ - "DEADLINE_EXCEEDED", - "UNAVAILABLE" - ], - "one_plus_delivery": [ - "CANCELLED", - "UNKNOWN", - "DEADLINE_EXCEEDED", - "RESOURCE_EXHAUSTED", - "ABORTED", - "INTERNAL", - "UNAVAILABLE" - ], - "non_idempotent": [ - "UNAVAILABLE" - ] - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 600000 - }, - "messaging": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 12000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 12000, - "total_timeout_millis": 600000 - } - }, - "methods": { - "CreateTopic": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "Publish": { - "timeout_millis": 60000, - "retry_codes_name": "one_plus_delivery", - "retry_params_name": "messaging", - "bundling": { - "element_count_threshold": 10, - "element_count_limit": 1000, - "request_byte_threshold": 1024, - "request_byte_limit": 10485760, - "delay_threshold_millis": 10 - } - }, - "GetTopic": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "ListTopics": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "ListTopicSubscriptions": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "DeleteTopic": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "SetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "GetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "TestIamPermissions": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - } - } - } - } -} diff --git a/pubsub/google/cloud/gapic/pubsub/v1/subscriber_client.py b/pubsub/google/cloud/gapic/pubsub/v1/subscriber_client.py deleted file mode 100644 index b2b86cd7f799..000000000000 --- a/pubsub/google/cloud/gapic/pubsub/v1/subscriber_client.py +++ /dev/null @@ -1,1063 +0,0 @@ -# Copyright 2017, Google LLC All rights reserved. -# -# Licensed under the Apache License, Version 2.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. -# -# EDITING INSTRUCTIONS -# This file was generated from the file -# https://github.com/google/googleapis/blob/master/google/pubsub/v1/pubsub.proto, -# and updates to that file get reflected here through a refresh process. -# For the short term, the refresh process will only be runnable by Google engineers. -# -# The only allowed edits are to method and file documentation. A 3-way -# merge preserves those additions if the generated source changes. -"""Accesses the google.pubsub.v1 Subscriber API.""" - -import collections -import json -import os -import pkg_resources -import platform - -from google.gax import api_callable -from google.gax import config -from google.gax import path_template -from google.gax.utils import oneof -import google.gax - -from google.cloud.proto.pubsub.v1 import pubsub_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import policy_pb2 -from google.protobuf import duration_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import timestamp_pb2 - -_PageDesc = google.gax.PageDescriptor - - -class SubscriberClient(object): - """ - The service that an application uses to manipulate subscriptions and to - consume messages from a subscription via the ``Pull`` method. - """ - - SERVICE_ADDRESS = 'pubsub.googleapis.com' - """The default address of the service.""" - - DEFAULT_SERVICE_PORT = 443 - """The default port of the service.""" - - _PAGE_DESCRIPTORS = { - 'list_subscriptions': - _PageDesc('page_token', 'next_page_token', 'subscriptions'), - 'list_snapshots': - _PageDesc('page_token', 'next_page_token', 'snapshots') - } - - # The scopes needed to make gRPC calls to all of the methods defined in - # this service - _ALL_SCOPES = ('https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', ) - - _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}') - _SNAPSHOT_PATH_TEMPLATE = path_template.PathTemplate( - 'projects/{project}/snapshots/{snapshot}') - _SUBSCRIPTION_PATH_TEMPLATE = path_template.PathTemplate( - 'projects/{project}/subscriptions/{subscription}') - _TOPIC_PATH_TEMPLATE = path_template.PathTemplate( - 'projects/{project}/topics/{topic}') - - @classmethod - def project_path(cls, project): - """Returns a fully-qualified project resource name string.""" - return cls._PROJECT_PATH_TEMPLATE.render({ - 'project': project, - }) - - @classmethod - def snapshot_path(cls, project, snapshot): - """Returns a fully-qualified snapshot resource name string.""" - return cls._SNAPSHOT_PATH_TEMPLATE.render({ - 'project': project, - 'snapshot': snapshot, - }) - - @classmethod - def subscription_path(cls, project, subscription): - """Returns a fully-qualified subscription resource name string.""" - return cls._SUBSCRIPTION_PATH_TEMPLATE.render({ - 'project': - project, - 'subscription': - subscription, - }) - - @classmethod - def topic_path(cls, project, topic): - """Returns a fully-qualified topic resource name string.""" - return cls._TOPIC_PATH_TEMPLATE.render({ - 'project': project, - 'topic': topic, - }) - - @classmethod - def match_project_from_project_name(cls, project_name): - """Parses the project from a project resource. - - Args: - project_name (string): A fully-qualified path representing a project - resource. - - Returns: - A string representing the project. - """ - return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project') - - @classmethod - def match_project_from_snapshot_name(cls, snapshot_name): - """Parses the project from a snapshot resource. - - Args: - snapshot_name (string): A fully-qualified path representing a snapshot - resource. - - Returns: - A string representing the project. - """ - return cls._SNAPSHOT_PATH_TEMPLATE.match(snapshot_name).get('project') - - @classmethod - def match_snapshot_from_snapshot_name(cls, snapshot_name): - """Parses the snapshot from a snapshot resource. - - Args: - snapshot_name (string): A fully-qualified path representing a snapshot - resource. - - Returns: - A string representing the snapshot. - """ - return cls._SNAPSHOT_PATH_TEMPLATE.match(snapshot_name).get('snapshot') - - @classmethod - def match_project_from_subscription_name(cls, subscription_name): - """Parses the project from a subscription resource. - - Args: - subscription_name (string): A fully-qualified path representing a subscription - resource. - - Returns: - A string representing the project. - """ - return cls._SUBSCRIPTION_PATH_TEMPLATE.match(subscription_name).get( - 'project') - - @classmethod - def match_subscription_from_subscription_name(cls, subscription_name): - """Parses the subscription from a subscription resource. - - Args: - subscription_name (string): A fully-qualified path representing a subscription - resource. - - Returns: - A string representing the subscription. - """ - return cls._SUBSCRIPTION_PATH_TEMPLATE.match(subscription_name).get( - 'subscription') - - @classmethod - def match_project_from_topic_name(cls, topic_name): - """Parses the project from a topic resource. - - Args: - topic_name (string): A fully-qualified path representing a topic - resource. - - Returns: - A string representing the project. - """ - return cls._TOPIC_PATH_TEMPLATE.match(topic_name).get('project') - - @classmethod - def match_topic_from_topic_name(cls, topic_name): - """Parses the topic from a topic resource. - - Args: - topic_name (string): A fully-qualified path representing a topic - resource. - - Returns: - A string representing the topic. - """ - return cls._TOPIC_PATH_TEMPLATE.match(topic_name).get('topic') - - def __init__(self, - service_path=SERVICE_ADDRESS, - port=DEFAULT_SERVICE_PORT, - channel=None, - credentials=None, - ssl_credentials=None, - scopes=None, - client_config=None, - app_name=None, - app_version='', - lib_name=None, - lib_version='', - metrics_headers=()): - """Constructor. - - Args: - service_path (string): The domain name of the API remote host. - port (int): The port on which to connect to the remote host. - channel (:class:`grpc.Channel`): A ``Channel`` instance through - which to make calls. - credentials (object): The authorization credentials to attach to - requests. These credentials identify this application to the - service. - ssl_credentials (:class:`grpc.ChannelCredentials`): A - ``ChannelCredentials`` instance for use with an SSL-enabled - channel. - scopes (list[string]): A list of OAuth2 scopes to attach to requests. - client_config (dict): - A dictionary for call options for each method. See - :func:`google.gax.construct_settings` for the structure of - this data. Falls back to the default config if not specified - or the specified config is missing data points. - app_name (string): The name of the application calling - the service. Recommended for analytics purposes. - app_version (string): The version of the application calling - the service. Recommended for analytics purposes. - lib_name (string): The API library software used for calling - the service. (Unless you are writing an API client itself, - leave this as default.) - lib_version (string): The API library software version used - for calling the service. (Unless you are writing an API client - itself, leave this as default.) - metrics_headers (dict): A dictionary of values for tracking - client library metrics. Ultimately serializes to a string - (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be - considered private. - - Returns: - A SubscriberClient object. - """ - # Unless the calling application specifically requested - # OAuth scopes, request everything. - if scopes is None: - scopes = self._ALL_SCOPES - - # Initialize an empty client config, if none is set. - if client_config is None: - client_config = {} - - # Initialize metrics_headers as an ordered dictionary - # (cuts down on cardinality of the resulting string slightly). - metrics_headers = collections.OrderedDict(metrics_headers) - metrics_headers['gl-python'] = platform.python_version() - - # The library may or may not be set, depending on what is - # calling this client. Newer client libraries set the library name - # and version. - if lib_name: - metrics_headers[lib_name] = lib_version - - # Finally, track the GAPIC package version. - metrics_headers['gapic'] = pkg_resources.get_distribution( - 'google-cloud-pubsub', ).version - - # Load the configuration defaults. - default_client_config = json.loads( - pkg_resources.resource_string( - __name__, 'subscriber_client_config.json').decode()) - defaults = api_callable.construct_settings( - 'google.pubsub.v1.Subscriber', - default_client_config, - client_config, - config.STATUS_CODE_NAMES, - metrics_headers=metrics_headers, - page_descriptors=self._PAGE_DESCRIPTORS, ) - self.iam_policy_stub = config.create_stub( - iam_policy_pb2.IAMPolicyStub, - channel=channel, - service_path=service_path, - service_port=port, - credentials=credentials, - scopes=scopes, - ssl_credentials=ssl_credentials) - self.subscriber_stub = config.create_stub( - pubsub_pb2.SubscriberStub, - channel=channel, - service_path=service_path, - service_port=port, - credentials=credentials, - scopes=scopes, - ssl_credentials=ssl_credentials) - - self._create_subscription = api_callable.create_api_call( - self.subscriber_stub.CreateSubscription, - settings=defaults['create_subscription']) - self._get_subscription = api_callable.create_api_call( - self.subscriber_stub.GetSubscription, - settings=defaults['get_subscription']) - self._update_subscription = api_callable.create_api_call( - self.subscriber_stub.UpdateSubscription, - settings=defaults['update_subscription']) - self._list_subscriptions = api_callable.create_api_call( - self.subscriber_stub.ListSubscriptions, - settings=defaults['list_subscriptions']) - self._delete_subscription = api_callable.create_api_call( - self.subscriber_stub.DeleteSubscription, - settings=defaults['delete_subscription']) - self._modify_ack_deadline = api_callable.create_api_call( - self.subscriber_stub.ModifyAckDeadline, - settings=defaults['modify_ack_deadline']) - self._acknowledge = api_callable.create_api_call( - self.subscriber_stub.Acknowledge, settings=defaults['acknowledge']) - self._pull = api_callable.create_api_call( - self.subscriber_stub.Pull, settings=defaults['pull']) - self._streaming_pull = api_callable.create_api_call( - self.subscriber_stub.StreamingPull, - settings=defaults['streaming_pull']) - self._modify_push_config = api_callable.create_api_call( - self.subscriber_stub.ModifyPushConfig, - settings=defaults['modify_push_config']) - self._list_snapshots = api_callable.create_api_call( - self.subscriber_stub.ListSnapshots, - settings=defaults['list_snapshots']) - self._create_snapshot = api_callable.create_api_call( - self.subscriber_stub.CreateSnapshot, - settings=defaults['create_snapshot']) - self._delete_snapshot = api_callable.create_api_call( - self.subscriber_stub.DeleteSnapshot, - settings=defaults['delete_snapshot']) - self._seek = api_callable.create_api_call( - self.subscriber_stub.Seek, settings=defaults['seek']) - self._set_iam_policy = api_callable.create_api_call( - self.iam_policy_stub.SetIamPolicy, - settings=defaults['set_iam_policy']) - self._get_iam_policy = api_callable.create_api_call( - self.iam_policy_stub.GetIamPolicy, - settings=defaults['get_iam_policy']) - self._test_iam_permissions = api_callable.create_api_call( - self.iam_policy_stub.TestIamPermissions, - settings=defaults['test_iam_permissions']) - - # Service calls - def create_subscription(self, - name, - topic, - push_config=None, - ack_deadline_seconds=None, - retain_acked_messages=None, - message_retention_duration=None, - options=None): - """ - Creates a subscription to a given topic. - If the subscription already exists, returns ``ALREADY_EXISTS``. - If the corresponding topic doesn't exist, returns ``NOT_FOUND``. - - If the name is not provided in the request, the server will assign a random - name for this subscription on the same project as the topic, conforming - to the - `resource name format `_. - The generated name is populated in the returned Subscription object. - Note that for REST API requests, you must specify a name in the request. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> client = subscriber_client.SubscriberClient() - >>> name = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') - >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') - >>> response = client.create_subscription(name, topic) - - Args: - name (string): The name of the subscription. It must have the format - ``\"projects/{project}/subscriptions/{subscription}\"``. ``{subscription}`` must - start with a letter, and contain only letters (``[A-Za-z]``), numbers - (``[0-9]``), dashes (``-``), underscores (``_``), periods (``.``), tildes (``~``), - plus (``+``) or percent signs (``%``). It must be between 3 and 255 characters - in length, and it must not start with ``\"goog\"``. - topic (string): The name of the topic from which this subscription is receiving messages. - Format is ``projects/{project}/topics/{topic}``. - The value of this field will be ``_deleted-topic_`` if the topic has been - deleted. - push_config (:class:`google.cloud.proto.pubsub.v1.pubsub_pb2.PushConfig`): If push delivery is used with this subscription, this field is - used to configure it. An empty ``pushConfig`` signifies that the subscriber - will pull and ack messages using API methods. - ack_deadline_seconds (int): This value is the maximum time after a subscriber receives a message - before the subscriber should acknowledge the message. After message - delivery but before the ack deadline expires and before the message is - acknowledged, it is an outstanding message and will not be delivered - again during that time (on a best-effort basis). - - For pull subscriptions, this value is used as the initial value for the ack - deadline. To override this value for a given message, call - ``ModifyAckDeadline`` with the corresponding ``ack_id`` if using - pull. - The minimum custom deadline you can specify is 10 seconds. - The maximum custom deadline you can specify is 600 seconds (10 minutes). - If this parameter is 0, a default value of 10 seconds is used. - - For push delivery, this value is also used to set the request timeout for - the call to the push endpoint. - - If the subscriber never acknowledges the message, the Pub/Sub - system will eventually redeliver the message. - retain_acked_messages (bool): Indicates whether to retain acknowledged messages. If true, then - messages are not expunged from the subscription's backlog, even if they are - acknowledged, until they fall out of the ``message_retention_duration`` - window. - message_retention_duration (:class:`google.protobuf.duration_pb2.Duration`): How long to retain unacknowledged messages in the subscription's backlog, - from the moment a message is published. - If ``retain_acked_messages`` is true, then this also configures the retention - of acknowledged messages, and thus configures how far back in time a ``Seek`` - can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 - minutes. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Subscription` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.Subscription( - name=name, - topic=topic, - push_config=push_config, - ack_deadline_seconds=ack_deadline_seconds, - retain_acked_messages=retain_acked_messages, - message_retention_duration=message_retention_duration) - return self._create_subscription(request, options) - - def get_subscription(self, subscription, options=None): - """ - Gets the configuration details of a subscription. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> client = subscriber_client.SubscriberClient() - >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') - >>> response = client.get_subscription(subscription) - - Args: - subscription (string): The name of the subscription to get. - Format is ``projects/{project}/subscriptions/{sub}``. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Subscription` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.GetSubscriptionRequest(subscription=subscription) - return self._get_subscription(request, options) - - def update_subscription(self, subscription, update_mask, options=None): - """ - Updates an existing subscription. Note that certain properties of a - subscription, such as its topic, are not modifiable. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> from google.cloud.proto.pubsub.v1 import pubsub_pb2 - >>> from google.protobuf import field_mask_pb2 - >>> client = subscriber_client.SubscriberClient() - >>> subscription = pubsub_pb2.Subscription() - >>> update_mask = field_mask_pb2.FieldMask() - >>> response = client.update_subscription(subscription, update_mask) - - Args: - subscription (:class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Subscription`): The updated subscription object. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): Indicates which fields in the provided subscription to update. - Must be specified and non-empty. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Subscription` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.UpdateSubscriptionRequest( - subscription=subscription, update_mask=update_mask) - return self._update_subscription(request, options) - - def list_subscriptions(self, project, page_size=None, options=None): - """ - Lists matching subscriptions. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> from google.gax import CallOptions, INITIAL_PAGE - >>> client = subscriber_client.SubscriberClient() - >>> project = client.project_path('[PROJECT]') - >>> - >>> # Iterate over all results - >>> for element in client.list_subscriptions(project): - >>> # process element - >>> pass - >>> - >>> # Or iterate over results one page at a time - >>> for page in client.list_subscriptions(project, options=CallOptions(page_token=INITIAL_PAGE)): - >>> for element in page: - >>> # process element - >>> pass - - Args: - project (string): The name of the cloud project that subscriptions belong to. - Format is ``projects/{project}``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.gax.PageIterator` instance. By default, this - is an iterable of :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Subscription` instances. - This object can also be configured to iterate over the pages - of the response through the `CallOptions` parameter. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.ListSubscriptionsRequest( - project=project, page_size=page_size) - return self._list_subscriptions(request, options) - - def delete_subscription(self, subscription, options=None): - """ - Deletes an existing subscription. All messages retained in the subscription - are immediately dropped. Calls to ``Pull`` after deletion will return - ``NOT_FOUND``. After a subscription is deleted, a new one may be created with - the same name, but the new one has no association with the old - subscription or its topic unless the same topic is specified. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> client = subscriber_client.SubscriberClient() - >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') - >>> client.delete_subscription(subscription) - - Args: - subscription (string): The subscription to delete. - Format is ``projects/{project}/subscriptions/{sub}``. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.DeleteSubscriptionRequest( - subscription=subscription) - self._delete_subscription(request, options) - - def modify_ack_deadline(self, - subscription, - ack_ids, - ack_deadline_seconds, - options=None): - """ - Modifies the ack deadline for a specific message. This method is useful - to indicate that more time is needed to process a message by the - subscriber, or to make the message available for redelivery if the - processing was interrupted. Note that this does not modify the - subscription-level ``ackDeadlineSeconds`` used for subsequent messages. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> client = subscriber_client.SubscriberClient() - >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') - >>> ack_ids = [] - >>> ack_deadline_seconds = 0 - >>> client.modify_ack_deadline(subscription, ack_ids, ack_deadline_seconds) - - Args: - subscription (string): The name of the subscription. - Format is ``projects/{project}/subscriptions/{sub}``. - ack_ids (list[string]): List of acknowledgment IDs. - ack_deadline_seconds (int): The new ack deadline with respect to the time this request was sent to - the Pub/Sub system. For example, if the value is 10, the new - ack deadline will expire 10 seconds after the ``ModifyAckDeadline`` call - was made. Specifying zero may immediately make the message available for - another pull request. - The minimum deadline you can specify is 0 seconds. - The maximum deadline you can specify is 600 seconds (10 minutes). - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.ModifyAckDeadlineRequest( - subscription=subscription, - ack_ids=ack_ids, - ack_deadline_seconds=ack_deadline_seconds) - self._modify_ack_deadline(request, options) - - def acknowledge(self, subscription, ack_ids, options=None): - """ - Acknowledges the messages associated with the ``ack_ids`` in the - ``AcknowledgeRequest``. The Pub/Sub system can remove the relevant messages - from the subscription. - - Acknowledging a message whose ack deadline has expired may succeed, - but such a message may be redelivered later. Acknowledging a message more - than once will not result in an error. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> client = subscriber_client.SubscriberClient() - >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') - >>> ack_ids = [] - >>> client.acknowledge(subscription, ack_ids) - - Args: - subscription (string): The subscription whose message is being acknowledged. - Format is ``projects/{project}/subscriptions/{sub}``. - ack_ids (list[string]): The acknowledgment ID for the messages being acknowledged that was returned - by the Pub/Sub system in the ``Pull`` response. Must not be empty. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.AcknowledgeRequest( - subscription=subscription, ack_ids=ack_ids) - self._acknowledge(request, options) - - def pull(self, - subscription, - max_messages, - return_immediately=None, - options=None): - """ - Pulls messages from the server. Returns an empty list if there are no - messages available in the backlog. The server may return ``UNAVAILABLE`` if - there are too many concurrent pull requests pending for the given - subscription. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> client = subscriber_client.SubscriberClient() - >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') - >>> max_messages = 0 - >>> response = client.pull(subscription, max_messages) - - Args: - subscription (string): The subscription from which messages should be pulled. - Format is ``projects/{project}/subscriptions/{sub}``. - max_messages (int): The maximum number of messages returned for this request. The Pub/Sub - system may return fewer than the number specified. - return_immediately (bool): If this field set to true, the system will respond immediately even if - it there are no messages available to return in the ``Pull`` response. - Otherwise, the system may wait (for a bounded amount of time) until at - least one message is available, rather than returning no messages. The - client may cancel the request if it does not wish to wait any longer for - the response. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.PullResponse` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.PullRequest( - subscription=subscription, - max_messages=max_messages, - return_immediately=return_immediately) - return self._pull(request, options) - - def streaming_pull(self, requests, options=None): - """ - (EXPERIMENTAL) StreamingPull is an experimental feature. This RPC will - respond with UNIMPLEMENTED errors unless you have been invited to test - this feature. Contact cloud-pubsub@google.com with any questions. - - Establishes a stream with the server, which sends messages down to the - client. The client streams acknowledgements and ack deadline modifications - back to the server. The server will close the stream and return the status - on any error. The server may close the stream with status ``OK`` to reassign - server-side resources, in which case, the client should re-establish the - stream. ``UNAVAILABLE`` may also be returned in the case of a transient error - (e.g., a server restart). These should also be retried by the client. Flow - control can be achieved by configuring the underlying RPC channel. - - EXPERIMENTAL: This method interface might change in the future. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> from google.cloud.proto.pubsub.v1 import pubsub_pb2 - >>> client = subscriber_client.SubscriberClient() - >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') - >>> stream_ack_deadline_seconds = 0 - >>> request = pubsub_pb2.StreamingPullRequest(subscription=subscription, stream_ack_deadline_seconds=stream_ack_deadline_seconds) - >>> requests = [request] - >>> for element in client.streaming_pull(requests): - >>> # process element - >>> pass - - Args: - requests (iterator[:class:`google.cloud.proto.pubsub.v1.pubsub_pb2.StreamingPullRequest`]): The input objects. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - iterator[:class:`google.cloud.proto.pubsub.v1.pubsub_pb2.StreamingPullResponse`]. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - return self._streaming_pull(requests, options) - - def modify_push_config(self, subscription, push_config, options=None): - """ - Modifies the ``PushConfig`` for a specified subscription. - - This may be used to change a push subscription to a pull one (signified by - an empty ``PushConfig``) or vice versa, or change the endpoint URL and other - attributes of a push subscription. Messages will accumulate for delivery - continuously through the call regardless of changes to the ``PushConfig``. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> from google.cloud.proto.pubsub.v1 import pubsub_pb2 - >>> client = subscriber_client.SubscriberClient() - >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') - >>> push_config = pubsub_pb2.PushConfig() - >>> client.modify_push_config(subscription, push_config) - - Args: - subscription (string): The name of the subscription. - Format is ``projects/{project}/subscriptions/{sub}``. - push_config (:class:`google.cloud.proto.pubsub.v1.pubsub_pb2.PushConfig`): The push configuration for future deliveries. - - An empty ``pushConfig`` indicates that the Pub/Sub system should - stop pushing messages from the given subscription and allow - messages to be pulled and acknowledged - effectively pausing - the subscription if ``Pull`` is not called. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.ModifyPushConfigRequest( - subscription=subscription, push_config=push_config) - self._modify_push_config(request, options) - - def list_snapshots(self, project, page_size=None, options=None): - """ - Lists the existing snapshots. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> from google.gax import CallOptions, INITIAL_PAGE - >>> client = subscriber_client.SubscriberClient() - >>> project = client.project_path('[PROJECT]') - >>> - >>> # Iterate over all results - >>> for element in client.list_snapshots(project): - >>> # process element - >>> pass - >>> - >>> # Or iterate over results one page at a time - >>> for page in client.list_snapshots(project, options=CallOptions(page_token=INITIAL_PAGE)): - >>> for element in page: - >>> # process element - >>> pass - - Args: - project (string): The name of the cloud project that snapshots belong to. - Format is ``projects/{project}``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.gax.PageIterator` instance. By default, this - is an iterable of :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Snapshot` instances. - This object can also be configured to iterate over the pages - of the response through the `CallOptions` parameter. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.ListSnapshotsRequest( - project=project, page_size=page_size) - return self._list_snapshots(request, options) - - def create_snapshot(self, name, subscription, options=None): - """ - Creates a snapshot from the requested subscription. - If the snapshot already exists, returns ``ALREADY_EXISTS``. - If the requested subscription doesn't exist, returns ``NOT_FOUND``. - - If the name is not provided in the request, the server will assign a random - name for this snapshot on the same project as the subscription, conforming - to the - `resource name format `_. - The generated name is populated in the returned Snapshot object. - Note that for REST API requests, you must specify a name in the request. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> client = subscriber_client.SubscriberClient() - >>> name = client.snapshot_path('[PROJECT]', '[SNAPSHOT]') - >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') - >>> response = client.create_snapshot(name, subscription) - - Args: - name (string): Optional user-provided name for this snapshot. - If the name is not provided in the request, the server will assign a random - name for this snapshot on the same project as the subscription. - Note that for REST API requests, you must specify a name. - Format is ``projects/{project}/snapshots/{snap}``. - subscription (string): The subscription whose backlog the snapshot retains. - Specifically, the created snapshot is guaranteed to retain: - - - The existing backlog on the subscription. More precisely, this is - defined as the messages in the subscription's backlog that are - unacknowledged upon the successful completion of the - `CreateSnapshot` request; as well as: - - Any messages published to the subscription's topic following the - successful completion of the CreateSnapshot request. - - Format is ``projects/{project}/subscriptions/{sub}``. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Snapshot` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.CreateSnapshotRequest( - name=name, subscription=subscription) - return self._create_snapshot(request, options) - - def delete_snapshot(self, snapshot, options=None): - """ - Removes an existing snapshot. All messages retained in the snapshot - are immediately dropped. After a snapshot is deleted, a new one may be - created with the same name, but the new one has no association with the old - snapshot or its subscription, unless the same subscription is specified. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> client = subscriber_client.SubscriberClient() - >>> snapshot = client.snapshot_path('[PROJECT]', '[SNAPSHOT]') - >>> client.delete_snapshot(snapshot) - - Args: - snapshot (string): The name of the snapshot to delete. - Format is ``projects/{project}/snapshots/{snap}``. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = pubsub_pb2.DeleteSnapshotRequest(snapshot=snapshot) - self._delete_snapshot(request, options) - - def seek(self, subscription, time=None, snapshot=None, options=None): - """ - Seeks an existing subscription to a point in time or to a given snapshot, - whichever is provided in the request. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> client = subscriber_client.SubscriberClient() - >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') - >>> response = client.seek(subscription) - - Args: - subscription (string): The subscription to affect. - time (:class:`google.protobuf.timestamp_pb2.Timestamp`): The time to seek to. - Messages retained in the subscription that were published before this - time are marked as acknowledged, and messages retained in the - subscription that were published after this time are marked as - unacknowledged. Note that this operation affects only those messages - retained in the subscription (configured by the combination of - ``message_retention_duration`` and ``retain_acked_messages``). For example, - if ``time`` corresponds to a point before the message retention - window (or to a point before the system's notion of the subscription - creation time), only retained messages will be marked as unacknowledged, - and already-expunged messages will not be restored. - snapshot (string): The snapshot to seek to. The snapshot's topic must be the same as that of - the provided subscription. - Format is ``projects/{project}/snapshots/{snap}``. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.SeekResponse` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Sanity check: We have some fields which are mutually exclusive; - # raise ValueError if more than one is sent. - oneof.check_oneof( - time=time, - snapshot=snapshot, ) - - # Create the request object. - request = pubsub_pb2.SeekRequest( - subscription=subscription, time=time, snapshot=snapshot) - return self._seek(request, options) - - def set_iam_policy(self, resource, policy, options=None): - """ - Sets the access control policy on the specified resource. Replaces any - existing policy. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> from google.iam.v1 import policy_pb2 - >>> client = subscriber_client.SubscriberClient() - >>> resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') - >>> policy = policy_pb2.Policy() - >>> response = client.set_iam_policy(resource, policy) - - Args: - resource (string): REQUIRED: The resource for which the policy is being specified. - ``resource`` is usually specified as a path. For example, a Project - resource is specified as ``projects/{project}``. - policy (:class:`google.iam.v1.policy_pb2.Policy`): REQUIRED: The complete policy to be applied to the ``resource``. The size of - the policy is limited to a few 10s of KB. An empty policy is a - valid policy but certain Cloud Platform services (such as Projects) - might reject them. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.iam.v1.policy_pb2.Policy` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = iam_policy_pb2.SetIamPolicyRequest( - resource=resource, policy=policy) - return self._set_iam_policy(request, options) - - def get_iam_policy(self, resource, options=None): - """ - Gets the access control policy for a resource. - Returns an empty policy if the resource exists and does not have a policy - set. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> client = subscriber_client.SubscriberClient() - >>> resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') - >>> response = client.get_iam_policy(resource) - - Args: - resource (string): REQUIRED: The resource for which the policy is being requested. - ``resource`` is usually specified as a path. For example, a Project - resource is specified as ``projects/{project}``. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.iam.v1.policy_pb2.Policy` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - return self._get_iam_policy(request, options) - - def test_iam_permissions(self, resource, permissions, options=None): - """ - Returns permissions that a caller has on the specified resource. - If the resource does not exist, this will return an empty set of - permissions, not a NOT_FOUND error. - - Example: - >>> from google.cloud.gapic.pubsub.v1 import subscriber_client - >>> client = subscriber_client.SubscriberClient() - >>> resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') - >>> permissions = [] - >>> response = client.test_iam_permissions(resource, permissions) - - Args: - resource (string): REQUIRED: The resource for which the policy detail is being requested. - ``resource`` is usually specified as a path. For example, a Project - resource is specified as ``projects/{project}``. - permissions (list[string]): The set of permissions to check for the ``resource``. Permissions with - wildcards (such as '*' or 'storage.*') are not allowed. For more - information see - `IAM Overview `_. - options (:class:`google.gax.CallOptions`): Overrides the default - settings for this call, e.g, timeout, retries etc. - - Returns: - A :class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse` instance. - - Raises: - :exc:`google.gax.errors.GaxError` if the RPC is aborted. - :exc:`ValueError` if the parameters are invalid. - """ - # Create the request object. - request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions) - return self._test_iam_permissions(request, options) diff --git a/pubsub/google/cloud/gapic/pubsub/v1/subscriber_client_config.json b/pubsub/google/cloud/gapic/pubsub/v1/subscriber_client_config.json deleted file mode 100644 index 6180cc0a941f..000000000000 --- a/pubsub/google/cloud/gapic/pubsub/v1/subscriber_client_config.json +++ /dev/null @@ -1,138 +0,0 @@ -{ - "interfaces": { - "google.pubsub.v1.Subscriber": { - "retry_codes": { - "idempotent": [ - "DEADLINE_EXCEEDED", - "UNAVAILABLE" - ], - "non_idempotent": [ - "UNAVAILABLE" - ], - "pull": [ - "CANCELLED", - "DEADLINE_EXCEEDED", - "RESOURCE_EXHAUSTED", - "INTERNAL", - "UNAVAILABLE" - ] - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 600000 - }, - "messaging": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 12000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 12000, - "total_timeout_millis": 600000 - }, - "streaming": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 900000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 900000, - "total_timeout_millis": 900000 - } - }, - "methods": { - "CreateSubscription": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "GetSubscription": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "UpdateSubscription": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "ListSubscriptions": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "DeleteSubscription": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "ModifyAckDeadline": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "Acknowledge": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "messaging" - }, - "Pull": { - "timeout_millis": 60000, - "retry_codes_name": "pull", - "retry_params_name": "messaging" - }, - "StreamingPull": { - "timeout_millis": 900000, - "retry_codes_name": "pull", - "retry_params_name": "streaming" - }, - "ModifyPushConfig": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "ListSnapshots": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "CreateSnapshot": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "DeleteSnapshot": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "Seek": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "SetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "GetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "TestIamPermissions": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - } - } - } - } -} diff --git a/pubsub/google/cloud/proto/__init__.py b/pubsub/google/cloud/proto/__init__.py deleted file mode 100644 index de40ea7ca058..000000000000 --- a/pubsub/google/cloud/proto/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__import__('pkg_resources').declare_namespace(__name__) diff --git a/pubsub/google/cloud/proto/pubsub/__init__.py b/pubsub/google/cloud/proto/pubsub/__init__.py deleted file mode 100644 index de40ea7ca058..000000000000 --- a/pubsub/google/cloud/proto/pubsub/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__import__('pkg_resources').declare_namespace(__name__) diff --git a/pubsub/google/cloud/proto/pubsub/v1/__init__.py b/pubsub/google/cloud/proto/pubsub/v1/__init__.py deleted file mode 100644 index 8b137891791f..000000000000 --- a/pubsub/google/cloud/proto/pubsub/v1/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/pubsub/google/cloud/pubsub.py b/pubsub/google/cloud/pubsub.py index afaa55e4ef81..dba2ad09a3fd 100644 --- a/pubsub/google/cloud/pubsub.py +++ b/pubsub/google/cloud/pubsub.py @@ -18,9 +18,8 @@ from google.cloud.pubsub_v1 import SubscriberClient from google.cloud.pubsub_v1 import types - __all__ = ( + 'types', 'PublisherClient', 'SubscriberClient', - 'types', ) diff --git a/pubsub/google/cloud/pubsub_v1/__init__.py b/pubsub/google/cloud/pubsub_v1/__init__.py index 7343acde9d49..e6f3c0aae6e7 100644 --- a/pubsub/google/cloud/pubsub_v1/__init__.py +++ b/pubsub/google/cloud/pubsub_v1/__init__.py @@ -15,11 +15,20 @@ from __future__ import absolute_import from google.cloud.pubsub_v1 import types -from google.cloud.pubsub_v1.publisher import Client as PublisherClient -from google.cloud.pubsub_v1.subscriber import Client as SubscriberClient +from google.cloud.pubsub_v1 import publisher +from google.cloud.pubsub_v1 import subscriber + + +class PublisherClient(publisher.Client): + __doc__ = publisher.Client.__doc__ + + +class SubscriberClient(subscriber.Client): + __doc__ = subscriber.Client.__doc__ + __all__ = ( + 'types', 'PublisherClient', 'SubscriberClient', - 'types', ) diff --git a/pubsub/google/cloud/gapic/pubsub/v1/__init__.py b/pubsub/google/cloud/pubsub_v1/gapic/__init__.py similarity index 100% rename from pubsub/google/cloud/gapic/pubsub/v1/__init__.py rename to pubsub/google/cloud/pubsub_v1/gapic/__init__.py diff --git a/pubsub/google/cloud/pubsub_v1/gapic/publisher_client.py b/pubsub/google/cloud/pubsub_v1/gapic/publisher_client.py new file mode 100644 index 000000000000..0e61814166dd --- /dev/null +++ b/pubsub/google/cloud/pubsub_v1/gapic/publisher_client.py @@ -0,0 +1,681 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.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. +# +# EDITING INSTRUCTIONS +# This file was generated from the file +# https://github.com/google/googleapis/blob/master/google/pubsub/v1/pubsub.proto, +# and updates to that file get reflected here through a refresh process. +# For the short term, the refresh process will only be runnable by Google engineers. +# +# The only allowed edits are to method and file documentation. A 3-way +# merge preserves those additions if the generated source changes. +"""Accesses the google.pubsub.v1 Publisher API.""" + +import functools +import pkg_resources + +import google.api_core.gapic_v1.client_info +import google.api_core.gapic_v1.config +import google.api_core.gapic_v1.method +import google.api_core.grpc_helpers +import google.api_core.page_iterator +import google.api_core.path_template + +from google.cloud.pubsub_v1.gapic import publisher_client_config +from google.cloud.pubsub_v1.proto import pubsub_pb2 +from google.iam.v1 import iam_policy_pb2 +from google.iam.v1 import policy_pb2 +from google.protobuf import field_mask_pb2 + + +_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( + 'google-cloud-pubsub').version + + +class PublisherClient(object): + """ + The service that an application uses to manipulate topics, and to send + messages to a topic. + """ + + SERVICE_ADDRESS = 'pubsub.googleapis.com:443' + """The default address of the service.""" + + # The scopes needed to make gRPC calls to all of the methods defined in + # this service + _DEFAULT_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', ) + + # The name of the interface for this client. This is the key used to find + # method configuration in the client_config dictionary + _INTERFACE_NAME = ('google.pubsub.v1.Publisher') + + @classmethod + def project_path(cls, project): + """Returns a fully-qualified project resource name string.""" + return google.api_core.path_template.expand( + 'projects/{project}', + project=project, ) + + @classmethod + def topic_path(cls, project, topic): + """Returns a fully-qualified topic resource name string.""" + return google.api_core.path_template.expand( + 'projects/{project}/topics/{topic}', + project=project, + topic=topic, ) + + def __init__(self, + channel=None, + credentials=None, + client_config=publisher_client_config.config, + client_info=None): + """Constructor. + + Args: + channel (grpc.Channel): A ``Channel`` instance through + which to make calls. If specified, then the ``credentials`` + argument is ignored. + credentials (google.auth.credentials.Credentials): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_config (dict): + A dictionary of call options for each method. If not specified + the default configuration is used. Generally, you only need + to set this if you're developing your own client library. + 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. + """ + if channel is not None and credentials is not None: + raise ValueError( + 'channel and credentials arguments to {} are mutually ' + 'exclusive.'.format(self.__class__.__name__)) + + if channel is None: + channel = google.api_core.grpc_helpers.create_channel( + self.SERVICE_ADDRESS, + credentials=credentials, + scopes=self._DEFAULT_SCOPES) + + self.iam_policy_stub = (iam_policy_pb2.IAMPolicyStub(channel)) + self.publisher_stub = (pubsub_pb2.PublisherStub(channel)) + + if client_info is None: + client_info = ( + google.api_core.gapic_v1.client_info.DEFAULT_CLIENT_INFO) + + client_info.gapic_version = _GAPIC_LIBRARY_VERSION + + interface_config = client_config['interfaces'][self._INTERFACE_NAME] + method_configs = google.api_core.gapic_v1.config.parse_method_configs( + interface_config) + + self._create_topic = google.api_core.gapic_v1.method.wrap_method( + self.publisher_stub.CreateTopic, + default_retry=method_configs['CreateTopic'].retry, + default_timeout=method_configs['CreateTopic'].timeout, + client_info=client_info) + self._update_topic = google.api_core.gapic_v1.method.wrap_method( + self.publisher_stub.UpdateTopic, + default_retry=method_configs['UpdateTopic'].retry, + default_timeout=method_configs['UpdateTopic'].timeout, + client_info=client_info) + self._publish = google.api_core.gapic_v1.method.wrap_method( + self.publisher_stub.Publish, + default_retry=method_configs['Publish'].retry, + default_timeout=method_configs['Publish'].timeout, + client_info=client_info) + self._get_topic = google.api_core.gapic_v1.method.wrap_method( + self.publisher_stub.GetTopic, + default_retry=method_configs['GetTopic'].retry, + default_timeout=method_configs['GetTopic'].timeout, + client_info=client_info) + self._list_topics = google.api_core.gapic_v1.method.wrap_method( + self.publisher_stub.ListTopics, + default_retry=method_configs['ListTopics'].retry, + default_timeout=method_configs['ListTopics'].timeout, + client_info=client_info) + self._list_topic_subscriptions = google.api_core.gapic_v1.method.wrap_method( + self.publisher_stub.ListTopicSubscriptions, + default_retry=method_configs['ListTopicSubscriptions'].retry, + default_timeout=method_configs['ListTopicSubscriptions'].timeout, + client_info=client_info) + self._delete_topic = google.api_core.gapic_v1.method.wrap_method( + self.publisher_stub.DeleteTopic, + default_retry=method_configs['DeleteTopic'].retry, + default_timeout=method_configs['DeleteTopic'].timeout, + client_info=client_info) + self._set_iam_policy = google.api_core.gapic_v1.method.wrap_method( + self.iam_policy_stub.SetIamPolicy, + default_retry=method_configs['SetIamPolicy'].retry, + default_timeout=method_configs['SetIamPolicy'].timeout, + client_info=client_info) + self._get_iam_policy = google.api_core.gapic_v1.method.wrap_method( + self.iam_policy_stub.GetIamPolicy, + default_retry=method_configs['GetIamPolicy'].retry, + default_timeout=method_configs['GetIamPolicy'].timeout, + client_info=client_info) + self._test_iam_permissions = google.api_core.gapic_v1.method.wrap_method( + self.iam_policy_stub.TestIamPermissions, + default_retry=method_configs['TestIamPermissions'].retry, + default_timeout=method_configs['TestIamPermissions'].timeout, + client_info=client_info) + + # Service calls + def create_topic(self, + name, + labels=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Creates the given topic with the given name. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.PublisherClient() + >>> + >>> name = client.topic_path('[PROJECT]', '[TOPIC]') + >>> + >>> response = client.create_topic(name) + + Args: + name (str): The name of the topic. It must have the format + ``\"projects/{project}/topics/{topic}\"``. ``{topic}`` must start with a letter, + and contain only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), + underscores (``_``), periods (``.``), tildes (``~``), plus (``+``) or percent + signs (``%``). It must be between 3 and 255 characters in length, and it + must not start with ``\"goog\"``. + labels (dict[str -> str]): User labels. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.Topic` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.Topic(name=name, labels=labels) + return self._create_topic(request, retry=retry, timeout=timeout) + + def update_topic(self, + topic, + update_mask, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Updates an existing topic. Note that certain properties of a topic are not + modifiable. Options settings follow the style guide: + NOTE: The style guide requires body: \"topic\" instead of body: \"*\". + Keeping the latter for internal consistency in V1, however it should be + corrected in V2. See + https://cloud.google.com/apis/design/standard_methods#update for details. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.PublisherClient() + >>> + >>> topic = {} + >>> update_mask = {} + >>> + >>> response = client.update_topic(topic, update_mask) + + Args: + topic (Union[dict, ~google.cloud.pubsub_v1.types.Topic]): The topic to update. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.pubsub_v1.types.Topic` + update_mask (Union[dict, ~google.cloud.pubsub_v1.types.FieldMask]): Indicates which fields in the provided topic to update. + Must be specified and non-empty. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.pubsub_v1.types.FieldMask` + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.Topic` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.UpdateTopicRequest( + topic=topic, update_mask=update_mask) + return self._update_topic(request, retry=retry, timeout=timeout) + + def publish(self, + topic, + messages, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Adds one or more messages to the topic. Returns ``NOT_FOUND`` if the topic + does not exist. The message payload must not be empty; it must contain + either a non-empty data field, or at least one attribute. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.PublisherClient() + >>> + >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') + >>> data = b'' + >>> messages_element = {'data': data} + >>> messages = [messages_element] + >>> + >>> response = client.publish(topic, messages) + + Args: + topic (str): The messages in the request will be published on this topic. + Format is ``projects/{project}/topics/{topic}``. + messages (list[Union[dict, ~google.cloud.pubsub_v1.types.PubsubMessage]]): The messages to publish. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.pubsub_v1.types.PubsubMessage` + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.PublishResponse` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.PublishRequest(topic=topic, messages=messages) + return self._publish(request, retry=retry, timeout=timeout) + + def get_topic(self, + topic, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Gets the configuration of a topic. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.PublisherClient() + >>> + >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') + >>> + >>> response = client.get_topic(topic) + + Args: + topic (str): The name of the topic to get. + Format is ``projects/{project}/topics/{topic}``. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.Topic` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.GetTopicRequest(topic=topic) + return self._get_topic(request, retry=retry, timeout=timeout) + + def list_topics(self, + project, + page_size=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Lists matching topics. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.PublisherClient() + >>> + >>> project = client.project_path('[PROJECT]') + >>> + >>> + >>> # Iterate over all results + >>> for element in client.list_topics(project): + ... # process element + ... pass + >>> + >>> # Or iterate over results one page at a time + >>> for page in client.list_topics(project, options=CallOptions(page_token=INITIAL_PAGE)): + ... for element in page: + ... # process element + ... pass + + Args: + project (str): The name of the cloud project that topics belong to. + Format is ``projects/{project}``. + page_size (int): The maximum number of resources contained in the + underlying API response. If page streaming is performed per- + resource, this parameter does not affect the return value. If page + streaming is performed per-page, this determines the maximum number + of resources in a page. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.gax.PageIterator` instance. By default, this + is an iterable of :class:`~google.cloud.pubsub_v1.types.Topic` instances. + This object can also be configured to iterate over the pages + of the response through the `options` parameter. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.ListTopicsRequest( + project=project, page_size=page_size) + iterator = google.api_core.page_iterator.GRPCIterator( + client=None, + method=functools.partial( + self._list_topics, retry=retry, timeout=timeout), + request=request, + items_field='topics', + request_token_field='page_token', + response_token_field='next_page_token') + return iterator + + def list_topic_subscriptions( + self, + topic, + page_size=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Lists the name of the subscriptions for this topic. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.PublisherClient() + >>> + >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') + >>> + >>> + >>> # Iterate over all results + >>> for element in client.list_topic_subscriptions(topic): + ... # process element + ... pass + >>> + >>> # Or iterate over results one page at a time + >>> for page in client.list_topic_subscriptions(topic, options=CallOptions(page_token=INITIAL_PAGE)): + ... for element in page: + ... # process element + ... pass + + Args: + topic (str): The name of the topic that subscriptions are attached to. + Format is ``projects/{project}/topics/{topic}``. + page_size (int): The maximum number of resources contained in the + underlying API response. If page streaming is performed per- + resource, this parameter does not affect the return value. If page + streaming is performed per-page, this determines the maximum number + of resources in a page. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.gax.PageIterator` instance. By default, this + is an iterable of :class:`str` instances. + This object can also be configured to iterate over the pages + of the response through the `options` parameter. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.ListTopicSubscriptionsRequest( + topic=topic, page_size=page_size) + iterator = google.api_core.page_iterator.GRPCIterator( + client=None, + method=functools.partial( + self._list_topic_subscriptions, retry=retry, timeout=timeout), + request=request, + items_field='subscriptions', + request_token_field='page_token', + response_token_field='next_page_token') + return iterator + + def delete_topic(self, + topic, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Deletes the topic with the given name. Returns ``NOT_FOUND`` if the topic + does not exist. After a topic is deleted, a new topic may be created with + the same name; this is an entirely new topic with none of the old + configuration or subscriptions. Existing subscriptions to this topic are + not deleted, but their ``topic`` field is set to ``_deleted-topic_``. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.PublisherClient() + >>> + >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') + >>> + >>> client.delete_topic(topic) + + Args: + topic (str): Name of the topic to delete. + Format is ``projects/{project}/topics/{topic}``. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.DeleteTopicRequest(topic=topic) + self._delete_topic(request, retry=retry, timeout=timeout) + + def set_iam_policy(self, + resource, + policy, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Sets the access control policy on the specified resource. Replaces any + existing policy. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.PublisherClient() + >>> + >>> resource = client.topic_path('[PROJECT]', '[TOPIC]') + >>> policy = {} + >>> + >>> response = client.set_iam_policy(resource, policy) + + Args: + resource (str): REQUIRED: The resource for which the policy is being specified. + ``resource`` is usually specified as a path. For example, a Project + resource is specified as ``projects/{project}``. + policy (Union[dict, ~google.cloud.pubsub_v1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The size of + the policy is limited to a few 10s of KB. An empty policy is a + valid policy but certain Cloud Platform services (such as Projects) + might reject them. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.pubsub_v1.types.Policy` + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.Policy` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = iam_policy_pb2.SetIamPolicyRequest( + resource=resource, policy=policy) + return self._set_iam_policy(request, retry=retry, timeout=timeout) + + def get_iam_policy(self, + resource, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Gets the access control policy for a resource. + Returns an empty policy if the resource exists and does not have a policy + set. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.PublisherClient() + >>> + >>> resource = client.topic_path('[PROJECT]', '[TOPIC]') + >>> + >>> response = client.get_iam_policy(resource) + + Args: + resource (str): REQUIRED: The resource for which the policy is being requested. + ``resource`` is usually specified as a path. For example, a Project + resource is specified as ``projects/{project}``. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.Policy` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + return self._get_iam_policy(request, retry=retry, timeout=timeout) + + def test_iam_permissions(self, + resource, + permissions, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Returns permissions that a caller has on the specified resource. + If the resource does not exist, this will return an empty set of + permissions, not a NOT_FOUND error. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.PublisherClient() + >>> + >>> resource = client.topic_path('[PROJECT]', '[TOPIC]') + >>> permissions = [] + >>> + >>> response = client.test_iam_permissions(resource, permissions) + + Args: + resource (str): REQUIRED: The resource for which the policy detail is being requested. + ``resource`` is usually specified as a path. For example, a Project + resource is specified as ``projects/{project}``. + permissions (list[str]): The set of permissions to check for the ``resource``. Permissions with + wildcards (such as '*' or 'storage.*') are not allowed. For more + information see + `IAM Overview `_. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.TestIamPermissionsResponse` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions) + return self._test_iam_permissions( + request, retry=retry, timeout=timeout) diff --git a/pubsub/google/cloud/pubsub_v1/gapic/publisher_client_config.py b/pubsub/google/cloud/pubsub_v1/gapic/publisher_client_config.py new file mode 100644 index 000000000000..38aa0ca0ffbf --- /dev/null +++ b/pubsub/google/cloud/pubsub_v1/gapic/publisher_client_config.py @@ -0,0 +1,93 @@ +config = { + "interfaces": { + "google.pubsub.v1.Publisher": { + "retry_codes": { + "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "one_plus_delivery": [ + "ABORTED", "CANCELLED", "DEADLINE_EXCEEDED", "INTERNAL", + "RESOURCE_EXHAUSTED", "UNAVAILABLE", "UNKNOWN" + ], + "non_idempotent": [] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + }, + "messaging": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 12000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 30000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "CreateTopic": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "UpdateTopic": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "Publish": { + "timeout_millis": 60000, + "retry_codes_name": "one_plus_delivery", + "retry_params_name": "messaging", + "bundling": { + "element_count_threshold": 10, + "element_count_limit": 1000, + "request_byte_threshold": 1024, + "request_byte_limit": 10485760, + "delay_threshold_millis": 10 + } + }, + "GetTopic": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ListTopics": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ListTopicSubscriptions": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "DeleteTopic": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "SetIamPolicy": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetIamPolicy": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "TestIamPermissions": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/pubsub/google/cloud/pubsub_v1/gapic/subscriber_client.py b/pubsub/google/cloud/pubsub_v1/gapic/subscriber_client.py new file mode 100644 index 000000000000..c019bd9e295f --- /dev/null +++ b/pubsub/google/cloud/pubsub_v1/gapic/subscriber_client.py @@ -0,0 +1,1239 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.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. +# +# EDITING INSTRUCTIONS +# This file was generated from the file +# https://github.com/google/googleapis/blob/master/google/pubsub/v1/pubsub.proto, +# and updates to that file get reflected here through a refresh process. +# For the short term, the refresh process will only be runnable by Google engineers. +# +# The only allowed edits are to method and file documentation. A 3-way +# merge preserves those additions if the generated source changes. +"""Accesses the google.pubsub.v1 Subscriber API.""" + +import functools +import pkg_resources + +import google.api_core.gapic_v1.client_info +import google.api_core.gapic_v1.config +import google.api_core.gapic_v1.method +import google.api_core.grpc_helpers +import google.api_core.page_iterator +import google.api_core.path_template +import google.api_core.protobuf_helpers + +from google.cloud.pubsub_v1.gapic import subscriber_client_config +from google.cloud.pubsub_v1.proto import pubsub_pb2 +from google.iam.v1 import iam_policy_pb2 +from google.iam.v1 import policy_pb2 +from google.protobuf import duration_pb2 +from google.protobuf import field_mask_pb2 +from google.protobuf import timestamp_pb2 + +_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( + 'google-cloud-pubsub', ).version + + +class SubscriberClient(object): + """ + The service that an application uses to manipulate subscriptions and to + consume messages from a subscription via the ``Pull`` method. + """ + + SERVICE_ADDRESS = 'pubsub.googleapis.com:443' + """The default address of the service.""" + + # The scopes needed to make gRPC calls to all of the methods defined in + # this service + _DEFAULT_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', ) + + # The name of the interface for this client. This is the key used to find + # method configuration in the client_config dictionary + _INTERFACE_NAME = ('google.pubsub.v1.Subscriber') + + @classmethod + def project_path(cls, project): + """Returns a fully-qualified project resource name string.""" + return google.api_core.path_template.expand( + 'projects/{project}', + project=project, ) + + @classmethod + def snapshot_path(cls, project, snapshot): + """Returns a fully-qualified snapshot resource name string.""" + return google.api_core.path_template.expand( + 'projects/{project}/snapshots/{snapshot}', + project=project, + snapshot=snapshot, ) + + @classmethod + def subscription_path(cls, project, subscription): + """Returns a fully-qualified subscription resource name string.""" + return google.api_core.path_template.expand( + 'projects/{project}/subscriptions/{subscription}', + project=project, + subscription=subscription, ) + + @classmethod + def topic_path(cls, project, topic): + """Returns a fully-qualified topic resource name string.""" + return google.api_core.path_template.expand( + 'projects/{project}/topics/{topic}', + project=project, + topic=topic, ) + + def __init__(self, + channel=None, + credentials=None, + client_config=subscriber_client_config.config, + client_info=None): + """Constructor. + + Args: + channel (grpc.Channel): A ``Channel`` instance through + which to make calls. If specified, then the ``credentials`` + argument is ignored. + credentials (google.auth.credentials.Credentials): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_config (dict): + A dictionary of call options for each method. If not specified + the default configuration is used. Generally, you only need + to set this if you're developing your own client library. + 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. + """ + if channel is not None and credentials is not None: + raise ValueError( + 'channel and credentials arguments to {} are mutually ' + 'exclusive.'.format(self.__class__.__name__)) + + if channel is None: + channel = google.api_core.grpc_helpers.create_channel( + self.SERVICE_ADDRESS, + credentials=credentials, + scopes=self._DEFAULT_SCOPES) + + self.iam_policy_stub = (iam_policy_pb2.IAMPolicyStub(channel)) + self.subscriber_stub = (pubsub_pb2.SubscriberStub(channel)) + + if client_info is None: + client_info = ( + google.api_core.gapic_v1.client_info.DEFAULT_CLIENT_INFO) + + client_info.gapic_version = _GAPIC_LIBRARY_VERSION + + interface_config = client_config['interfaces'][self._INTERFACE_NAME] + method_configs = google.api_core.gapic_v1.config.parse_method_configs( + interface_config) + + self._create_subscription = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.CreateSubscription, + default_retry=method_configs['CreateSubscription'].retry, + default_timeout=method_configs['CreateSubscription'].timeout, + client_info=client_info) + self._get_subscription = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.GetSubscription, + default_retry=method_configs['GetSubscription'].retry, + default_timeout=method_configs['GetSubscription'].timeout, + client_info=client_info) + self._update_subscription = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.UpdateSubscription, + default_retry=method_configs['UpdateSubscription'].retry, + default_timeout=method_configs['UpdateSubscription'].timeout, + client_info=client_info) + self._list_subscriptions = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.ListSubscriptions, + default_retry=method_configs['ListSubscriptions'].retry, + default_timeout=method_configs['ListSubscriptions'].timeout, + client_info=client_info) + self._delete_subscription = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.DeleteSubscription, + default_retry=method_configs['DeleteSubscription'].retry, + default_timeout=method_configs['DeleteSubscription'].timeout, + client_info=client_info) + self._modify_ack_deadline = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.ModifyAckDeadline, + default_retry=method_configs['ModifyAckDeadline'].retry, + default_timeout=method_configs['ModifyAckDeadline'].timeout, + client_info=client_info) + self._acknowledge = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.Acknowledge, + default_retry=method_configs['Acknowledge'].retry, + default_timeout=method_configs['Acknowledge'].timeout, + client_info=client_info) + self._pull = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.Pull, + default_retry=method_configs['Pull'].retry, + default_timeout=method_configs['Pull'].timeout, + client_info=client_info) + self._streaming_pull = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.StreamingPull, + default_retry=method_configs['StreamingPull'].retry, + default_timeout=method_configs['StreamingPull'].timeout, + client_info=client_info) + self._modify_push_config = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.ModifyPushConfig, + default_retry=method_configs['ModifyPushConfig'].retry, + default_timeout=method_configs['ModifyPushConfig'].timeout, + client_info=client_info) + self._list_snapshots = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.ListSnapshots, + default_retry=method_configs['ListSnapshots'].retry, + default_timeout=method_configs['ListSnapshots'].timeout, + client_info=client_info) + self._create_snapshot = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.CreateSnapshot, + default_retry=method_configs['CreateSnapshot'].retry, + default_timeout=method_configs['CreateSnapshot'].timeout, + client_info=client_info) + self._update_snapshot = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.UpdateSnapshot, + default_retry=method_configs['UpdateSnapshot'].retry, + default_timeout=method_configs['UpdateSnapshot'].timeout, + client_info=client_info) + self._delete_snapshot = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.DeleteSnapshot, + default_retry=method_configs['DeleteSnapshot'].retry, + default_timeout=method_configs['DeleteSnapshot'].timeout, + client_info=client_info) + self._seek = google.api_core.gapic_v1.method.wrap_method( + self.subscriber_stub.Seek, + default_retry=method_configs['Seek'].retry, + default_timeout=method_configs['Seek'].timeout, + client_info=client_info) + self._set_iam_policy = google.api_core.gapic_v1.method.wrap_method( + self.iam_policy_stub.SetIamPolicy, + default_retry=method_configs['SetIamPolicy'].retry, + default_timeout=method_configs['SetIamPolicy'].timeout, + client_info=client_info) + self._get_iam_policy = google.api_core.gapic_v1.method.wrap_method( + self.iam_policy_stub.GetIamPolicy, + default_retry=method_configs['GetIamPolicy'].retry, + default_timeout=method_configs['GetIamPolicy'].timeout, + client_info=client_info) + self._test_iam_permissions = google.api_core.gapic_v1.method.wrap_method( + self.iam_policy_stub.TestIamPermissions, + default_retry=method_configs['TestIamPermissions'].retry, + default_timeout=method_configs['TestIamPermissions'].timeout, + client_info=client_info) + + # Service calls + def create_subscription(self, + name, + topic, + push_config=None, + ack_deadline_seconds=None, + retain_acked_messages=None, + message_retention_duration=None, + labels=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Creates a subscription to a given topic. + If the subscription already exists, returns ``ALREADY_EXISTS``. + If the corresponding topic doesn't exist, returns ``NOT_FOUND``. + + If the name is not provided in the request, the server will assign a random + name for this subscription on the same project as the topic, conforming + to the + `resource name format `_. + The generated name is populated in the returned Subscription object. + Note that for REST API requests, you must specify a name in the request. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> name = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') + >>> + >>> response = client.create_subscription(name, topic) + + Args: + name (str): The name of the subscription. It must have the format + ``\"projects/{project}/subscriptions/{subscription}\"``. ``{subscription}`` must + start with a letter, and contain only letters (``[A-Za-z]``), numbers + (``[0-9]``), dashes (``-``), underscores (``_``), periods (``.``), tildes (``~``), + plus (``+``) or percent signs (``%``). It must be between 3 and 255 characters + in length, and it must not start with ``\"goog\"``. + topic (str): The name of the topic from which this subscription is receiving messages. + Format is ``projects/{project}/topics/{topic}``. + The value of this field will be ``_deleted-topic_`` if the topic has been + deleted. + push_config (Union[dict, ~google.cloud.pubsub_v1.types.PushConfig]): If push delivery is used with this subscription, this field is + used to configure it. An empty ``pushConfig`` signifies that the subscriber + will pull and ack messages using API methods. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.pubsub_v1.types.PushConfig` + ack_deadline_seconds (int): This value is the maximum time after a subscriber receives a message + before the subscriber should acknowledge the message. After message + delivery but before the ack deadline expires and before the message is + acknowledged, it is an outstanding message and will not be delivered + again during that time (on a best-effort basis). + + For pull subscriptions, this value is used as the initial value for the ack + deadline. To override this value for a given message, call + ``ModifyAckDeadline`` with the corresponding ``ack_id`` if using + pull. + The minimum custom deadline you can specify is 10 seconds. + The maximum custom deadline you can specify is 600 seconds (10 minutes). + If this parameter is 0, a default value of 10 seconds is used. + + For push delivery, this value is also used to set the request timeout for + the call to the push endpoint. + + If the subscriber never acknowledges the message, the Pub/Sub + system will eventually redeliver the message. + retain_acked_messages (bool): Indicates whether to retain acknowledged messages. If true, then + messages are not expunged from the subscription's backlog, even if they are + acknowledged, until they fall out of the ``message_retention_duration`` + window. + message_retention_duration (Union[dict, ~google.cloud.pubsub_v1.types.Duration]): How long to retain unacknowledged messages in the subscription's backlog, + from the moment a message is published. + If ``retain_acked_messages`` is true, then this also configures the retention + of acknowledged messages, and thus configures how far back in time a ``Seek`` + can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 + minutes. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.pubsub_v1.types.Duration` + labels (dict[str -> str]): User labels. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.Subscription` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.Subscription( + name=name, + topic=topic, + push_config=push_config, + ack_deadline_seconds=ack_deadline_seconds, + retain_acked_messages=retain_acked_messages, + message_retention_duration=message_retention_duration, + labels=labels) + return self._create_subscription(request, retry=retry, timeout=timeout) + + def get_subscription(self, + subscription, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Gets the configuration details of a subscription. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + >>> + >>> response = client.get_subscription(subscription) + + Args: + subscription (str): The name of the subscription to get. + Format is ``projects/{project}/subscriptions/{sub}``. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.Subscription` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.GetSubscriptionRequest(subscription=subscription) + return self._get_subscription(request, retry=retry, timeout=timeout) + + def update_subscription(self, + subscription, + update_mask, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Updates an existing subscription. Note that certain properties of a + subscription, such as its topic, are not modifiable. + NOTE: The style guide requires body: \"subscription\" instead of body: \"*\". + Keeping the latter for internal consistency in V1, however it should be + corrected in V2. See + https://cloud.google.com/apis/design/standard_methods#update for details. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> subscription = {} + >>> update_mask = {} + >>> + >>> response = client.update_subscription(subscription, update_mask) + + Args: + subscription (Union[dict, ~google.cloud.pubsub_v1.types.Subscription]): The updated subscription object. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.pubsub_v1.types.Subscription` + update_mask (Union[dict, ~google.cloud.pubsub_v1.types.FieldMask]): Indicates which fields in the provided subscription to update. + Must be specified and non-empty. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.pubsub_v1.types.FieldMask` + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.Subscription` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.UpdateSubscriptionRequest( + subscription=subscription, update_mask=update_mask) + return self._update_subscription(request, retry=retry, timeout=timeout) + + def list_subscriptions(self, + project, + page_size=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Lists matching subscriptions. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> project = client.project_path('[PROJECT]') + >>> + >>> + >>> # Iterate over all results + >>> for element in client.list_subscriptions(project): + ... # process element + ... pass + >>> + >>> # Or iterate over results one page at a time + >>> for page in client.list_subscriptions(project, options=CallOptions(page_token=INITIAL_PAGE)): + ... for element in page: + ... # process element + ... pass + + Args: + project (str): The name of the cloud project that subscriptions belong to. + Format is ``projects/{project}``. + page_size (int): The maximum number of resources contained in the + underlying API response. If page streaming is performed per- + resource, this parameter does not affect the return value. If page + streaming is performed per-page, this determines the maximum number + of resources in a page. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.gax.PageIterator` instance. By default, this + is an iterable of :class:`~google.cloud.pubsub_v1.types.Subscription` instances. + This object can also be configured to iterate over the pages + of the response through the `options` parameter. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.ListSubscriptionsRequest( + project=project, page_size=page_size) + iterator = google.api_core.page_iterator.GRPCIterator( + client=None, + method=functools.partial( + self._list_subscriptions, retry=retry, timeout=timeout), + request=request, + items_field='subscriptions', + request_token_field='page_token', + response_token_field='next_page_token') + return iterator + + def delete_subscription(self, + subscription, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Deletes an existing subscription. All messages retained in the subscription + are immediately dropped. Calls to ``Pull`` after deletion will return + ``NOT_FOUND``. After a subscription is deleted, a new one may be created with + the same name, but the new one has no association with the old + subscription or its topic unless the same topic is specified. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + >>> + >>> client.delete_subscription(subscription) + + Args: + subscription (str): The subscription to delete. + Format is ``projects/{project}/subscriptions/{sub}``. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.DeleteSubscriptionRequest( + subscription=subscription) + self._delete_subscription(request, retry=retry, timeout=timeout) + + def modify_ack_deadline(self, + subscription, + ack_ids, + ack_deadline_seconds, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Modifies the ack deadline for a specific message. This method is useful + to indicate that more time is needed to process a message by the + subscriber, or to make the message available for redelivery if the + processing was interrupted. Note that this does not modify the + subscription-level ``ackDeadlineSeconds`` used for subsequent messages. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + >>> ack_ids = [] + >>> ack_deadline_seconds = 0 + >>> + >>> client.modify_ack_deadline(subscription, ack_ids, ack_deadline_seconds) + + Args: + subscription (str): The name of the subscription. + Format is ``projects/{project}/subscriptions/{sub}``. + ack_ids (list[str]): List of acknowledgment IDs. + ack_deadline_seconds (int): The new ack deadline with respect to the time this request was sent to + the Pub/Sub system. For example, if the value is 10, the new + ack deadline will expire 10 seconds after the ``ModifyAckDeadline`` call + was made. Specifying zero may immediately make the message available for + another pull request. + The minimum deadline you can specify is 0 seconds. + The maximum deadline you can specify is 600 seconds (10 minutes). + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.ModifyAckDeadlineRequest( + subscription=subscription, + ack_ids=ack_ids, + ack_deadline_seconds=ack_deadline_seconds) + self._modify_ack_deadline(request, retry=retry, timeout=timeout) + + def acknowledge(self, + subscription, + ack_ids, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Acknowledges the messages associated with the ``ack_ids`` in the + ``AcknowledgeRequest``. The Pub/Sub system can remove the relevant messages + from the subscription. + + Acknowledging a message whose ack deadline has expired may succeed, + but such a message may be redelivered later. Acknowledging a message more + than once will not result in an error. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + >>> ack_ids = [] + >>> + >>> client.acknowledge(subscription, ack_ids) + + Args: + subscription (str): The subscription whose message is being acknowledged. + Format is ``projects/{project}/subscriptions/{sub}``. + ack_ids (list[str]): The acknowledgment ID for the messages being acknowledged that was returned + by the Pub/Sub system in the ``Pull`` response. Must not be empty. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.AcknowledgeRequest( + subscription=subscription, ack_ids=ack_ids) + self._acknowledge(request, retry=retry, timeout=timeout) + + def pull(self, + subscription, + max_messages, + return_immediately=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Pulls messages from the server. Returns an empty list if there are no + messages available in the backlog. The server may return ``UNAVAILABLE`` if + there are too many concurrent pull requests pending for the given + subscription. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + >>> max_messages = 0 + >>> + >>> response = client.pull(subscription, max_messages) + + Args: + subscription (str): The subscription from which messages should be pulled. + Format is ``projects/{project}/subscriptions/{sub}``. + max_messages (int): The maximum number of messages returned for this request. The Pub/Sub + system may return fewer than the number specified. + return_immediately (bool): If this field set to true, the system will respond immediately even if + it there are no messages available to return in the ``Pull`` response. + Otherwise, the system may wait (for a bounded amount of time) until at + least one message is available, rather than returning no messages. The + client may cancel the request if it does not wish to wait any longer for + the response. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.PullResponse` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.PullRequest( + subscription=subscription, + max_messages=max_messages, + return_immediately=return_immediately) + return self._pull(request, retry=retry, timeout=timeout) + + def streaming_pull(self, + requests, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + (EXPERIMENTAL) StreamingPull is an experimental feature. This RPC will + respond with UNIMPLEMENTED errors unless you have been invited to test + this feature. Contact cloud-pubsub@google.com with any questions. + + Establishes a stream with the server, which sends messages down to the + client. The client streams acknowledgements and ack deadline modifications + back to the server. The server will close the stream and return the status + on any error. The server may close the stream with status ``OK`` to reassign + server-side resources, in which case, the client should re-establish the + stream. ``UNAVAILABLE`` may also be returned in the case of a transient error + (e.g., a server restart). These should also be retried by the client. Flow + control can be achieved by configuring the underlying RPC channel. + + EXPERIMENTAL: This method interface might change in the future. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + >>> stream_ack_deadline_seconds = 0 + >>> request = {'subscription': subscription, 'stream_ack_deadline_seconds': stream_ack_deadline_seconds} + >>> + >>> requests = [request] + >>> for element in client.streaming_pull(requests): + ... # process element + ... pass + + Args: + requests (iterator[dict|google.cloud.pubsub_v1.proto.pubsub_pb2.StreamingPullRequest]): The input objects. If a dict is provided, it must be of the + same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.StreamingPullRequest` + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + Iterable[~google.cloud.pubsub_v1.types.StreamingPullResponse]. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + return self._streaming_pull(requests, retry=retry, timeout=timeout) + + def modify_push_config(self, + subscription, + push_config, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Modifies the ``PushConfig`` for a specified subscription. + + This may be used to change a push subscription to a pull one (signified by + an empty ``PushConfig``) or vice versa, or change the endpoint URL and other + attributes of a push subscription. Messages will accumulate for delivery + continuously through the call regardless of changes to the ``PushConfig``. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + >>> push_config = {} + >>> + >>> client.modify_push_config(subscription, push_config) + + Args: + subscription (str): The name of the subscription. + Format is ``projects/{project}/subscriptions/{sub}``. + push_config (Union[dict, ~google.cloud.pubsub_v1.types.PushConfig]): The push configuration for future deliveries. + + An empty ``pushConfig`` indicates that the Pub/Sub system should + stop pushing messages from the given subscription and allow + messages to be pulled and acknowledged - effectively pausing + the subscription if ``Pull`` is not called. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.pubsub_v1.types.PushConfig` + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.ModifyPushConfigRequest( + subscription=subscription, push_config=push_config) + self._modify_push_config(request, retry=retry, timeout=timeout) + + def list_snapshots(self, + project, + page_size=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Lists the existing snapshots. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> project = client.project_path('[PROJECT]') + >>> + >>> + >>> # Iterate over all results + >>> for element in client.list_snapshots(project): + ... # process element + ... pass + >>> + >>> # Or iterate over results one page at a time + >>> for page in client.list_snapshots(project, options=CallOptions(page_token=INITIAL_PAGE)): + ... for element in page: + ... # process element + ... pass + + Args: + project (str): The name of the cloud project that snapshots belong to. + Format is ``projects/{project}``. + page_size (int): The maximum number of resources contained in the + underlying API response. If page streaming is performed per- + resource, this parameter does not affect the return value. If page + streaming is performed per-page, this determines the maximum number + of resources in a page. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.gax.PageIterator` instance. By default, this + is an iterable of :class:`~google.cloud.pubsub_v1.types.Snapshot` instances. + This object can also be configured to iterate over the pages + of the response through the `options` parameter. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.ListSnapshotsRequest( + project=project, page_size=page_size) + iterator = google.api_core.page_iterator.GRPCIterator( + client=None, + method=functools.partial( + self._list_snapshots, retry=retry, timeout=timeout), + request=request, + items_field='snapshots', + request_token_field='page_token', + response_token_field='next_page_token') + return iterator + + def create_snapshot(self, + name, + subscription, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Creates a snapshot from the requested subscription. + If the snapshot already exists, returns ``ALREADY_EXISTS``. + If the requested subscription doesn't exist, returns ``NOT_FOUND``. + + If the name is not provided in the request, the server will assign a random + name for this snapshot on the same project as the subscription, conforming + to the + `resource name format `_. + The generated name is populated in the returned Snapshot object. + Note that for REST API requests, you must specify a name in the request. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> name = client.snapshot_path('[PROJECT]', '[SNAPSHOT]') + >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + >>> + >>> response = client.create_snapshot(name, subscription) + + Args: + name (str): Optional user-provided name for this snapshot. + If the name is not provided in the request, the server will assign a random + name for this snapshot on the same project as the subscription. + Note that for REST API requests, you must specify a name. + Format is ``projects/{project}/snapshots/{snap}``. + subscription (str): The subscription whose backlog the snapshot retains. + Specifically, the created snapshot is guaranteed to retain: + + * The existing backlog on the subscription. More precisely, this is + defined as the messages in the subscription's backlog that are + unacknowledged upon the successful completion of the + `CreateSnapshot` request; as well as: + * Any messages published to the subscription's topic following the + successful completion of the CreateSnapshot request. + + Format is ``projects/{project}/subscriptions/{sub}``. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.Snapshot` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.CreateSnapshotRequest( + name=name, subscription=subscription) + return self._create_snapshot(request, retry=retry, timeout=timeout) + + def update_snapshot(self, + snapshot, + update_mask, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Updates an existing snapshot. Note that certain properties of a snapshot + are not modifiable. + NOTE: The style guide requires body: \"snapshot\" instead of body: \"*\". + Keeping the latter for internal consistency in V1, however it should be + corrected in V2. See + https://cloud.google.com/apis/design/standard_methods#update for details. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> snapshot = {} + >>> update_mask = {} + >>> + >>> response = client.update_snapshot(snapshot, update_mask) + + Args: + snapshot (Union[dict, ~google.cloud.pubsub_v1.types.Snapshot]): The updated snpashot object. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.pubsub_v1.types.Snapshot` + update_mask (Union[dict, ~google.cloud.pubsub_v1.types.FieldMask]): Indicates which fields in the provided snapshot to update. + Must be specified and non-empty. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.pubsub_v1.types.FieldMask` + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.Snapshot` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.UpdateSnapshotRequest( + snapshot=snapshot, update_mask=update_mask) + return self._update_snapshot(request, retry=retry, timeout=timeout) + + def delete_snapshot(self, + snapshot, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Removes an existing snapshot. All messages retained in the snapshot + are immediately dropped. After a snapshot is deleted, a new one may be + created with the same name, but the new one has no association with the old + snapshot or its subscription, unless the same subscription is specified. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> snapshot = client.snapshot_path('[PROJECT]', '[SNAPSHOT]') + >>> + >>> client.delete_snapshot(snapshot) + + Args: + snapshot (str): The name of the snapshot to delete. + Format is ``projects/{project}/snapshots/{snap}``. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = pubsub_pb2.DeleteSnapshotRequest(snapshot=snapshot) + self._delete_snapshot(request, retry=retry, timeout=timeout) + + def seek(self, + subscription, + time=None, + snapshot=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Seeks an existing subscription to a point in time or to a given snapshot, + whichever is provided in the request. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + >>> + >>> response = client.seek(subscription) + + Args: + subscription (str): The subscription to affect. + time (Union[dict, ~google.cloud.pubsub_v1.types.Timestamp]): The time to seek to. + Messages retained in the subscription that were published before this + time are marked as acknowledged, and messages retained in the + subscription that were published after this time are marked as + unacknowledged. Note that this operation affects only those messages + retained in the subscription (configured by the combination of + ``message_retention_duration`` and ``retain_acked_messages``). For example, + if ``time`` corresponds to a point before the message retention + window (or to a point before the system's notion of the subscription + creation time), only retained messages will be marked as unacknowledged, + and already-expunged messages will not be restored. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.pubsub_v1.types.Timestamp` + snapshot (str): The snapshot to seek to. The snapshot's topic must be the same as that of + the provided subscription. + Format is ``projects/{project}/snapshots/{snap}``. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.SeekResponse` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + # Sanity check: We have some fields which are mutually exclusive; + # raise ValueError if more than one is sent. + google.api_core.protobuf_helpers.check_oneof( + time=time, + snapshot=snapshot, ) + + request = pubsub_pb2.SeekRequest( + subscription=subscription, time=time, snapshot=snapshot) + return self._seek(request, retry=retry, timeout=timeout) + + def set_iam_policy(self, + resource, + policy, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Sets the access control policy on the specified resource. Replaces any + existing policy. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + >>> policy = {} + >>> + >>> response = client.set_iam_policy(resource, policy) + + Args: + resource (str): REQUIRED: The resource for which the policy is being specified. + ``resource`` is usually specified as a path. For example, a Project + resource is specified as ``projects/{project}``. + policy (Union[dict, ~google.cloud.pubsub_v1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The size of + the policy is limited to a few 10s of KB. An empty policy is a + valid policy but certain Cloud Platform services (such as Projects) + might reject them. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.pubsub_v1.types.Policy` + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.Policy` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = iam_policy_pb2.SetIamPolicyRequest( + resource=resource, policy=policy) + return self._set_iam_policy(request, retry=retry, timeout=timeout) + + def get_iam_policy(self, + resource, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Gets the access control policy for a resource. + Returns an empty policy if the resource exists and does not have a policy + set. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + >>> + >>> response = client.get_iam_policy(resource) + + Args: + resource (str): REQUIRED: The resource for which the policy is being requested. + ``resource`` is usually specified as a path. For example, a Project + resource is specified as ``projects/{project}``. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.Policy` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + return self._get_iam_policy(request, retry=retry, timeout=timeout) + + def test_iam_permissions(self, + resource, + permissions, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT): + """ + Returns permissions that a caller has on the specified resource. + If the resource does not exist, this will return an empty set of + permissions, not a NOT_FOUND error. + + Example: + >>> from google.cloud import pubsub_v1 + >>> + >>> client = pubsub_v1.SubscriberClient() + >>> + >>> resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + >>> permissions = [] + >>> + >>> response = client.test_iam_permissions(resource, permissions) + + Args: + resource (str): REQUIRED: The resource for which the policy detail is being requested. + ``resource`` is usually specified as a path. For example, a Project + resource is specified as ``projects/{project}``. + permissions (list[str]): The set of permissions to check for the ``resource``. Permissions with + wildcards (such as '*' or 'storage.*') are not allowed. For more + information see + `IAM Overview `_. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will not + be retried. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + + Returns: + A :class:`~google.cloud.pubsub_v1.types.TestIamPermissionsResponse` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions) + return self._test_iam_permissions( + request, retry=retry, timeout=timeout) diff --git a/pubsub/google/cloud/pubsub_v1/gapic/subscriber_client_config.py b/pubsub/google/cloud/pubsub_v1/gapic/subscriber_client_config.py new file mode 100644 index 000000000000..896d2002cb12 --- /dev/null +++ b/pubsub/google/cloud/pubsub_v1/gapic/subscriber_client_config.py @@ -0,0 +1,135 @@ +config = { + "interfaces": { + "google.pubsub.v1.Subscriber": { + "retry_codes": { + "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "non_idempotent": [], + "pull": [ + "CANCELLED", "DEADLINE_EXCEEDED", "INTERNAL", + "RESOURCE_EXHAUSTED", "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + }, + "messaging": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 12000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 12000, + "total_timeout_millis": 600000 + }, + "streaming_messaging": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 600000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 600000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "CreateSubscription": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "GetSubscription": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "UpdateSubscription": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ListSubscriptions": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "DeleteSubscription": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ModifyAckDeadline": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Acknowledge": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "messaging" + }, + "Pull": { + "timeout_millis": 60000, + "retry_codes_name": "pull", + "retry_params_name": "messaging" + }, + "StreamingPull": { + "timeout_millis": 60000, + "retry_codes_name": "pull", + "retry_params_name": "streaming_messaging" + }, + "ModifyPushConfig": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListSnapshots": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "CreateSnapshot": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "UpdateSnapshot": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "DeleteSnapshot": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "Seek": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "SetIamPolicy": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetIamPolicy": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "TestIamPermissions": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/pubsub/google/cloud/pubsub_v1/proto/__init__.py b/pubsub/google/cloud/pubsub_v1/proto/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/pubsub/google/cloud/proto/pubsub/v1/pubsub_pb2.py b/pubsub/google/cloud/pubsub_v1/proto/pubsub_pb2.py similarity index 98% rename from pubsub/google/cloud/proto/pubsub/v1/pubsub_pb2.py rename to pubsub/google/cloud/pubsub_v1/proto/pubsub_pb2.py index aeee99e182d0..932c7c1a7ac0 100644 --- a/pubsub/google/cloud/proto/pubsub/v1/pubsub_pb2.py +++ b/pubsub/google/cloud/pubsub_v1/proto/pubsub_pb2.py @@ -1,5 +1,5 @@ # Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/proto/pubsub/v1/pubsub.proto +# source: google/cloud/pubsub_v1/proto/pubsub.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) @@ -21,13 +21,12 @@ DESCRIPTOR = _descriptor.FileDescriptor( - name='google/cloud/proto/pubsub/v1/pubsub.proto', + name='google/cloud/pubsub_v1/proto/pubsub.proto', package='google.pubsub.v1', syntax='proto3', - serialized_pb=_b('\n)google/cloud/proto/pubsub/v1/pubsub.proto\x12\x10google.pubsub.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"y\n\x05Topic\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x33\n\x06labels\x18\x02 \x03(\x0b\x32#.google.pubsub.v1.Topic.LabelsEntry\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xdb\x01\n\rPubsubMessage\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\x12\x43\n\nattributes\x18\x02 \x03(\x0b\x32/.google.pubsub.v1.PubsubMessage.AttributesEntry\x12\x12\n\nmessage_id\x18\x03 \x01(\t\x12\x30\n\x0cpublish_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1a\x31\n\x0f\x41ttributesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\" \n\x0fGetTopicRequest\x12\r\n\x05topic\x18\x01 \x01(\t\"m\n\x12UpdateTopicRequest\x12&\n\x05topic\x18\x01 \x01(\x0b\x32\x17.google.pubsub.v1.Topic\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\"R\n\x0ePublishRequest\x12\r\n\x05topic\x18\x01 \x01(\t\x12\x31\n\x08messages\x18\x02 \x03(\x0b\x32\x1f.google.pubsub.v1.PubsubMessage\"&\n\x0fPublishResponse\x12\x13\n\x0bmessage_ids\x18\x01 \x03(\t\"K\n\x11ListTopicsRequest\x12\x0f\n\x07project\x18\x01 \x01(\t\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t\"V\n\x12ListTopicsResponse\x12\'\n\x06topics\x18\x01 \x03(\x0b\x32\x17.google.pubsub.v1.Topic\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\"U\n\x1dListTopicSubscriptionsRequest\x12\r\n\x05topic\x18\x01 \x01(\t\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t\"P\n\x1eListTopicSubscriptionsResponse\x12\x15\n\rsubscriptions\x18\x01 \x03(\t\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\"#\n\x12\x44\x65leteTopicRequest\x12\r\n\x05topic\x18\x01 \x01(\t\"\xc5\x02\n\x0cSubscription\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05topic\x18\x02 \x01(\t\x12\x31\n\x0bpush_config\x18\x04 \x01(\x0b\x32\x1c.google.pubsub.v1.PushConfig\x12\x1c\n\x14\x61\x63k_deadline_seconds\x18\x05 \x01(\x05\x12\x1d\n\x15retain_acked_messages\x18\x07 \x01(\x08\x12=\n\x1amessage_retention_duration\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12:\n\x06labels\x18\t \x03(\x0b\x32*.google.pubsub.v1.Subscription.LabelsEntry\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x98\x01\n\nPushConfig\x12\x15\n\rpush_endpoint\x18\x01 \x01(\t\x12@\n\nattributes\x18\x02 \x03(\x0b\x32,.google.pubsub.v1.PushConfig.AttributesEntry\x1a\x31\n\x0f\x41ttributesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"S\n\x0fReceivedMessage\x12\x0e\n\x06\x61\x63k_id\x18\x01 \x01(\t\x12\x30\n\x07message\x18\x02 \x01(\x0b\x32\x1f.google.pubsub.v1.PubsubMessage\".\n\x16GetSubscriptionRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\"\x82\x01\n\x19UpdateSubscriptionRequest\x12\x34\n\x0csubscription\x18\x01 \x01(\x0b\x32\x1e.google.pubsub.v1.Subscription\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\"R\n\x18ListSubscriptionsRequest\x12\x0f\n\x07project\x18\x01 \x01(\t\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t\"k\n\x19ListSubscriptionsResponse\x12\x35\n\rsubscriptions\x18\x01 \x03(\x0b\x32\x1e.google.pubsub.v1.Subscription\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\"1\n\x19\x44\x65leteSubscriptionRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\"b\n\x17ModifyPushConfigRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\x12\x31\n\x0bpush_config\x18\x02 \x01(\x0b\x32\x1c.google.pubsub.v1.PushConfig\"U\n\x0bPullRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\x12\x1a\n\x12return_immediately\x18\x02 \x01(\x08\x12\x14\n\x0cmax_messages\x18\x03 \x01(\x05\"L\n\x0cPullResponse\x12<\n\x11received_messages\x18\x01 \x03(\x0b\x32!.google.pubsub.v1.ReceivedMessage\"_\n\x18ModifyAckDeadlineRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\x12\x0f\n\x07\x61\x63k_ids\x18\x04 \x03(\t\x12\x1c\n\x14\x61\x63k_deadline_seconds\x18\x03 \x01(\x05\";\n\x12\x41\x63knowledgeRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\x12\x0f\n\x07\x61\x63k_ids\x18\x02 \x03(\t\"\xa4\x01\n\x14StreamingPullRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\x12\x0f\n\x07\x61\x63k_ids\x18\x02 \x03(\t\x12\x1f\n\x17modify_deadline_seconds\x18\x03 \x03(\x05\x12\x1f\n\x17modify_deadline_ack_ids\x18\x04 \x03(\t\x12#\n\x1bstream_ack_deadline_seconds\x18\x05 \x01(\x05\"U\n\x15StreamingPullResponse\x12<\n\x11received_messages\x18\x01 \x03(\x0b\x32!.google.pubsub.v1.ReceivedMessage\";\n\x15\x43reateSnapshotRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0csubscription\x18\x02 \x01(\t\"v\n\x15UpdateSnapshotRequest\x12,\n\x08snapshot\x18\x01 \x01(\x0b\x32\x1a.google.pubsub.v1.Snapshot\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\"\xbf\x01\n\x08Snapshot\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05topic\x18\x02 \x01(\t\x12/\n\x0b\x65xpire_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x36\n\x06labels\x18\x04 \x03(\x0b\x32&.google.pubsub.v1.Snapshot.LabelsEntry\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"N\n\x14ListSnapshotsRequest\x12\x0f\n\x07project\x18\x01 \x01(\t\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t\"_\n\x15ListSnapshotsResponse\x12-\n\tsnapshots\x18\x01 \x03(\x0b\x32\x1a.google.pubsub.v1.Snapshot\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\")\n\x15\x44\x65leteSnapshotRequest\x12\x10\n\x08snapshot\x18\x01 \x01(\t\"m\n\x0bSeekRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\x12*\n\x04time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.TimestampH\x00\x12\x12\n\x08snapshot\x18\x03 \x01(\tH\x00\x42\x08\n\x06target\"\x0e\n\x0cSeekResponse2\xf7\x10\n\nSubscriber\x12\x86\x01\n\x12\x43reateSubscription\x12\x1e.google.pubsub.v1.Subscription\x1a\x1e.google.pubsub.v1.Subscription\"0\x82\xd3\xe4\x93\x02*\x1a%/v1/{name=projects/*/subscriptions/*}:\x01*\x12\x92\x01\n\x0fGetSubscription\x12(.google.pubsub.v1.GetSubscriptionRequest\x1a\x1e.google.pubsub.v1.Subscription\"5\x82\xd3\xe4\x93\x02/\x12-/v1/{subscription=projects/*/subscriptions/*}\x12\xa0\x01\n\x12UpdateSubscription\x12+.google.pubsub.v1.UpdateSubscriptionRequest\x1a\x1e.google.pubsub.v1.Subscription\"=\x82\xd3\xe4\x93\x02\x37\x32\x32/v1/{subscription.name=projects/*/subscriptions/*}:\x01*\x12\x9c\x01\n\x11ListSubscriptions\x12*.google.pubsub.v1.ListSubscriptionsRequest\x1a+.google.pubsub.v1.ListSubscriptionsResponse\".\x82\xd3\xe4\x93\x02(\x12&/v1/{project=projects/*}/subscriptions\x12\x90\x01\n\x12\x44\x65leteSubscription\x12+.google.pubsub.v1.DeleteSubscriptionRequest\x1a\x16.google.protobuf.Empty\"5\x82\xd3\xe4\x93\x02/*-/v1/{subscription=projects/*/subscriptions/*}\x12\xa3\x01\n\x11ModifyAckDeadline\x12*.google.pubsub.v1.ModifyAckDeadlineRequest\x1a\x16.google.protobuf.Empty\"J\x82\xd3\xe4\x93\x02\x44\"?/v1/{subscription=projects/*/subscriptions/*}:modifyAckDeadline:\x01*\x12\x91\x01\n\x0b\x41\x63knowledge\x12$.google.pubsub.v1.AcknowledgeRequest\x1a\x16.google.protobuf.Empty\"D\x82\xd3\xe4\x93\x02>\"9/v1/{subscription=projects/*/subscriptions/*}:acknowledge:\x01*\x12\x84\x01\n\x04Pull\x12\x1d.google.pubsub.v1.PullRequest\x1a\x1e.google.pubsub.v1.PullResponse\"=\x82\xd3\xe4\x93\x02\x37\"2/v1/{subscription=projects/*/subscriptions/*}:pull:\x01*\x12\x64\n\rStreamingPull\x12&.google.pubsub.v1.StreamingPullRequest\x1a\'.google.pubsub.v1.StreamingPullResponse(\x01\x30\x01\x12\xa0\x01\n\x10ModifyPushConfig\x12).google.pubsub.v1.ModifyPushConfigRequest\x1a\x16.google.protobuf.Empty\"I\x82\xd3\xe4\x93\x02\x43\">/v1/{subscription=projects/*/subscriptions/*}:modifyPushConfig:\x01*\x12\x8c\x01\n\rListSnapshots\x12&.google.pubsub.v1.ListSnapshotsRequest\x1a\'.google.pubsub.v1.ListSnapshotsResponse\"*\x82\xd3\xe4\x93\x02$\x12\"/v1/{project=projects/*}/snapshots\x12\x83\x01\n\x0e\x43reateSnapshot\x12\'.google.pubsub.v1.CreateSnapshotRequest\x1a\x1a.google.pubsub.v1.Snapshot\",\x82\xd3\xe4\x93\x02&\x1a!/v1/{name=projects/*/snapshots/*}:\x01*\x12\x8c\x01\n\x0eUpdateSnapshot\x12\'.google.pubsub.v1.UpdateSnapshotRequest\x1a\x1a.google.pubsub.v1.Snapshot\"5\x82\xd3\xe4\x93\x02/2*/v1/{snapshot.name=projects/*/snapshots/*}:\x01*\x12\x80\x01\n\x0e\x44\x65leteSnapshot\x12\'.google.pubsub.v1.DeleteSnapshotRequest\x1a\x16.google.protobuf.Empty\"-\x82\xd3\xe4\x93\x02\'*%/v1/{snapshot=projects/*/snapshots/*}\x12\x84\x01\n\x04Seek\x12\x1d.google.pubsub.v1.SeekRequest\x1a\x1e.google.pubsub.v1.SeekResponse\"=\x82\xd3\xe4\x93\x02\x37\"2/v1/{subscription=projects/*/subscriptions/*}:seek:\x01*2\x9a\x07\n\tPublisher\x12j\n\x0b\x43reateTopic\x12\x17.google.pubsub.v1.Topic\x1a\x17.google.pubsub.v1.Topic\")\x82\xd3\xe4\x93\x02#\x1a\x1e/v1/{name=projects/*/topics/*}:\x01*\x12}\n\x0bUpdateTopic\x12$.google.pubsub.v1.UpdateTopicRequest\x1a\x17.google.pubsub.v1.Topic\"/\x82\xd3\xe4\x93\x02)2$/v1/{topic.name=projects/*/topics/*}:\x01*\x12\x82\x01\n\x07Publish\x12 .google.pubsub.v1.PublishRequest\x1a!.google.pubsub.v1.PublishResponse\"2\x82\xd3\xe4\x93\x02,\"\'/v1/{topic=projects/*/topics/*}:publish:\x01*\x12o\n\x08GetTopic\x12!.google.pubsub.v1.GetTopicRequest\x1a\x17.google.pubsub.v1.Topic\"\'\x82\xd3\xe4\x93\x02!\x12\x1f/v1/{topic=projects/*/topics/*}\x12\x80\x01\n\nListTopics\x12#.google.pubsub.v1.ListTopicsRequest\x1a$.google.pubsub.v1.ListTopicsResponse\"\'\x82\xd3\xe4\x93\x02!\x12\x1f/v1/{project=projects/*}/topics\x12\xb2\x01\n\x16ListTopicSubscriptions\x12/.google.pubsub.v1.ListTopicSubscriptionsRequest\x1a\x30.google.pubsub.v1.ListTopicSubscriptionsResponse\"5\x82\xd3\xe4\x93\x02/\x12-/v1/{topic=projects/*/topics/*}/subscriptions\x12t\n\x0b\x44\x65leteTopic\x12$.google.pubsub.v1.DeleteTopicRequest\x1a\x16.google.protobuf.Empty\"\'\x82\xd3\xe4\x93\x02!*\x1f/v1/{topic=projects/*/topics/*}By\n\x14\x63om.google.pubsub.v1B\x0bPubsubProtoP\x01Z6google.golang.org/genproto/googleapis/pubsub/v1;pubsub\xf8\x01\x01\xaa\x02\x16Google.Cloud.PubSub.V1b\x06proto3') + serialized_pb=_b('\n)google/cloud/pubsub_v1/proto/pubsub.proto\x12\x10google.pubsub.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"y\n\x05Topic\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x33\n\x06labels\x18\x02 \x03(\x0b\x32#.google.pubsub.v1.Topic.LabelsEntry\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xdb\x01\n\rPubsubMessage\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\x12\x43\n\nattributes\x18\x02 \x03(\x0b\x32/.google.pubsub.v1.PubsubMessage.AttributesEntry\x12\x12\n\nmessage_id\x18\x03 \x01(\t\x12\x30\n\x0cpublish_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1a\x31\n\x0f\x41ttributesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\" \n\x0fGetTopicRequest\x12\r\n\x05topic\x18\x01 \x01(\t\"m\n\x12UpdateTopicRequest\x12&\n\x05topic\x18\x01 \x01(\x0b\x32\x17.google.pubsub.v1.Topic\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\"R\n\x0ePublishRequest\x12\r\n\x05topic\x18\x01 \x01(\t\x12\x31\n\x08messages\x18\x02 \x03(\x0b\x32\x1f.google.pubsub.v1.PubsubMessage\"&\n\x0fPublishResponse\x12\x13\n\x0bmessage_ids\x18\x01 \x03(\t\"K\n\x11ListTopicsRequest\x12\x0f\n\x07project\x18\x01 \x01(\t\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t\"V\n\x12ListTopicsResponse\x12\'\n\x06topics\x18\x01 \x03(\x0b\x32\x17.google.pubsub.v1.Topic\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\"U\n\x1dListTopicSubscriptionsRequest\x12\r\n\x05topic\x18\x01 \x01(\t\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t\"P\n\x1eListTopicSubscriptionsResponse\x12\x15\n\rsubscriptions\x18\x01 \x03(\t\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\"#\n\x12\x44\x65leteTopicRequest\x12\r\n\x05topic\x18\x01 \x01(\t\"\xc5\x02\n\x0cSubscription\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05topic\x18\x02 \x01(\t\x12\x31\n\x0bpush_config\x18\x04 \x01(\x0b\x32\x1c.google.pubsub.v1.PushConfig\x12\x1c\n\x14\x61\x63k_deadline_seconds\x18\x05 \x01(\x05\x12\x1d\n\x15retain_acked_messages\x18\x07 \x01(\x08\x12=\n\x1amessage_retention_duration\x18\x08 \x01(\x0b\x32\x19.google.protobuf.Duration\x12:\n\x06labels\x18\t \x03(\x0b\x32*.google.pubsub.v1.Subscription.LabelsEntry\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x98\x01\n\nPushConfig\x12\x15\n\rpush_endpoint\x18\x01 \x01(\t\x12@\n\nattributes\x18\x02 \x03(\x0b\x32,.google.pubsub.v1.PushConfig.AttributesEntry\x1a\x31\n\x0f\x41ttributesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"S\n\x0fReceivedMessage\x12\x0e\n\x06\x61\x63k_id\x18\x01 \x01(\t\x12\x30\n\x07message\x18\x02 \x01(\x0b\x32\x1f.google.pubsub.v1.PubsubMessage\".\n\x16GetSubscriptionRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\"\x82\x01\n\x19UpdateSubscriptionRequest\x12\x34\n\x0csubscription\x18\x01 \x01(\x0b\x32\x1e.google.pubsub.v1.Subscription\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\"R\n\x18ListSubscriptionsRequest\x12\x0f\n\x07project\x18\x01 \x01(\t\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t\"k\n\x19ListSubscriptionsResponse\x12\x35\n\rsubscriptions\x18\x01 \x03(\x0b\x32\x1e.google.pubsub.v1.Subscription\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\"1\n\x19\x44\x65leteSubscriptionRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\"b\n\x17ModifyPushConfigRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\x12\x31\n\x0bpush_config\x18\x02 \x01(\x0b\x32\x1c.google.pubsub.v1.PushConfig\"U\n\x0bPullRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\x12\x1a\n\x12return_immediately\x18\x02 \x01(\x08\x12\x14\n\x0cmax_messages\x18\x03 \x01(\x05\"L\n\x0cPullResponse\x12<\n\x11received_messages\x18\x01 \x03(\x0b\x32!.google.pubsub.v1.ReceivedMessage\"_\n\x18ModifyAckDeadlineRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\x12\x0f\n\x07\x61\x63k_ids\x18\x04 \x03(\t\x12\x1c\n\x14\x61\x63k_deadline_seconds\x18\x03 \x01(\x05\";\n\x12\x41\x63knowledgeRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\x12\x0f\n\x07\x61\x63k_ids\x18\x02 \x03(\t\"\xa4\x01\n\x14StreamingPullRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\x12\x0f\n\x07\x61\x63k_ids\x18\x02 \x03(\t\x12\x1f\n\x17modify_deadline_seconds\x18\x03 \x03(\x05\x12\x1f\n\x17modify_deadline_ack_ids\x18\x04 \x03(\t\x12#\n\x1bstream_ack_deadline_seconds\x18\x05 \x01(\x05\"U\n\x15StreamingPullResponse\x12<\n\x11received_messages\x18\x01 \x03(\x0b\x32!.google.pubsub.v1.ReceivedMessage\";\n\x15\x43reateSnapshotRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0csubscription\x18\x02 \x01(\t\"v\n\x15UpdateSnapshotRequest\x12,\n\x08snapshot\x18\x01 \x01(\x0b\x32\x1a.google.pubsub.v1.Snapshot\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\"\xbf\x01\n\x08Snapshot\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05topic\x18\x02 \x01(\t\x12/\n\x0b\x65xpire_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x36\n\x06labels\x18\x04 \x03(\x0b\x32&.google.pubsub.v1.Snapshot.LabelsEntry\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"N\n\x14ListSnapshotsRequest\x12\x0f\n\x07project\x18\x01 \x01(\t\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t\"_\n\x15ListSnapshotsResponse\x12-\n\tsnapshots\x18\x01 \x03(\x0b\x32\x1a.google.pubsub.v1.Snapshot\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\")\n\x15\x44\x65leteSnapshotRequest\x12\x10\n\x08snapshot\x18\x01 \x01(\t\"m\n\x0bSeekRequest\x12\x14\n\x0csubscription\x18\x01 \x01(\t\x12*\n\x04time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.TimestampH\x00\x12\x12\n\x08snapshot\x18\x03 \x01(\tH\x00\x42\x08\n\x06target\"\x0e\n\x0cSeekResponse2\xf7\x10\n\nSubscriber\x12\x86\x01\n\x12\x43reateSubscription\x12\x1e.google.pubsub.v1.Subscription\x1a\x1e.google.pubsub.v1.Subscription\"0\x82\xd3\xe4\x93\x02*\x1a%/v1/{name=projects/*/subscriptions/*}:\x01*\x12\x92\x01\n\x0fGetSubscription\x12(.google.pubsub.v1.GetSubscriptionRequest\x1a\x1e.google.pubsub.v1.Subscription\"5\x82\xd3\xe4\x93\x02/\x12-/v1/{subscription=projects/*/subscriptions/*}\x12\xa0\x01\n\x12UpdateSubscription\x12+.google.pubsub.v1.UpdateSubscriptionRequest\x1a\x1e.google.pubsub.v1.Subscription\"=\x82\xd3\xe4\x93\x02\x37\x32\x32/v1/{subscription.name=projects/*/subscriptions/*}:\x01*\x12\x9c\x01\n\x11ListSubscriptions\x12*.google.pubsub.v1.ListSubscriptionsRequest\x1a+.google.pubsub.v1.ListSubscriptionsResponse\".\x82\xd3\xe4\x93\x02(\x12&/v1/{project=projects/*}/subscriptions\x12\x90\x01\n\x12\x44\x65leteSubscription\x12+.google.pubsub.v1.DeleteSubscriptionRequest\x1a\x16.google.protobuf.Empty\"5\x82\xd3\xe4\x93\x02/*-/v1/{subscription=projects/*/subscriptions/*}\x12\xa3\x01\n\x11ModifyAckDeadline\x12*.google.pubsub.v1.ModifyAckDeadlineRequest\x1a\x16.google.protobuf.Empty\"J\x82\xd3\xe4\x93\x02\x44\"?/v1/{subscription=projects/*/subscriptions/*}:modifyAckDeadline:\x01*\x12\x91\x01\n\x0b\x41\x63knowledge\x12$.google.pubsub.v1.AcknowledgeRequest\x1a\x16.google.protobuf.Empty\"D\x82\xd3\xe4\x93\x02>\"9/v1/{subscription=projects/*/subscriptions/*}:acknowledge:\x01*\x12\x84\x01\n\x04Pull\x12\x1d.google.pubsub.v1.PullRequest\x1a\x1e.google.pubsub.v1.PullResponse\"=\x82\xd3\xe4\x93\x02\x37\"2/v1/{subscription=projects/*/subscriptions/*}:pull:\x01*\x12\x64\n\rStreamingPull\x12&.google.pubsub.v1.StreamingPullRequest\x1a\'.google.pubsub.v1.StreamingPullResponse(\x01\x30\x01\x12\xa0\x01\n\x10ModifyPushConfig\x12).google.pubsub.v1.ModifyPushConfigRequest\x1a\x16.google.protobuf.Empty\"I\x82\xd3\xe4\x93\x02\x43\">/v1/{subscription=projects/*/subscriptions/*}:modifyPushConfig:\x01*\x12\x8c\x01\n\rListSnapshots\x12&.google.pubsub.v1.ListSnapshotsRequest\x1a\'.google.pubsub.v1.ListSnapshotsResponse\"*\x82\xd3\xe4\x93\x02$\x12\"/v1/{project=projects/*}/snapshots\x12\x83\x01\n\x0e\x43reateSnapshot\x12\'.google.pubsub.v1.CreateSnapshotRequest\x1a\x1a.google.pubsub.v1.Snapshot\",\x82\xd3\xe4\x93\x02&\x1a!/v1/{name=projects/*/snapshots/*}:\x01*\x12\x8c\x01\n\x0eUpdateSnapshot\x12\'.google.pubsub.v1.UpdateSnapshotRequest\x1a\x1a.google.pubsub.v1.Snapshot\"5\x82\xd3\xe4\x93\x02/2*/v1/{snapshot.name=projects/*/snapshots/*}:\x01*\x12\x80\x01\n\x0e\x44\x65leteSnapshot\x12\'.google.pubsub.v1.DeleteSnapshotRequest\x1a\x16.google.protobuf.Empty\"-\x82\xd3\xe4\x93\x02\'*%/v1/{snapshot=projects/*/snapshots/*}\x12\x84\x01\n\x04Seek\x12\x1d.google.pubsub.v1.SeekRequest\x1a\x1e.google.pubsub.v1.SeekResponse\"=\x82\xd3\xe4\x93\x02\x37\"2/v1/{subscription=projects/*/subscriptions/*}:seek:\x01*2\x9a\x07\n\tPublisher\x12j\n\x0b\x43reateTopic\x12\x17.google.pubsub.v1.Topic\x1a\x17.google.pubsub.v1.Topic\")\x82\xd3\xe4\x93\x02#\x1a\x1e/v1/{name=projects/*/topics/*}:\x01*\x12}\n\x0bUpdateTopic\x12$.google.pubsub.v1.UpdateTopicRequest\x1a\x17.google.pubsub.v1.Topic\"/\x82\xd3\xe4\x93\x02)2$/v1/{topic.name=projects/*/topics/*}:\x01*\x12\x82\x01\n\x07Publish\x12 .google.pubsub.v1.PublishRequest\x1a!.google.pubsub.v1.PublishResponse\"2\x82\xd3\xe4\x93\x02,\"\'/v1/{topic=projects/*/topics/*}:publish:\x01*\x12o\n\x08GetTopic\x12!.google.pubsub.v1.GetTopicRequest\x1a\x17.google.pubsub.v1.Topic\"\'\x82\xd3\xe4\x93\x02!\x12\x1f/v1/{topic=projects/*/topics/*}\x12\x80\x01\n\nListTopics\x12#.google.pubsub.v1.ListTopicsRequest\x1a$.google.pubsub.v1.ListTopicsResponse\"\'\x82\xd3\xe4\x93\x02!\x12\x1f/v1/{project=projects/*}/topics\x12\xb2\x01\n\x16ListTopicSubscriptions\x12/.google.pubsub.v1.ListTopicSubscriptionsRequest\x1a\x30.google.pubsub.v1.ListTopicSubscriptionsResponse\"5\x82\xd3\xe4\x93\x02/\x12-/v1/{topic=projects/*/topics/*}/subscriptions\x12t\n\x0b\x44\x65leteTopic\x12$.google.pubsub.v1.DeleteTopicRequest\x1a\x16.google.protobuf.Empty\"\'\x82\xd3\xe4\x93\x02!*\x1f/v1/{topic=projects/*/topics/*}By\n\x14\x63om.google.pubsub.v1B\x0bPubsubProtoP\x01Z6google.golang.org/genproto/googleapis/pubsub/v1;pubsub\xf8\x01\x01\xaa\x02\x16Google.Cloud.PubSub.V1b\x06proto3') , dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_protobuf_dot_duration__pb2.DESCRIPTOR,google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR,google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,]) -_sym_db.RegisterFileDescriptor(DESCRIPTOR) @@ -1643,17 +1642,18 @@ DESCRIPTOR.message_types_by_name['DeleteSnapshotRequest'] = _DELETESNAPSHOTREQUEST DESCRIPTOR.message_types_by_name['SeekRequest'] = _SEEKREQUEST DESCRIPTOR.message_types_by_name['SeekResponse'] = _SEEKRESPONSE +_sym_db.RegisterFileDescriptor(DESCRIPTOR) Topic = _reflection.GeneratedProtocolMessageType('Topic', (_message.Message,), dict( LabelsEntry = _reflection.GeneratedProtocolMessageType('LabelsEntry', (_message.Message,), dict( DESCRIPTOR = _TOPIC_LABELSENTRY, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' # @@protoc_insertion_point(class_scope:google.pubsub.v1.Topic.LabelsEntry) )) , DESCRIPTOR = _TOPIC, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """A topic resource. @@ -1679,12 +1679,12 @@ AttributesEntry = _reflection.GeneratedProtocolMessageType('AttributesEntry', (_message.Message,), dict( DESCRIPTOR = _PUBSUBMESSAGE_ATTRIBUTESENTRY, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' # @@protoc_insertion_point(class_scope:google.pubsub.v1.PubsubMessage.AttributesEntry) )) , DESCRIPTOR = _PUBSUBMESSAGE, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """A message data and its attributes. The message payload must not be empty; it must contain either a non-empty data field, or at least one @@ -1714,7 +1714,7 @@ GetTopicRequest = _reflection.GeneratedProtocolMessageType('GetTopicRequest', (_message.Message,), dict( DESCRIPTOR = _GETTOPICREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the GetTopic method. @@ -1730,7 +1730,7 @@ UpdateTopicRequest = _reflection.GeneratedProtocolMessageType('UpdateTopicRequest', (_message.Message,), dict( DESCRIPTOR = _UPDATETOPICREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the UpdateTopic method. @@ -1748,7 +1748,7 @@ PublishRequest = _reflection.GeneratedProtocolMessageType('PublishRequest', (_message.Message,), dict( DESCRIPTOR = _PUBLISHREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the Publish method. @@ -1766,7 +1766,7 @@ PublishResponse = _reflection.GeneratedProtocolMessageType('PublishResponse', (_message.Message,), dict( DESCRIPTOR = _PUBLISHRESPONSE, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Response for the ``Publish`` method. @@ -1783,7 +1783,7 @@ ListTopicsRequest = _reflection.GeneratedProtocolMessageType('ListTopicsRequest', (_message.Message,), dict( DESCRIPTOR = _LISTTOPICSREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the ``ListTopics`` method. @@ -1806,7 +1806,7 @@ ListTopicsResponse = _reflection.GeneratedProtocolMessageType('ListTopicsResponse', (_message.Message,), dict( DESCRIPTOR = _LISTTOPICSRESPONSE, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Response for the ``ListTopics`` method. @@ -1825,7 +1825,7 @@ ListTopicSubscriptionsRequest = _reflection.GeneratedProtocolMessageType('ListTopicSubscriptionsRequest', (_message.Message,), dict( DESCRIPTOR = _LISTTOPICSUBSCRIPTIONSREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the ``ListTopicSubscriptions`` method. @@ -1848,7 +1848,7 @@ ListTopicSubscriptionsResponse = _reflection.GeneratedProtocolMessageType('ListTopicSubscriptionsResponse', (_message.Message,), dict( DESCRIPTOR = _LISTTOPICSUBSCRIPTIONSRESPONSE, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Response for the ``ListTopicSubscriptions`` method. @@ -1867,7 +1867,7 @@ DeleteTopicRequest = _reflection.GeneratedProtocolMessageType('DeleteTopicRequest', (_message.Message,), dict( DESCRIPTOR = _DELETETOPICREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the ``DeleteTopic`` method. @@ -1885,12 +1885,12 @@ LabelsEntry = _reflection.GeneratedProtocolMessageType('LabelsEntry', (_message.Message,), dict( DESCRIPTOR = _SUBSCRIPTION_LABELSENTRY, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' # @@protoc_insertion_point(class_scope:google.pubsub.v1.Subscription.LabelsEntry) )) , DESCRIPTOR = _SUBSCRIPTION, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """A subscription resource. @@ -1955,12 +1955,12 @@ AttributesEntry = _reflection.GeneratedProtocolMessageType('AttributesEntry', (_message.Message,), dict( DESCRIPTOR = _PUSHCONFIG_ATTRIBUTESENTRY, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' # @@protoc_insertion_point(class_scope:google.pubsub.v1.PushConfig.AttributesEntry) )) , DESCRIPTOR = _PUSHCONFIG, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Configuration for a push delivery endpoint. @@ -1997,7 +1997,7 @@ ReceivedMessage = _reflection.GeneratedProtocolMessageType('ReceivedMessage', (_message.Message,), dict( DESCRIPTOR = _RECEIVEDMESSAGE, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """A message and its corresponding acknowledgment ID. @@ -2014,7 +2014,7 @@ GetSubscriptionRequest = _reflection.GeneratedProtocolMessageType('GetSubscriptionRequest', (_message.Message,), dict( DESCRIPTOR = _GETSUBSCRIPTIONREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the GetSubscription method. @@ -2030,7 +2030,7 @@ UpdateSubscriptionRequest = _reflection.GeneratedProtocolMessageType('UpdateSubscriptionRequest', (_message.Message,), dict( DESCRIPTOR = _UPDATESUBSCRIPTIONREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the UpdateSubscription method. @@ -2048,7 +2048,7 @@ ListSubscriptionsRequest = _reflection.GeneratedProtocolMessageType('ListSubscriptionsRequest', (_message.Message,), dict( DESCRIPTOR = _LISTSUBSCRIPTIONSREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the ``ListSubscriptions`` method. @@ -2071,7 +2071,7 @@ ListSubscriptionsResponse = _reflection.GeneratedProtocolMessageType('ListSubscriptionsResponse', (_message.Message,), dict( DESCRIPTOR = _LISTSUBSCRIPTIONSRESPONSE, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Response for the ``ListSubscriptions`` method. @@ -2090,7 +2090,7 @@ DeleteSubscriptionRequest = _reflection.GeneratedProtocolMessageType('DeleteSubscriptionRequest', (_message.Message,), dict( DESCRIPTOR = _DELETESUBSCRIPTIONREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the DeleteSubscription method. @@ -2106,7 +2106,7 @@ ModifyPushConfigRequest = _reflection.GeneratedProtocolMessageType('ModifyPushConfigRequest', (_message.Message,), dict( DESCRIPTOR = _MODIFYPUSHCONFIGREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the ModifyPushConfig method. @@ -2128,7 +2128,7 @@ PullRequest = _reflection.GeneratedProtocolMessageType('PullRequest', (_message.Message,), dict( DESCRIPTOR = _PULLREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the ``Pull`` method. @@ -2155,7 +2155,7 @@ PullResponse = _reflection.GeneratedProtocolMessageType('PullResponse', (_message.Message,), dict( DESCRIPTOR = _PULLRESPONSE, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Response for the ``Pull`` method. @@ -2174,7 +2174,7 @@ ModifyAckDeadlineRequest = _reflection.GeneratedProtocolMessageType('ModifyAckDeadlineRequest', (_message.Message,), dict( DESCRIPTOR = _MODIFYACKDEADLINEREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the ModifyAckDeadline method. @@ -2201,7 +2201,7 @@ AcknowledgeRequest = _reflection.GeneratedProtocolMessageType('AcknowledgeRequest', (_message.Message,), dict( DESCRIPTOR = _ACKNOWLEDGEREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the Acknowledge method. @@ -2221,7 +2221,7 @@ StreamingPullRequest = _reflection.GeneratedProtocolMessageType('StreamingPullRequest', (_message.Message,), dict( DESCRIPTOR = _STREAMINGPULLREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the ``StreamingPull`` streaming RPC method. This request is used to establish the initial stream as well as to stream @@ -2277,7 +2277,7 @@ StreamingPullResponse = _reflection.GeneratedProtocolMessageType('StreamingPullResponse', (_message.Message,), dict( DESCRIPTOR = _STREAMINGPULLRESPONSE, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Response for the ``StreamingPull`` method. This response is used to stream messages from the server to the client. @@ -2293,7 +2293,7 @@ CreateSnapshotRequest = _reflection.GeneratedProtocolMessageType('CreateSnapshotRequest', (_message.Message,), dict( DESCRIPTOR = _CREATESNAPSHOTREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the ``CreateSnapshot`` method. @@ -2323,7 +2323,7 @@ UpdateSnapshotRequest = _reflection.GeneratedProtocolMessageType('UpdateSnapshotRequest', (_message.Message,), dict( DESCRIPTOR = _UPDATESNAPSHOTREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the UpdateSnapshot method. @@ -2343,12 +2343,12 @@ LabelsEntry = _reflection.GeneratedProtocolMessageType('LabelsEntry', (_message.Message,), dict( DESCRIPTOR = _SNAPSHOT_LABELSENTRY, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' # @@protoc_insertion_point(class_scope:google.pubsub.v1.Snapshot.LabelsEntry) )) , DESCRIPTOR = _SNAPSHOT, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """A snapshot resource. @@ -2380,7 +2380,7 @@ ListSnapshotsRequest = _reflection.GeneratedProtocolMessageType('ListSnapshotsRequest', (_message.Message,), dict( DESCRIPTOR = _LISTSNAPSHOTSREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the ``ListSnapshots`` method. @@ -2403,7 +2403,7 @@ ListSnapshotsResponse = _reflection.GeneratedProtocolMessageType('ListSnapshotsResponse', (_message.Message,), dict( DESCRIPTOR = _LISTSNAPSHOTSRESPONSE, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Response for the ``ListSnapshots`` method. @@ -2422,7 +2422,7 @@ DeleteSnapshotRequest = _reflection.GeneratedProtocolMessageType('DeleteSnapshotRequest', (_message.Message,), dict( DESCRIPTOR = _DELETESNAPSHOTREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the ``DeleteSnapshot`` method. @@ -2438,7 +2438,7 @@ SeekRequest = _reflection.GeneratedProtocolMessageType('SeekRequest', (_message.Message,), dict( DESCRIPTOR = _SEEKREQUEST, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' , __doc__ = """Request for the ``Seek`` method. @@ -2470,7 +2470,7 @@ SeekResponse = _reflection.GeneratedProtocolMessageType('SeekResponse', (_message.Message,), dict( DESCRIPTOR = _SEEKRESPONSE, - __module__ = 'google.cloud.proto.pubsub.v1.pubsub_pb2' + __module__ = 'google.cloud.pubsub_v1.proto.pubsub_pb2' # @@protoc_insertion_point(class_scope:google.pubsub.v1.SeekResponse) )) _sym_db.RegisterMessage(SeekResponse) diff --git a/pubsub/google/cloud/proto/pubsub/v1/pubsub_pb2_grpc.py b/pubsub/google/cloud/pubsub_v1/proto/pubsub_pb2_grpc.py similarity index 65% rename from pubsub/google/cloud/proto/pubsub/v1/pubsub_pb2_grpc.py rename to pubsub/google/cloud/pubsub_v1/proto/pubsub_pb2_grpc.py index 06dd470470d8..b0e76ca0fa44 100644 --- a/pubsub/google/cloud/proto/pubsub/v1/pubsub_pb2_grpc.py +++ b/pubsub/google/cloud/pubsub_v1/proto/pubsub_pb2_grpc.py @@ -1,8 +1,8 @@ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc -import google.cloud.proto.pubsub.v1.pubsub_pb2 as google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2 -import google.protobuf.empty_pb2 as google_dot_protobuf_dot_empty__pb2 +from google.cloud.pubsub_v1.proto import pubsub_pb2 as google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2 +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 class SubscriberStub(object): @@ -18,78 +18,78 @@ def __init__(self, channel): """ self.CreateSubscription = channel.unary_unary( '/google.pubsub.v1.Subscriber/CreateSubscription', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Subscription.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Subscription.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Subscription.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Subscription.FromString, ) self.GetSubscription = channel.unary_unary( '/google.pubsub.v1.Subscriber/GetSubscription', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.GetSubscriptionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Subscription.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.GetSubscriptionRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Subscription.FromString, ) self.UpdateSubscription = channel.unary_unary( '/google.pubsub.v1.Subscriber/UpdateSubscription', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.UpdateSubscriptionRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Subscription.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.UpdateSubscriptionRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Subscription.FromString, ) self.ListSubscriptions = channel.unary_unary( '/google.pubsub.v1.Subscriber/ListSubscriptions', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListSubscriptionsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListSubscriptionsResponse.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListSubscriptionsRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListSubscriptionsResponse.FromString, ) self.DeleteSubscription = channel.unary_unary( '/google.pubsub.v1.Subscriber/DeleteSubscription', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.DeleteSubscriptionRequest.SerializeToString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.DeleteSubscriptionRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.ModifyAckDeadline = channel.unary_unary( '/google.pubsub.v1.Subscriber/ModifyAckDeadline', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ModifyAckDeadlineRequest.SerializeToString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ModifyAckDeadlineRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.Acknowledge = channel.unary_unary( '/google.pubsub.v1.Subscriber/Acknowledge', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.AcknowledgeRequest.SerializeToString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.AcknowledgeRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.Pull = channel.unary_unary( '/google.pubsub.v1.Subscriber/Pull', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.PullRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.PullResponse.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.PullRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.PullResponse.FromString, ) self.StreamingPull = channel.stream_stream( '/google.pubsub.v1.Subscriber/StreamingPull', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.StreamingPullRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.StreamingPullResponse.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.StreamingPullRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.StreamingPullResponse.FromString, ) self.ModifyPushConfig = channel.unary_unary( '/google.pubsub.v1.Subscriber/ModifyPushConfig', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ModifyPushConfigRequest.SerializeToString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ModifyPushConfigRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.ListSnapshots = channel.unary_unary( '/google.pubsub.v1.Subscriber/ListSnapshots', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListSnapshotsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListSnapshotsResponse.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListSnapshotsRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListSnapshotsResponse.FromString, ) self.CreateSnapshot = channel.unary_unary( '/google.pubsub.v1.Subscriber/CreateSnapshot', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.CreateSnapshotRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Snapshot.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.CreateSnapshotRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Snapshot.FromString, ) self.UpdateSnapshot = channel.unary_unary( '/google.pubsub.v1.Subscriber/UpdateSnapshot', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.UpdateSnapshotRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Snapshot.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.UpdateSnapshotRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Snapshot.FromString, ) self.DeleteSnapshot = channel.unary_unary( '/google.pubsub.v1.Subscriber/DeleteSnapshot', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.DeleteSnapshotRequest.SerializeToString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.DeleteSnapshotRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.Seek = channel.unary_unary( '/google.pubsub.v1.Subscriber/Seek', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.SeekRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.SeekResponse.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.SeekRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.SeekResponse.FromString, ) @@ -273,78 +273,78 @@ def add_SubscriberServicer_to_server(servicer, server): rpc_method_handlers = { 'CreateSubscription': grpc.unary_unary_rpc_method_handler( servicer.CreateSubscription, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Subscription.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Subscription.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Subscription.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Subscription.SerializeToString, ), 'GetSubscription': grpc.unary_unary_rpc_method_handler( servicer.GetSubscription, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.GetSubscriptionRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Subscription.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.GetSubscriptionRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Subscription.SerializeToString, ), 'UpdateSubscription': grpc.unary_unary_rpc_method_handler( servicer.UpdateSubscription, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.UpdateSubscriptionRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Subscription.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.UpdateSubscriptionRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Subscription.SerializeToString, ), 'ListSubscriptions': grpc.unary_unary_rpc_method_handler( servicer.ListSubscriptions, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListSubscriptionsRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListSubscriptionsResponse.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListSubscriptionsRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListSubscriptionsResponse.SerializeToString, ), 'DeleteSubscription': grpc.unary_unary_rpc_method_handler( servicer.DeleteSubscription, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.DeleteSubscriptionRequest.FromString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.DeleteSubscriptionRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'ModifyAckDeadline': grpc.unary_unary_rpc_method_handler( servicer.ModifyAckDeadline, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ModifyAckDeadlineRequest.FromString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ModifyAckDeadlineRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'Acknowledge': grpc.unary_unary_rpc_method_handler( servicer.Acknowledge, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.AcknowledgeRequest.FromString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.AcknowledgeRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'Pull': grpc.unary_unary_rpc_method_handler( servicer.Pull, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.PullRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.PullResponse.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.PullRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.PullResponse.SerializeToString, ), 'StreamingPull': grpc.stream_stream_rpc_method_handler( servicer.StreamingPull, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.StreamingPullRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.StreamingPullResponse.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.StreamingPullRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.StreamingPullResponse.SerializeToString, ), 'ModifyPushConfig': grpc.unary_unary_rpc_method_handler( servicer.ModifyPushConfig, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ModifyPushConfigRequest.FromString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ModifyPushConfigRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'ListSnapshots': grpc.unary_unary_rpc_method_handler( servicer.ListSnapshots, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListSnapshotsRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListSnapshotsResponse.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListSnapshotsRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListSnapshotsResponse.SerializeToString, ), 'CreateSnapshot': grpc.unary_unary_rpc_method_handler( servicer.CreateSnapshot, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.CreateSnapshotRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Snapshot.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.CreateSnapshotRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Snapshot.SerializeToString, ), 'UpdateSnapshot': grpc.unary_unary_rpc_method_handler( servicer.UpdateSnapshot, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.UpdateSnapshotRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Snapshot.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.UpdateSnapshotRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Snapshot.SerializeToString, ), 'DeleteSnapshot': grpc.unary_unary_rpc_method_handler( servicer.DeleteSnapshot, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.DeleteSnapshotRequest.FromString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.DeleteSnapshotRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'Seek': grpc.unary_unary_rpc_method_handler( servicer.Seek, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.SeekRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.SeekResponse.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.SeekRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.SeekResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( @@ -365,37 +365,37 @@ def __init__(self, channel): """ self.CreateTopic = channel.unary_unary( '/google.pubsub.v1.Publisher/CreateTopic', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Topic.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Topic.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Topic.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Topic.FromString, ) self.UpdateTopic = channel.unary_unary( '/google.pubsub.v1.Publisher/UpdateTopic', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.UpdateTopicRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Topic.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.UpdateTopicRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Topic.FromString, ) self.Publish = channel.unary_unary( '/google.pubsub.v1.Publisher/Publish', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.PublishRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.PublishResponse.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.PublishRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.PublishResponse.FromString, ) self.GetTopic = channel.unary_unary( '/google.pubsub.v1.Publisher/GetTopic', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.GetTopicRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Topic.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.GetTopicRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Topic.FromString, ) self.ListTopics = channel.unary_unary( '/google.pubsub.v1.Publisher/ListTopics', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListTopicsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListTopicsResponse.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicsRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicsResponse.FromString, ) self.ListTopicSubscriptions = channel.unary_unary( '/google.pubsub.v1.Publisher/ListTopicSubscriptions', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListTopicSubscriptionsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListTopicSubscriptionsResponse.FromString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicSubscriptionsRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicSubscriptionsResponse.FromString, ) self.DeleteTopic = channel.unary_unary( '/google.pubsub.v1.Publisher/DeleteTopic', - request_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.DeleteTopicRequest.SerializeToString, + request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.DeleteTopicRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) @@ -470,37 +470,37 @@ def add_PublisherServicer_to_server(servicer, server): rpc_method_handlers = { 'CreateTopic': grpc.unary_unary_rpc_method_handler( servicer.CreateTopic, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Topic.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Topic.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Topic.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Topic.SerializeToString, ), 'UpdateTopic': grpc.unary_unary_rpc_method_handler( servicer.UpdateTopic, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.UpdateTopicRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Topic.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.UpdateTopicRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Topic.SerializeToString, ), 'Publish': grpc.unary_unary_rpc_method_handler( servicer.Publish, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.PublishRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.PublishResponse.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.PublishRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.PublishResponse.SerializeToString, ), 'GetTopic': grpc.unary_unary_rpc_method_handler( servicer.GetTopic, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.GetTopicRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.Topic.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.GetTopicRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Topic.SerializeToString, ), 'ListTopics': grpc.unary_unary_rpc_method_handler( servicer.ListTopics, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListTopicsRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListTopicsResponse.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicsRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicsResponse.SerializeToString, ), 'ListTopicSubscriptions': grpc.unary_unary_rpc_method_handler( servicer.ListTopicSubscriptions, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListTopicSubscriptionsRequest.FromString, - response_serializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.ListTopicSubscriptionsResponse.SerializeToString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicSubscriptionsRequest.FromString, + response_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicSubscriptionsResponse.SerializeToString, ), 'DeleteTopic': grpc.unary_unary_rpc_method_handler( servicer.DeleteTopic, - request_deserializer=google_dot_cloud_dot_proto_dot_pubsub_dot_v1_dot_pubsub__pb2.DeleteTopicRequest.FromString, + request_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.DeleteTopicRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), } diff --git a/pubsub/google/cloud/pubsub_v1/publisher/client.py b/pubsub/google/cloud/pubsub_v1/publisher/client.py index d1375372df28..4d00abe22504 100644 --- a/pubsub/google/cloud/pubsub_v1/publisher/client.py +++ b/pubsub/google/cloud/pubsub_v1/publisher/client.py @@ -23,14 +23,14 @@ import six from google.api_core import grpc_helpers -from google.cloud.gapic.pubsub.v1 import publisher_client from google.cloud.pubsub_v1 import _gapic from google.cloud.pubsub_v1 import types +from google.cloud.pubsub_v1.gapic import publisher_client from google.cloud.pubsub_v1.publisher.batch import thread -__VERSION__ = pkg_resources.get_distribution('google-cloud-pubsub').version +__version__ = pkg_resources.get_distribution('google-cloud-pubsub').version @_gapic.add_methods(publisher_client.PublisherClient, blacklist=('publish',)) @@ -69,9 +69,9 @@ def __init__(self, batch_settings=(), batch_class=thread.Batch, **kwargs): # keepalive options. if 'channel' not in kwargs: kwargs['channel'] = grpc_helpers.create_channel( - credentials=kwargs.get('credentials', None), + credentials=kwargs.pop('credentials', None), target=self.target, - scopes=publisher_client.PublisherClient._ALL_SCOPES, + scopes=publisher_client.PublisherClient._DEFAULT_SCOPES, options={ 'grpc.max_send_message_length': -1, 'grpc.max_receive_message_length': -1, @@ -80,8 +80,6 @@ def __init__(self, batch_settings=(), batch_class=thread.Batch, **kwargs): # Add the metrics headers, and instantiate the underlying GAPIC # client. - kwargs['lib_name'] = 'gccl' - kwargs['lib_version'] = __VERSION__ self.api = publisher_client.PublisherClient(**kwargs) self.batch_settings = types.BatchSettings(*batch_settings) @@ -98,10 +96,7 @@ def target(self): Returns: str: The location of the API. """ - return '{host}:{port}'.format( - host=publisher_client.PublisherClient.SERVICE_ADDRESS, - port=publisher_client.PublisherClient.DEFAULT_SERVICE_PORT, - ) + return publisher_client.PublisherClient.SERVICE_ADDRESS def batch(self, topic, message, create=True, autocommit=True): """Return the current batch for the provided topic. diff --git a/pubsub/google/cloud/pubsub_v1/subscriber/_consumer.py b/pubsub/google/cloud/pubsub_v1/subscriber/_consumer.py index 127675683af1..099f86336b4a 100644 --- a/pubsub/google/cloud/pubsub_v1/subscriber/_consumer.py +++ b/pubsub/google/cloud/pubsub_v1/subscriber/_consumer.py @@ -117,9 +117,10 @@ """ import logging -import queue import threading +from six.moves import queue + from google.cloud.pubsub_v1.subscriber import _helper_threads _LOGGER = logging.getLogger(__name__) diff --git a/pubsub/google/cloud/pubsub_v1/subscriber/client.py b/pubsub/google/cloud/pubsub_v1/subscriber/client.py index 8e5f377834bc..6c9b2fccb10d 100644 --- a/pubsub/google/cloud/pubsub_v1/subscriber/client.py +++ b/pubsub/google/cloud/pubsub_v1/subscriber/client.py @@ -20,14 +20,14 @@ import grpc from google.api_core import grpc_helpers -from google.cloud.gapic.pubsub.v1 import subscriber_client from google.cloud.pubsub_v1 import _gapic from google.cloud.pubsub_v1 import types +from google.cloud.pubsub_v1.gapic import subscriber_client from google.cloud.pubsub_v1.subscriber.policy import thread -__VERSION__ = pkg_resources.get_distribution('google-cloud-pubsub').version +__version__ = pkg_resources.get_distribution('google-cloud-pubsub').version @_gapic.add_methods(subscriber_client.SubscriberClient, @@ -66,9 +66,9 @@ def __init__(self, policy_class=thread.Policy, **kwargs): # keepalive options. if 'channel' not in kwargs: kwargs['channel'] = grpc_helpers.create_channel( - credentials=kwargs.get('credentials', None), + credentials=kwargs.pop('credentials', None), target=self.target, - scopes=subscriber_client.SubscriberClient._ALL_SCOPES, + scopes=subscriber_client.SubscriberClient._DEFAULT_SCOPES, options={ 'grpc.max_send_message_length': -1, 'grpc.max_receive_message_length': -1, @@ -78,8 +78,6 @@ def __init__(self, policy_class=thread.Policy, **kwargs): # Add the metrics headers, and instantiate the underlying GAPIC # client. - kwargs['lib_name'] = 'gccl' - kwargs['lib_version'] = __VERSION__ self.api = subscriber_client.SubscriberClient(**kwargs) # The subcription class is responsible to retrieving and dispatching @@ -93,10 +91,7 @@ def target(self): Returns: str: The location of the API. """ - return '{host}:{port}'.format( - host=subscriber_client.SubscriberClient.SERVICE_ADDRESS, - port=subscriber_client.SubscriberClient.DEFAULT_SERVICE_PORT, - ) + return subscriber_client.SubscriberClient.SERVICE_ADDRESS def subscribe(self, subscription, callback=None, flow_control=()): """Return a representation of an individual subscription. diff --git a/pubsub/google/cloud/pubsub_v1/subscriber/policy/thread.py b/pubsub/google/cloud/pubsub_v1/subscriber/policy/thread.py index 30bb540cea2f..8444132c1bc5 100644 --- a/pubsub/google/cloud/pubsub_v1/subscriber/policy/thread.py +++ b/pubsub/google/cloud/pubsub_v1/subscriber/policy/thread.py @@ -15,11 +15,11 @@ from __future__ import absolute_import from concurrent import futures -from queue import Queue import logging import threading import grpc +from six.moves import queue as queue_mod from google.cloud.pubsub_v1 import types from google.cloud.pubsub_v1.subscriber import _helper_threads @@ -69,7 +69,7 @@ def __init__(self, client, subscription, flow_control=types.FlowControl(), # Create a queue for keeping track of shared state. if queue is None: - queue = Queue() + queue = queue_mod.Queue() self._request_queue = queue # Call the superclass constructor. diff --git a/pubsub/google/cloud/pubsub_v1/types.py b/pubsub/google/cloud/pubsub_v1/types.py index 23a055a31954..f601915d0a60 100644 --- a/pubsub/google/cloud/pubsub_v1/types.py +++ b/pubsub/google/cloud/pubsub_v1/types.py @@ -13,14 +13,21 @@ # limitations under the License. from __future__ import absolute_import - import collections +import psutil import sys -import psutil +from google.api_core.protobuf_helpers import get_messages -from google.cloud.proto.pubsub.v1 import pubsub_pb2 -from google.gax.utils.messages import get_messages +from google.api import http_pb2 +from google.cloud.pubsub_v1.proto import pubsub_pb2 +from google.iam.v1 import iam_policy_pb2 +from google.iam.v1 import policy_pb2 +from google.iam.v1.logging import audit_data_pb2 +from google.protobuf import descriptor_pb2 +from google.protobuf import duration_pb2 +from google.protobuf import empty_pb2 +from google.protobuf import field_mask_pb2 from google.protobuf import timestamp_pb2 @@ -55,16 +62,28 @@ ) -# Pub/Sub uses timestamps from the common protobuf package. -# Do not make users import from there. -Timestamp = timestamp_pb2.Timestamp - - -_names = ['BatchSettings', 'FlowControl', 'Timestamp'] +names = ['BatchSettings', 'FlowControl'] for name, message in get_messages(pubsub_pb2).items(): message.__module__ = 'google.cloud.pubsub_v1.types' setattr(sys.modules[__name__], name, message) - _names.append(name) + names.append(name) + + +for module in ( + http_pb2, + pubsub_pb2, + iam_policy_pb2, + policy_pb2, + audit_data_pb2, + descriptor_pb2, + duration_pb2, + empty_pb2, + field_mask_pb2, + timestamp_pb2, ): + for name, message in get_messages(module).items(): + message.__module__ = 'google.cloud.pubsub_v1.types' + setattr(sys.modules[__name__], name, message) + names.append(name) -__all__ = tuple(sorted(_names)) +__all__ = tuple(sorted(names)) diff --git a/pubsub/setup.py b/pubsub/setup.py index c347de589917..b7f45a7c38db 100644 --- a/pubsub/setup.py +++ b/pubsub/setup.py @@ -51,9 +51,8 @@ REQUIREMENTS = [ - 'google-cloud-core[grpc] >= 0.28.0, < 0.29dev', - 'google-api-core >= 0.1.1, < 0.2.0dev', - 'google-gax >= 0.15.13, < 0.16dev', + 'google-api-core[grpc] >= 0.1.1, < 0.2.0dev', + 'google-auth >= 1.0.2, < 2.0dev', 'grpc-google-iam-v1 >= 0.11.1, < 0.12dev', 'psutil >= 5.2.2, < 6.0dev', ] @@ -66,10 +65,6 @@ namespace_packages=[ 'google', 'google.cloud', - 'google.cloud.gapic', - 'google.cloud.gapic.pubsub', - 'google.cloud.proto', - 'google.cloud.proto.pubsub', ], packages=find_packages(exclude=('tests*',)), install_requires=REQUIREMENTS, diff --git a/pubsub/tests/unit/gapic/v1/test_publisher_client_v1.py b/pubsub/tests/unit/gapic/v1/test_publisher_client_v1.py new file mode 100644 index 000000000000..13b3bc6fbc1c --- /dev/null +++ b/pubsub/tests/unit/gapic/v1/test_publisher_client_v1.py @@ -0,0 +1,415 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.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. +"""Unit tests.""" + +import pytest + +from google.cloud.pubsub_v1.gapic import publisher_client +from google.cloud.pubsub_v1.proto import pubsub_pb2 +from google.iam.v1 import iam_policy_pb2 +from google.iam.v1 import policy_pb2 +from google.protobuf import empty_pb2 +from google.protobuf import field_mask_pb2 + + +class MultiCallableStub(object): + """Stub for the grpc.UnaryUnaryMultiCallable interface.""" + + def __init__(self, method, channel_stub): + self.method = method + self.channel_stub = channel_stub + + def __call__(self, request, timeout=None, metadata=None, credentials=None): + self.channel_stub.requests.append((self.method, request)) + + response = None + if self.channel_stub.responses: + response = self.channel_stub.responses.pop() + + if isinstance(response, Exception): + raise response + + if response: + return response + + +class ChannelStub(object): + """Stub for the grpc.Channel interface.""" + + def __init__(self, responses=[]): + self.responses = responses + self.requests = [] + + def unary_unary(self, + method, + request_serializer=None, + response_deserializer=None): + return MultiCallableStub(method, self) + + +class CustomException(Exception): + pass + + +class TestPublisherClient(object): + def test_create_topic(self): + # Setup Expected Response + name_2 = 'name2-1052831874' + expected_response = {'name': name_2} + expected_response = pubsub_pb2.Topic(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup Request + name = client.topic_path('[PROJECT]', '[TOPIC]') + + response = client.create_topic(name) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.Topic(name=name) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_create_topic_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup request + name = client.topic_path('[PROJECT]', '[TOPIC]') + + with pytest.raises(CustomException): + client.create_topic(name) + + def test_update_topic(self): + # Setup Expected Response + name = 'name3373707' + expected_response = {'name': name} + expected_response = pubsub_pb2.Topic(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup Request + topic = {} + update_mask = {} + + response = client.update_topic(topic, update_mask) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.UpdateTopicRequest( + topic=topic, update_mask=update_mask) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_update_topic_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup request + topic = {} + update_mask = {} + + with pytest.raises(CustomException): + client.update_topic(topic, update_mask) + + def test_publish(self): + # Setup Expected Response + message_ids_element = 'messageIdsElement-744837059' + message_ids = [message_ids_element] + expected_response = {'message_ids': message_ids} + expected_response = pubsub_pb2.PublishResponse(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup Request + topic = client.topic_path('[PROJECT]', '[TOPIC]') + data = b'-86' + messages_element = {'data': data} + messages = [messages_element] + + response = client.publish(topic, messages) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.PublishRequest( + topic=topic, messages=messages) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_publish_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup request + topic = client.topic_path('[PROJECT]', '[TOPIC]') + data = b'-86' + messages_element = {'data': data} + messages = [messages_element] + + with pytest.raises(CustomException): + client.publish(topic, messages) + + def test_get_topic(self): + # Setup Expected Response + name = 'name3373707' + expected_response = {'name': name} + expected_response = pubsub_pb2.Topic(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup Request + topic = client.topic_path('[PROJECT]', '[TOPIC]') + + response = client.get_topic(topic) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.GetTopicRequest(topic=topic) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_get_topic_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup request + topic = client.topic_path('[PROJECT]', '[TOPIC]') + + with pytest.raises(CustomException): + client.get_topic(topic) + + def test_list_topics(self): + # Setup Expected Response + next_page_token = '' + topics_element = {} + topics = [topics_element] + expected_response = { + 'next_page_token': next_page_token, + 'topics': topics + } + expected_response = pubsub_pb2.ListTopicsResponse(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup Request + project = client.project_path('[PROJECT]') + + paged_list_response = client.list_topics(project) + resources = list(paged_list_response) + assert len(resources) == 1 + + assert expected_response.topics[0] == resources[0] + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.ListTopicsRequest(project=project) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_list_topics_exception(self): + channel = ChannelStub(responses=[CustomException()]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup request + project = client.project_path('[PROJECT]') + + paged_list_response = client.list_topics(project) + with pytest.raises(CustomException): + list(paged_list_response) + + def test_list_topic_subscriptions(self): + # Setup Expected Response + next_page_token = '' + subscriptions_element = 'subscriptionsElement1698708147' + subscriptions = [subscriptions_element] + expected_response = { + 'next_page_token': next_page_token, + 'subscriptions': subscriptions + } + expected_response = pubsub_pb2.ListTopicSubscriptionsResponse( + **expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup Request + topic = client.topic_path('[PROJECT]', '[TOPIC]') + + paged_list_response = client.list_topic_subscriptions(topic) + resources = list(paged_list_response) + assert len(resources) == 1 + + assert expected_response.subscriptions[0] == resources[0] + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.ListTopicSubscriptionsRequest( + topic=topic) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_list_topic_subscriptions_exception(self): + channel = ChannelStub(responses=[CustomException()]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup request + topic = client.topic_path('[PROJECT]', '[TOPIC]') + + paged_list_response = client.list_topic_subscriptions(topic) + with pytest.raises(CustomException): + list(paged_list_response) + + def test_delete_topic(self): + channel = ChannelStub() + client = publisher_client.PublisherClient(channel=channel) + + # Setup Request + topic = client.topic_path('[PROJECT]', '[TOPIC]') + + client.delete_topic(topic) + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.DeleteTopicRequest(topic=topic) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_delete_topic_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup request + topic = client.topic_path('[PROJECT]', '[TOPIC]') + + with pytest.raises(CustomException): + client.delete_topic(topic) + + def test_set_iam_policy(self): + # Setup Expected Response + version = 351608024 + etag = b'21' + expected_response = {'version': version, 'etag': etag} + expected_response = policy_pb2.Policy(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup Request + resource = client.topic_path('[PROJECT]', '[TOPIC]') + policy = {} + + response = client.set_iam_policy(resource, policy) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = iam_policy_pb2.SetIamPolicyRequest( + resource=resource, policy=policy) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_set_iam_policy_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup request + resource = client.topic_path('[PROJECT]', '[TOPIC]') + policy = {} + + with pytest.raises(CustomException): + client.set_iam_policy(resource, policy) + + def test_get_iam_policy(self): + # Setup Expected Response + version = 351608024 + etag = b'21' + expected_response = {'version': version, 'etag': etag} + expected_response = policy_pb2.Policy(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup Request + resource = client.topic_path('[PROJECT]', '[TOPIC]') + + response = client.get_iam_policy(resource) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = iam_policy_pb2.GetIamPolicyRequest( + resource=resource) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_get_iam_policy_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup request + resource = client.topic_path('[PROJECT]', '[TOPIC]') + + with pytest.raises(CustomException): + client.get_iam_policy(resource) + + def test_test_iam_permissions(self): + # Setup Expected Response + expected_response = {} + expected_response = iam_policy_pb2.TestIamPermissionsResponse( + **expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup Request + resource = client.topic_path('[PROJECT]', '[TOPIC]') + permissions = [] + + response = client.test_iam_permissions(resource, permissions) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_test_iam_permissions_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = publisher_client.PublisherClient(channel=channel) + + # Setup request + resource = client.topic_path('[PROJECT]', '[TOPIC]') + permissions = [] + + with pytest.raises(CustomException): + client.test_iam_permissions(resource, permissions) diff --git a/pubsub/tests/unit/gapic/v1/test_subscriber_client_v1.py b/pubsub/tests/unit/gapic/v1/test_subscriber_client_v1.py new file mode 100644 index 000000000000..fd3e04c044fd --- /dev/null +++ b/pubsub/tests/unit/gapic/v1/test_subscriber_client_v1.py @@ -0,0 +1,712 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.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. +"""Unit tests.""" + +import pytest + +from google.cloud.pubsub_v1.gapic import subscriber_client +from google.cloud.pubsub_v1.proto import pubsub_pb2 +from google.iam.v1 import iam_policy_pb2 +from google.iam.v1 import policy_pb2 +from google.protobuf import empty_pb2 +from google.protobuf import field_mask_pb2 + + +class MultiCallableStub(object): + """Stub for the grpc.UnaryUnaryMultiCallable interface.""" + + def __init__(self, method, channel_stub): + self.method = method + self.channel_stub = channel_stub + + def __call__(self, request, timeout=None, metadata=None, credentials=None): + self.channel_stub.requests.append((self.method, request)) + + response = None + if self.channel_stub.responses: + response = self.channel_stub.responses.pop() + + if isinstance(response, Exception): + raise response + + if response: + return response + + +class ChannelStub(object): + """Stub for the grpc.Channel interface.""" + + def __init__(self, responses=[]): + self.responses = responses + self.requests = [] + + def unary_unary(self, + method, + request_serializer=None, + response_deserializer=None): + return MultiCallableStub(method, self) + + def stream_stream(self, + method, + request_serializer=None, + response_deserializer=None): + return MultiCallableStub(method, self) + + +class CustomException(Exception): + pass + + +class TestSubscriberClient(object): + def test_create_subscription(self): + # Setup Expected Response + name_2 = 'name2-1052831874' + topic_2 = 'topic2-1139259102' + ack_deadline_seconds = 2135351438 + retain_acked_messages = False + expected_response = { + 'name': name_2, + 'topic': topic_2, + 'ack_deadline_seconds': ack_deadline_seconds, + 'retain_acked_messages': retain_acked_messages + } + expected_response = pubsub_pb2.Subscription(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + name = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + topic = client.topic_path('[PROJECT]', '[TOPIC]') + + response = client.create_subscription(name, topic) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.Subscription(name=name, topic=topic) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_create_subscription_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + name = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + topic = client.topic_path('[PROJECT]', '[TOPIC]') + + with pytest.raises(CustomException): + client.create_subscription(name, topic) + + def test_get_subscription(self): + # Setup Expected Response + name = 'name3373707' + topic = 'topic110546223' + ack_deadline_seconds = 2135351438 + retain_acked_messages = False + expected_response = { + 'name': name, + 'topic': topic, + 'ack_deadline_seconds': ack_deadline_seconds, + 'retain_acked_messages': retain_acked_messages + } + expected_response = pubsub_pb2.Subscription(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + + response = client.get_subscription(subscription) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.GetSubscriptionRequest( + subscription=subscription) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_get_subscription_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + + with pytest.raises(CustomException): + client.get_subscription(subscription) + + def test_update_subscription(self): + # Setup Expected Response + name = 'name3373707' + topic = 'topic110546223' + ack_deadline_seconds = 2135351438 + retain_acked_messages = False + expected_response = { + 'name': name, + 'topic': topic, + 'ack_deadline_seconds': ack_deadline_seconds, + 'retain_acked_messages': retain_acked_messages + } + expected_response = pubsub_pb2.Subscription(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + subscription = {} + update_mask = {} + + response = client.update_subscription(subscription, update_mask) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.UpdateSubscriptionRequest( + subscription=subscription, update_mask=update_mask) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_update_subscription_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + subscription = {} + update_mask = {} + + with pytest.raises(CustomException): + client.update_subscription(subscription, update_mask) + + def test_list_subscriptions(self): + # Setup Expected Response + next_page_token = '' + subscriptions_element = {} + subscriptions = [subscriptions_element] + expected_response = { + 'next_page_token': next_page_token, + 'subscriptions': subscriptions + } + expected_response = pubsub_pb2.ListSubscriptionsResponse( + **expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + project = client.project_path('[PROJECT]') + + paged_list_response = client.list_subscriptions(project) + resources = list(paged_list_response) + assert len(resources) == 1 + + assert expected_response.subscriptions[0] == resources[0] + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.ListSubscriptionsRequest(project=project) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_list_subscriptions_exception(self): + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + project = client.project_path('[PROJECT]') + + paged_list_response = client.list_subscriptions(project) + with pytest.raises(CustomException): + list(paged_list_response) + + def test_delete_subscription(self): + channel = ChannelStub() + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + + client.delete_subscription(subscription) + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.DeleteSubscriptionRequest( + subscription=subscription) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_delete_subscription_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + + with pytest.raises(CustomException): + client.delete_subscription(subscription) + + def test_modify_ack_deadline(self): + channel = ChannelStub() + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + ack_ids = [] + ack_deadline_seconds = 2135351438 + + client.modify_ack_deadline(subscription, ack_ids, ack_deadline_seconds) + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.ModifyAckDeadlineRequest( + subscription=subscription, + ack_ids=ack_ids, + ack_deadline_seconds=ack_deadline_seconds) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_modify_ack_deadline_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + ack_ids = [] + ack_deadline_seconds = 2135351438 + + with pytest.raises(CustomException): + client.modify_ack_deadline(subscription, ack_ids, + ack_deadline_seconds) + + def test_acknowledge(self): + channel = ChannelStub() + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + ack_ids = [] + + client.acknowledge(subscription, ack_ids) + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.AcknowledgeRequest( + subscription=subscription, ack_ids=ack_ids) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_acknowledge_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + ack_ids = [] + + with pytest.raises(CustomException): + client.acknowledge(subscription, ack_ids) + + def test_pull(self): + # Setup Expected Response + expected_response = {} + expected_response = pubsub_pb2.PullResponse(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + max_messages = 496131527 + + response = client.pull(subscription, max_messages) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.PullRequest( + subscription=subscription, max_messages=max_messages) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_pull_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + max_messages = 496131527 + + with pytest.raises(CustomException): + client.pull(subscription, max_messages) + + def test_streaming_pull(self): + # Setup Expected Response + received_messages_element = {} + received_messages = [received_messages_element] + expected_response = {'received_messages': received_messages} + expected_response = pubsub_pb2.StreamingPullResponse( + **expected_response) + + # Mock the API response + channel = ChannelStub(responses=[iter([expected_response])]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + stream_ack_deadline_seconds = 1875467245 + request = { + 'subscription': subscription, + 'stream_ack_deadline_seconds': stream_ack_deadline_seconds + } + request = pubsub_pb2.StreamingPullRequest(**request) + requests = [request] + + response = client.streaming_pull(requests) + resources = list(response) + assert len(resources) == 1 + assert expected_response == resources[0] + + assert len(channel.requests) == 1 + actual_requests = channel.requests[0][1] + assert len(actual_requests) == 1 + actual_request = list(actual_requests)[0] + assert request == actual_request + + def test_streaming_pull_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + stream_ack_deadline_seconds = 1875467245 + request = { + 'subscription': subscription, + 'stream_ack_deadline_seconds': stream_ack_deadline_seconds + } + + request = pubsub_pb2.StreamingPullRequest(**request) + requests = [request] + + with pytest.raises(CustomException): + client.streaming_pull(requests) + + def test_modify_push_config(self): + channel = ChannelStub() + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + push_config = {} + + client.modify_push_config(subscription, push_config) + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.ModifyPushConfigRequest( + subscription=subscription, push_config=push_config) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_modify_push_config_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + push_config = {} + + with pytest.raises(CustomException): + client.modify_push_config(subscription, push_config) + + def test_list_snapshots(self): + # Setup Expected Response + next_page_token = '' + snapshots_element = {} + snapshots = [snapshots_element] + expected_response = { + 'next_page_token': next_page_token, + 'snapshots': snapshots + } + expected_response = pubsub_pb2.ListSnapshotsResponse( + **expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + project = client.project_path('[PROJECT]') + + paged_list_response = client.list_snapshots(project) + resources = list(paged_list_response) + assert len(resources) == 1 + + assert expected_response.snapshots[0] == resources[0] + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.ListSnapshotsRequest(project=project) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_list_snapshots_exception(self): + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + project = client.project_path('[PROJECT]') + + paged_list_response = client.list_snapshots(project) + with pytest.raises(CustomException): + list(paged_list_response) + + def test_create_snapshot(self): + # Setup Expected Response + name_2 = 'name2-1052831874' + topic = 'topic110546223' + expected_response = {'name': name_2, 'topic': topic} + expected_response = pubsub_pb2.Snapshot(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + name = client.snapshot_path('[PROJECT]', '[SNAPSHOT]') + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + + response = client.create_snapshot(name, subscription) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.CreateSnapshotRequest( + name=name, subscription=subscription) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_create_snapshot_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + name = client.snapshot_path('[PROJECT]', '[SNAPSHOT]') + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + + with pytest.raises(CustomException): + client.create_snapshot(name, subscription) + + def test_update_snapshot(self): + # Setup Expected Response + name = 'name3373707' + topic = 'topic110546223' + expected_response = {'name': name, 'topic': topic} + expected_response = pubsub_pb2.Snapshot(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + snapshot = {} + update_mask = {} + + response = client.update_snapshot(snapshot, update_mask) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.UpdateSnapshotRequest( + snapshot=snapshot, update_mask=update_mask) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_update_snapshot_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + snapshot = {} + update_mask = {} + + with pytest.raises(CustomException): + client.update_snapshot(snapshot, update_mask) + + def test_delete_snapshot(self): + channel = ChannelStub() + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + snapshot = client.snapshot_path('[PROJECT]', '[SNAPSHOT]') + + client.delete_snapshot(snapshot) + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.DeleteSnapshotRequest(snapshot=snapshot) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_delete_snapshot_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + snapshot = client.snapshot_path('[PROJECT]', '[SNAPSHOT]') + + with pytest.raises(CustomException): + client.delete_snapshot(snapshot) + + def test_seek(self): + # Setup Expected Response + expected_response = {} + expected_response = pubsub_pb2.SeekResponse(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + + response = client.seek(subscription) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = pubsub_pb2.SeekRequest(subscription=subscription) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_seek_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + + with pytest.raises(CustomException): + client.seek(subscription) + + def test_set_iam_policy(self): + # Setup Expected Response + version = 351608024 + etag = b'21' + expected_response = {'version': version, 'etag': etag} + expected_response = policy_pb2.Policy(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + policy = {} + + response = client.set_iam_policy(resource, policy) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = iam_policy_pb2.SetIamPolicyRequest( + resource=resource, policy=policy) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_set_iam_policy_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + policy = {} + + with pytest.raises(CustomException): + client.set_iam_policy(resource, policy) + + def test_get_iam_policy(self): + # Setup Expected Response + version = 351608024 + etag = b'21' + expected_response = {'version': version, 'etag': etag} + expected_response = policy_pb2.Policy(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + + response = client.get_iam_policy(resource) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = iam_policy_pb2.GetIamPolicyRequest( + resource=resource) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_get_iam_policy_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + + with pytest.raises(CustomException): + client.get_iam_policy(resource) + + def test_test_iam_permissions(self): + # Setup Expected Response + expected_response = {} + expected_response = iam_policy_pb2.TestIamPermissionsResponse( + **expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup Request + resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + permissions = [] + + response = client.test_iam_permissions(resource, permissions) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_test_iam_permissions_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + client = subscriber_client.SubscriberClient(channel=channel) + + # Setup request + resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') + permissions = [] + + with pytest.raises(CustomException): + client.test_iam_permissions(resource, permissions) diff --git a/pubsub/tests/unit/pubsub_v1/publisher/test_publisher_client.py b/pubsub/tests/unit/pubsub_v1/publisher/test_publisher_client.py index ce010e69a8cd..c817fb45887f 100644 --- a/pubsub/tests/unit/pubsub_v1/publisher/test_publisher_client.py +++ b/pubsub/tests/unit/pubsub_v1/publisher/test_publisher_client.py @@ -20,18 +20,13 @@ import pytest from google.auth import credentials -from google.cloud.gapic.pubsub.v1 import publisher_client +from google.cloud.pubsub_v1.gapic import publisher_client from google.cloud.pubsub_v1 import publisher from google.cloud.pubsub_v1 import types -def create_client(): - creds = mock.Mock(spec=credentials.Credentials) - return publisher.Client(credentials=creds) - - def test_init(): - client = create_client() + client = publisher.Client() # A plain client should have an `api` (the underlying GAPIC) and a # batch settings object, which should have the defaults. @@ -43,7 +38,7 @@ def test_init(): def test_init_emulator(monkeypatch): monkeypatch.setenv('PUBSUB_EMULATOR_HOST', '/foo/bar/') - client = create_client() + client = publisher.Client() # Establish that a gRPC request would attempt to hit the emulator host. # @@ -55,7 +50,7 @@ def test_init_emulator(monkeypatch): def test_batch_accepting(): """Establish that an existing batch is returned if it accepts messages.""" - client = create_client() + client = publisher.Client() message = types.PubsubMessage(data=b'foo') # At first, there are no batches, so this should return a new batch @@ -72,7 +67,7 @@ def test_batch_accepting(): def test_batch_without_autocreate(): - client = create_client() + client = publisher.Client() message = types.PubsubMessage(data=b'foo') # If `create=False` is sent, then when the batch is not found, None @@ -84,7 +79,7 @@ def test_batch_without_autocreate(): def test_publish(): - client = create_client() + client = publisher.Client() # Use a mock in lieu of the actual batch class; set the mock up to claim # indiscriminately that it accepts all messages. @@ -112,7 +107,7 @@ def test_publish(): def test_publish_data_not_bytestring_error(): - client = create_client() + client = publisher.Client() with pytest.raises(TypeError): client.publish('topic_name', u'This is a text string.') with pytest.raises(TypeError): @@ -120,7 +115,7 @@ def test_publish_data_not_bytestring_error(): def test_publish_attrs_bytestring(): - client = create_client() + client = publisher.Client() # Use a mock in lieu of the actual batch class; set the mock up to claim # indiscriminately that it accepts all messages. @@ -138,13 +133,13 @@ def test_publish_attrs_bytestring(): def test_publish_attrs_type_error(): - client = create_client() + client = publisher.Client() with pytest.raises(TypeError): client.publish('topic_name', b'foo', answer=42) def test_gapic_instance_method(): - client = create_client() + client = publisher.Client() with mock.patch.object(client.api, '_create_topic', autospec=True) as ct: client.create_topic('projects/foo/topics/bar') assert ct.call_count == 1 @@ -153,6 +148,6 @@ def test_gapic_instance_method(): def test_gapic_class_method(): - client = create_client() + client = publisher.Client() answer = client.topic_path('foo', 'bar') assert answer == 'projects/foo/topics/bar' diff --git a/pubsub/tests/unit/pubsub_v1/subscriber/test_consumer.py b/pubsub/tests/unit/pubsub_v1/subscriber/test_consumer.py index 53f81296fe92..c0a0828c8a1e 100644 --- a/pubsub/tests/unit/pubsub_v1/subscriber/test_consumer.py +++ b/pubsub/tests/unit/pubsub_v1/subscriber/test_consumer.py @@ -12,13 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -import queue - +from google.auth import credentials import mock - import pytest +from six.moves import queue -from google.auth import credentials from google.cloud.pubsub_v1 import subscriber from google.cloud.pubsub_v1 import types from google.cloud.pubsub_v1.subscriber import _consumer diff --git a/pubsub/tests/unit/pubsub_v1/subscriber/test_helper_threads.py b/pubsub/tests/unit/pubsub_v1/subscriber/test_helper_threads.py index 6b104c874617..6a8bff2a7f66 100644 --- a/pubsub/tests/unit/pubsub_v1/subscriber/test_helper_threads.py +++ b/pubsub/tests/unit/pubsub_v1/subscriber/test_helper_threads.py @@ -12,10 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -import queue import threading import mock +from six.moves import queue from google.cloud.pubsub_v1.subscriber import _helper_threads diff --git a/pubsub/tests/unit/pubsub_v1/subscriber/test_message.py b/pubsub/tests/unit/pubsub_v1/subscriber/test_message.py index 0cde86169417..5a564a52eee3 100644 --- a/pubsub/tests/unit/pubsub_v1/subscriber/test_message.py +++ b/pubsub/tests/unit/pubsub_v1/subscriber/test_message.py @@ -12,10 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -import queue import time import mock +from six.moves import queue from google.cloud.pubsub_v1 import types from google.cloud.pubsub_v1.subscriber import message diff --git a/pubsub/tests/unit/pubsub_v1/subscriber/test_policy_thread.py b/pubsub/tests/unit/pubsub_v1/subscriber/test_policy_thread.py index 5adfb7817086..106e735a7110 100644 --- a/pubsub/tests/unit/pubsub_v1/subscriber/test_policy_thread.py +++ b/pubsub/tests/unit/pubsub_v1/subscriber/test_policy_thread.py @@ -15,16 +15,14 @@ from __future__ import absolute_import from concurrent import futures -import queue import threading +from google.auth import credentials import grpc - import mock - import pytest +from six.moves import queue -from google.auth import credentials from google.cloud.pubsub_v1 import subscriber from google.cloud.pubsub_v1 import types from google.cloud.pubsub_v1.subscriber import _helper_threads diff --git a/pubsub/tests/unit/pubsub_v1/subscriber/test_subscriber_client.py b/pubsub/tests/unit/pubsub_v1/subscriber/test_subscriber_client.py index fb5faaf6b10c..8620081a8b44 100644 --- a/pubsub/tests/unit/pubsub_v1/subscriber/test_subscriber_client.py +++ b/pubsub/tests/unit/pubsub_v1/subscriber/test_subscriber_client.py @@ -19,19 +19,14 @@ from google.cloud.pubsub_v1.subscriber.policy import thread -def create_client(): - creds = mock.Mock(spec=credentials.Credentials) - return subscriber.Client(credentials=creds) - - def test_init(): - client = create_client() + client = subscriber.Client() assert client._policy_class is thread.Policy def test_init_emulator(monkeypatch): monkeypatch.setenv('PUBSUB_EMULATOR_HOST', '/baz/bacon/') - client = create_client() + client = subscriber.Client() # Establish that a gRPC request would attempt to hit the emulator host. # @@ -42,13 +37,13 @@ def test_init_emulator(monkeypatch): def test_subscribe(): - client = create_client() + client = subscriber.Client() subscription = client.subscribe('sub_name_a') assert isinstance(subscription, thread.Policy) def test_subscribe_with_callback(): - client = create_client() + client = subscriber.Client() callback = mock.Mock() with mock.patch.object(thread.Policy, 'open') as open_: subscription = client.subscribe('sub_name_b', callback)