Skip to main content

This is a shared codebase for gcloud-rest-pubsub and gcloud-rest-pubsub

Latest PyPI Version Python Version Support (gcloud-rest-pubsub) Python Version Support (gcloud-rest-pubsub)

Installation

$ pip install --upgrade gcloud-{aio,rest}-pubsub

Usage

Subscriber

gcloud-{aio,rest}-pubsub provides SubscriberClient as an interface to call pubsub’s HTTP API:

from gcloud.rest.pubsub import SubscriberClient
from gcloud.rest.pubsub import SubscriberMessage

client = SubscriberClient()
# create subscription
await client.create_subscription(
    'projects/<project_name>/subscriptions/<subscription_name>',
    'projects/<project_name>/topics/<topic_name>')

# pull messages
messages: List[SubscriberMessage] = await client.pull(
    'projects/<project_name>/subscriptions/<subscription_name>',
    max_messages=10)

There’s also gcloud.rest.pubsub.subscribe helper function you can use to setup a pubsub processing pipeline. It is built with asyncio and thus only available in gcloud-rest-pubsub package. The usage is fairly simple:

from gcloud.rest.pubsub import SubscriberClient
from gcloud.rest.pubsub import subscribe
from gcloud.rest.pubsub.metrics_agent import MetricsAgent

subscriber_client = SubscriberClient()

async def handler(message):
    return

await subscribe(
    'projects/<my_project>/subscriptions/<my_subscription>',
    handler,
    subscriber_client,
    num_producers=1,
    max_messages_per_producer=100,
    ack_window=0.3,
    num_tasks_per_consumer=1,
    enable_nack=True,
    nack_window=0.3,
    metrics_client=MetricsAgent()
)

While defaults are somewhat sensible, it is highly recommended to performance test your application and tweak function parameter to your specific needs. Here’s a few hints:

handler:

an async function that will be called for each message. It should accept an instance of SubscriberMessage as its only argument and return None if the message should be acked. An exception raised within the handler will result in the message being left to expire, and thus it will be redelivered according to your subscription’s ack deadline.

num_producers:

number of workers that will be making pull requests to pubsub. Please note that a worker will only fetch new batch once the handler was called for each message from the previous batch. This means that running only a single worker will most likely make your application IO bound. If you notice this being an issue don’t hesitate to bump this parameter.

max_messages_per_producer:

number of pubsub messages a worker will try to fetch in a single batch. This value is passed to pull endpoint as maxMessages parameter. A rule of thumb here is the faster your handler is the bigger this value should be.

ack_window:

ack requests are handled separately and are done in batches. This parameters specifies how often ack requests will be made. Setting it to 0.0 will effectively disable batching.

num_tasks_per_consumer:

how many handle calls a worker can make until it blocks to wait for them to return. If you process messages independently from each other you should be good with the default value of 1. If you do something fancy (e.g. aggregate messages before processing them), you’ll want a higher pool here. You can think of num_producers * num_tasks_per_consumer as an upper limit of how many messages can possibly be within your application state at any given moment.

enable_nack:

if enabled messages for which callback raised an exception will be explicitly nacked using modifyAckDeadline endpoint so they can be retried immediately.

nack_window:

same as ack_window but for nack requests

subscribe has also an optional metrics_client argument. You can provide any metrics agent that implements the same interface as MetricsAgent (Datadog client will do ;) ) and get the following metrics:

  • pubsub.producer.batch - [histogram] actual size of a batch retrieved from pubsub.

  • pubsub.consumer.failfast - [increment] a message was dropped due to its lease being expired.

  • pubsub.consumer.latency.receive - [histogram] how many seconds it took for a message to reach handler after it was published.

  • pubsub.consumer.succeeded - [increment] handler call was successfull.

  • pubsub.consumer.failed - [increment] handler call raised an exception.

  • pubsub.consumer.latency.runtime - [histogram] handler execution time in seconds.

  • pubsub.acker.batch.failed - [increment] ack request failed.

  • pubsub.acker.batch - [histogram] actual number of messages that was acked in a single request.

Publisher

The PublisherClient is a dead-simple alternative to the official Google Cloud Pub/Sub publisher client. The main design goal was to eliminate all the additional gRPC overhead implemented by the upstream client.

If migrating between this library and the official one, the main difference is this: the gcloud-{aio,rest}-pubsub publisher’s .publish() method immediately publishes the messages you’ve provided, rather than maintaining our own publishing queue, implementing batching and flow control, etc. If you’re looking for a full-featured publishing library with all the bells and whistles built in, you may be interested in the upstream provider. If you’re looking to manage your own batching / timeouts / retry / threads / etc, this library should be a bit easier to work with.

Sample usage:

from gcloud.rest.pubsub import PubsubMessage
from gcloud.rest.pubsub import PublisherClient

async with aiohttp.ClientSession() as session:
    client = PublisherClient(session=session)

    topic = client.topic_path('my-gcp-project', 'my-topic-name')

    messages = [
        PubsubMessage(b'payload', attribute='value'),
        PubsubMessage(b'other payload', other_attribute='whatever',
                      more_attributes='something else'),
    ]
    response = await client.publish(topic, messages)
    # response == {'messageIds': ['1', '2']}

Emulators

For testing purposes, you may want to use gcloud-rest-pubsub along with a local GCS emulator. Setting the $PUBSUB_EMULATOR_HOST environment variable to the local address of your emulator should be enough to do the trick.

For example, using the official Google Pubsub emulator:

gcloud beta emulators pubsub start --host-port=0.0.0.0:8681
export PUBSUB_EMULATOR_HOST='0.0.0.0:8681'

Any gcloud-rest-pubsub Publisher requests made with that environment variable set will query the emulator instead of the official GCS APIs.

For easier ergonomics, you may be interested in messagebird/gcloud-pubsub-emulator.

Customization

This library mostly tries to stay agnostic of potential use-cases; as such, we do not implement any sort of retrying or other policies under the assumption that we wouldn’t get things right for every user’s situation.

As such, we recommend configuring your own policies on an as-needed basis. The backoff library can make this quite straightforward! For example, you may find it useful to configure something like:

class SubscriberClientWithBackoff(SubscriberClient):
    @backoff.on_exception(backoff.expo, aiohttp.ClientResponseError,
                          max_tries=5, jitter=backoff.full_jitter)
    async def pull(self, *args: Any, **kwargs: Any):
        return await super().pull(*args, **kwargs)

Contributing

Please see our contributing guide.

Release files for gcloud-rest-pubsub 5.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gcloud-rest-pubsub 5.0.0
File Size Uploaded
gcloud-rest-pubsub-5.0.0.tar.gz 15.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for gcloud-rest-pubsub 5.0.0
File Interpreter ABI Platform
gcloud_rest_pubsub-5.0.0-py2.py3-none-any.whl Python 3, Python 2 none any Details

Total release size: 30.9 kB

Release files / gcloud-rest-pubsub-5.0.0.tar.gz

Download URL gcloud-rest-pubsub-5.0.0.tar.gz
Size 15.3 kB
Tags Source
SHA-256 checksum
How to use checksums
58f8d831c9a716907fcf87f87b4b0daaf3b300a37a6ff324a849185619880727
BLAKE2b-256 checksum
How to use checksums
b488b602ac4ab290c237f08f667f9fdcf29fa7f7edc5cf5d68247b0e7d1a8ca5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.1.13 CPython/3.9.12 Linux/5.13.0-1017-aws

Release files / gcloud_rest_pubsub-5.0.0-py2.py3-none-any.whl

Download URL gcloud_rest_pubsub-5.0.0-py2.py3-none-any.whl
Size 15.6 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
bba573e741511a25afc76b9dc292fd5c4179d764df56e0b187ebb5d41f78bcfc
BLAKE2b-256 checksum
How to use checksums
b36bd170179791156211c6a657bd63731a60f677aa453e2747fd793bf29983d2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.1.13 CPython/3.9.12 Linux/5.13.0-1017-aws

Release history Release notifications | RSS feed

6.3.0

2 release files

6.2.0

2 release files

6.1.0

2 release files

6.0.1

2 release files

6.0.0

2 release files

5.4.0

2 release files

5.3.0

2 release files

5.2.0

2 release files

5.1.1

2 release files

5.0.1

2 release files

This release

5.0.0 This release

2 release files

4.5.0

2 release files

4.4.0

2 release files

4.3.4

2 release files

4.3.3

2 release files

4.3.2

2 release files

4.3.1

2 release files

4.3.0

2 release files

4.2.1

2 release files

4.2.0

2 release files

4.1.0

2 release files

4.0.4

2 release files

4.0.3

2 release files

4.0.2

2 release files

4.0.1

2 release files

4.0.0

2 release files

3.0.0

2 release files

2.1.2

2 release files

2.1.1

2 release files

2.1.0

2 release files

2.0.1

2 release files

2.0.0

2 release files

1.2.3

2 release files

1.2.2

2 release files

1.2.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page