Getting started#
A service is a PubSubBroker, a FastStream app and handlers.
from faststream import FastStream, Logger
from faststream_gcp_pubsub import PubSubBroker
broker = PubSubBroker(project_id="my-project")
app = FastStream(broker)
@broker.subscriber("orders-billing", topic="orders")
async def handle(order: dict[str, int], logger: Logger) -> None:
logger.info("order %s", order["id"])
The handler reads the subscription orders-billing, which is attached to the topic orders.
The broker is built without any network call; it connects when the app starts.
Run the service#
Install the cli extra, then start the app with the faststream command:
pip install "faststream-gcp-pubsub[cli]"
faststream run service:app
The service authenticates with
Application Default Credentials.
On a workstation, gcloud auth application-default login creates them. Other ways to
authenticate are on the Emulator and credentials page.
Pub/Sub keeps topics and subscriptions as separate resources, and a service reads from resources that exist. The next sections create them for local work.
Run against the emulator#
The repository ships a docker-compose.yaml that starts the Pub/Sub emulator:
services:
pubsub:
image: gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators
command: gcloud beta emulators pubsub start --host-port=0.0.0.0:8085 --project=faststream-test
ports:
- "${PUBSUB_EMULATOR_PORT:-8085}:8085"
The justfile has the recipes you need:
| Recipe | What it does |
|---|---|
just emulator-up |
Starts the emulator on port 8085 (set PUBSUB_EMULATOR_PORT to change it) and waits until it is ready. |
just test-gcp |
Runs the tests marked gcp against the emulator. |
just emulator-down |
Stops the emulator. |
A service connects to the emulator with emulator_host. A subscription declared with
declare=True creates its topic and itself at startup, so the emulator needs no setup:
from faststream import FastStream, Logger
from faststream_gcp_pubsub import PubSub, PubSubBroker
broker = PubSubBroker(project_id="faststream-test", emulator_host="localhost:8085")
app = FastStream(broker)
@broker.subscriber(PubSub("orders-billing", declare=True), topic="orders")
async def handle(order: dict[str, int], logger: Logger) -> None:
logger.info("order %s", order["id"])
@app.after_startup
async def place_order() -> None:
await broker.publish({"id": 1}, "orders")
just emulator-up
faststream run service:app
The handler logs the order that place_order publishes after startup.
Tip
Setting PUBSUB_EMULATOR_HOST=localhost:8085 in the environment has the same effect as
emulator_host, so the service code stays the same in production.
Test the service#
TestPubSubBroker runs the handlers in process:
@pytest.mark.asyncio()
async def test_service() -> None:
async with TestPubSubBroker(broker) as br:
await br.publish({"id": 1}, "orders")
handle.mock.assert_called_once_with({"id": 1})
Read Testing for the routing rules of the in-process broker.