Topics and subscriptions#
Pub/Sub keeps topics and subscriptions as separate resources. A publisher names a topic. A subscriber names a subscription attached to a topic.
from faststream import FastStream
from faststream_gcp_pubsub import PubSubBroker
broker = PubSubBroker(project_id="my-project")
app = FastStream(broker)
@broker.subscriber("orders-billing", topic="orders")
async def bill(order: dict[str, int]) -> None: ...
@broker.subscriber("orders-audit", topic="orders")
async def audit(order: dict[str, int]) -> None: ...
# a subscription named without a topic is attached to the topic of the same name
@broker.subscriber("invoices")
async def archive(invoice: dict[str, int]) -> None: ...
# a full name is used as it is: this reads a subscription of another project
@broker.subscriber("projects/other-project/subscriptions/orders-export", topic="orders")
async def export(order: dict[str, int]) -> None: ...
A message published to orders is delivered to both orders-billing and orders-audit. When
several consumers read one subscription, they share its messages.
Names#
A short id such as orders is expanded with the broker's project:
projects/my-project/topics/orders. A name that starts with projects/ is a full name and is
used as it is. This is how a subscriber reads a subscription of another project.
A subscription named without a topic is attached to the topic of the same name. The topic
argument names what the subscription is attached to. The broker uses it to declare the
resources, in the test broker routing and in the AsyncAPI document.
Names as declarations#
Both arguments also take a declaration, PubSub and
PubSubTopic, which describes how to create the resource:
from faststream import FastStream
from faststream_gcp_pubsub import PubSub, PubSubBroker, PubSubTopic
broker = PubSubBroker(project_id="my-project")
app = FastStream(broker)
@broker.subscriber(
PubSub("orders-billing", declare=True),
topic=PubSubTopic("orders"),
)
async def bill(order: dict[str, int]) -> None: ...
See Declaring resources for every setting.