Skip to content

PubSubClient class

fastpubsub._internal.clients.PubSubClient

PubSubClient(project_id)

Creates topics and subscriptions, and publishes messages.

Initializes the PubSubClient.

PARAMETER DESCRIPTION
project_id

The Google Cloud project ID.

TYPE: str

Source code in fastpubsub/_internal/clients.py
def __init__(self, project_id: str) -> None:
    """Initializes the PubSubClient.

    Args:
        project_id: The Google Cloud project ID.
    """
    self.project_id = project_id
    self.connection = Connection(project_id)
    self.is_emulator = Connection.is_emulator()

project_id instance-attribute

project_id = project_id

connection instance-attribute

connection = Connection(project_id)

is_emulator instance-attribute

is_emulator = Connection.is_emulator()

create_topic async

create_topic(topic_name, create_default_subscription=True)

Creates a topic.

PARAMETER DESCRIPTION
topic_name

The name of the topic.

TYPE: str

create_default_subscription

Whether to create a default subscription for the topic.

TYPE: bool DEFAULT: True

Source code in fastpubsub/_internal/clients.py
async def create_topic(
    self, topic_name: str, create_default_subscription: bool = True
) -> None:
    """Creates a topic.

    Args:
        topic_name: The name of the topic.
        create_default_subscription: Whether to create a default
            subscription for the topic.
    """
    admin_client = await PubSubClientFactory.get_admin_client()
    topic_path = self.connection.topic_path(topic_name)
    with suppress(AlreadyExistsError):
        await asyncio.to_thread(admin_client.create_topic, topic_path)
        logger.debug(f"Created topic '{topic_path}' successfully.")
        if not create_default_subscription:
            return
        await asyncio.to_thread(
            admin_client.create_subscription,
            self.connection.subscription_path(topic_name),
            topic_path,
            {},
        )

create_subscription async

create_subscription(
    topic_name,
    subscription_name,
    retry_policy,
    delivery_policy,
    dead_letter_policy=None,
)

Creates a subscription.

PARAMETER DESCRIPTION
topic_name

The name of the topic.

TYPE: str

subscription_name

The name of the subscription.

TYPE: str

retry_policy

The retry policy for the subscription.

TYPE: MessageRetryPolicy

delivery_policy

The delivery policy for the subscription.

TYPE: MessageDeliveryPolicy

dead_letter_policy

The dead-letter policy for the subscription.

TYPE: DeadLetterPolicy | None DEFAULT: None

Source code in fastpubsub/_internal/clients.py
async def create_subscription(
    self,
    topic_name: str,
    subscription_name: str,
    retry_policy: MessageRetryPolicy,
    delivery_policy: MessageDeliveryPolicy,
    dead_letter_policy: DeadLetterPolicy | None = None,
) -> None:
    """Creates a subscription.

    Args:
        topic_name: The name of the topic.
        subscription_name: The name of the subscription.
        retry_policy: The retry policy for the subscription.
        delivery_policy: The delivery policy for the subscription.
        dead_letter_policy: The dead-letter policy for the subscription.
    """
    admin_client = await PubSubClientFactory.get_admin_client()
    with suppress(AlreadyExistsError):
        await asyncio.to_thread(
            admin_client.create_subscription,
            self.connection.subscription_path(subscription_name),
            self.connection.topic_path(topic_name),
            self._build_settings(
                retry_policy, delivery_policy, dead_letter_policy
            ),
        )

update_subscription async

update_subscription(
    topic_name,
    subscription_name,
    retry_policy,
    delivery_policy,
    dead_letter_policy=None,
)

Updates a subscription.

PARAMETER DESCRIPTION
topic_name

The name of the topic.

TYPE: str

subscription_name

The name of the subscription.

TYPE: str

retry_policy

The retry policy for the subscription.

TYPE: MessageRetryPolicy

delivery_policy

The delivery policy for the subscription.

TYPE: MessageDeliveryPolicy

dead_letter_policy

The dead-letter policy for the subscription.

TYPE: DeadLetterPolicy | None DEFAULT: None

Source code in fastpubsub/_internal/clients.py
async def update_subscription(
    self,
    topic_name: str,
    subscription_name: str,
    retry_policy: MessageRetryPolicy,
    delivery_policy: MessageDeliveryPolicy,
    dead_letter_policy: DeadLetterPolicy | None = None,
) -> None:
    """Updates a subscription.

    Args:
        topic_name: The name of the topic.
        subscription_name: The name of the subscription.
        retry_policy: The retry policy for the subscription.
        delivery_policy: The delivery policy for the subscription.
        dead_letter_policy: The dead-letter policy for the subscription.
    """
    update_fields = [
        "ack_deadline_seconds",
        "dead_letter_policy",
        "retry_policy",
        "enable_exactly_once_delivery",
    ]
    if not self.is_emulator:
        update_fields.append("filter")

    admin_client = await PubSubClientFactory.get_admin_client()
    subscription_path = self.connection.subscription_path(
        subscription_name
    )
    topic_path = self.connection.topic_path(topic_name)
    try:
        await asyncio.to_thread(
            admin_client.update_subscription,
            subscription_path,
            topic_path,
            self._build_settings(
                retry_policy, delivery_policy, dead_letter_policy
            ),
            update_fields,
        )
    except CoreNotFoundError as e:
        raise FastPubSubException(
            "We could not update the subscription configuration. "
            f"The topic {topic_path} or "
            f"subscription {subscription_path} were not found. "
            "They may be deleted or not autocreated. "
            "Please, setup your @subscriber with the 'autocreate=True' "
            "option to automatically create them."
        ) from e

publish async

publish(topic_name, *, data, ordering_key, attributes)

Publishes a message.

PARAMETER DESCRIPTION
topic_name

The name of the topic.

TYPE: str

data

The message data.

TYPE: bytes

ordering_key

The ordering key for the message.

TYPE: str

attributes

A dictionary of message attributes.

TYPE: dict[str, str] | None

RAISES DESCRIPTION
NotFoundError

The topic does not exist.

Source code in fastpubsub/_internal/clients.py
async def publish(
    self,
    topic_name: str,
    *,
    data: bytes,
    ordering_key: str,
    attributes: dict[str, str] | None,
) -> None:
    """Publishes a message.

    Args:
        topic_name: The name of the topic.
        data: The message data.
        ordering_key: The ordering key for the message.
        attributes: A dictionary of message attributes.

    Raises:
        NotFoundError: The topic does not exist.
    """
    topic_path = self.connection.topic_path(topic_name)
    publisher = await PubSubClientFactory.get_publisher(topic_path)
    future: asyncio.Future[str] = (
        asyncio.get_running_loop().create_future()
    )
    try:
        publisher.publish(data, attributes or {}, future, ordering_key)
        message_id = await future
        logger.info(
            f"Message published for topic {topic_path} "
            f"with id {message_id}"
        )
    except CoreNotFoundError as e:
        logger.exception("Publisher failure", stacklevel=5)
        raise NotFoundError(str(e)) from e
    except Exception:
        logger.exception("Publisher failure", stacklevel=5)
        raise