Reference¶
Transport¶
- class mersal.gcp_pubsub.transport.GCPPubSubTransport¶
Bases:
BaseTransportA GCP Pub/Sub transport using pull delivery (streaming pull) for consumption.
- Topology:
Every Mersal address - both an app’s own point-to-point address and a pub/sub topic name - becomes its own GCP topic, since Pub/Sub has no concept of routing keys or exchanges: a plain address
"billing"becomes topicf"{direct_topic_prefix}billing", while an event topic"order.created"becomesf"{event_topic_prefix}order.created". Each app’s own input queue is backed by a single dedicated subscription (named after its address) bound to its own direct topic. Pub/sub fan-out is native: every subscriber gets its own subscription on the same event topic (see mersal.gcp_pubsub.subscription_storage.GCPPubSubSubscriptionStorage), so publishing once reaches everyone subscribed.- Push-pull bridge:
SubscriberClient.subscribe delivers messages by invoking a callback on a thread pool it manages internally - a push model Every subscription’s callback is a foreign thread as far as the event loop is concerned, so it hands each message to receive via an anyio.from_thread.BlockingPortal: the callback does portal.call(send_stream.send_nowait, message) on a shared anyio memory object stream, and receive is just await receive_stream.receive(). One portal and one stream pair serve every subscription this transport consumes - this app’s own, plus one per pub/sub topic it’s subscribed to.
- Startup:
Connecting is lazy: the first call to send, receive, or create_queue creates the underlying clients and this app’s own topic/subscription/consumer if they don’t exist yet. __call__ (registered as an on-startup lifespan hook by GCPPubSubPlugin) simply triggers this eagerly. After close, the next use starts the transport again from scratch.
- Self-healing:
See GCPPubSubTransportConfig.consumer_health_check_interval.
- Send-only apps:
See GCPPubSubTransportConfig.send_only: this app’s own topic, subscription, and pull consumer are only ever created when it isn’t send-only, since a send-only app never receives.
- Deferral:
Not native (supports_deferral is False): Pub/Sub has no per-message scheduled delivery - a subscription’s retry policy/ack deadline only delays redelivery, capped at 600 seconds. Deferring goes through a timeout manager instead (see mersal.timeouts.TimeoutsConfig); without one, Mersal.defer raises.
- __init__(config: GCPPubSubTransportConfig, periodic_task_factory: PeriodicAsyncTaskFactory | None = None, logger: Logger | None = None)¶
- async close() None¶
Gracefully tear down every live consumer and the underlying clients.
Wired up as an on-shutdown lifespan hook by GCPPubSubPlugin. The transport can be used again afterwards; the next use starts it from scratch.
- async create_queue(address: str) None¶
Ensure address can receive point-to-point sends even before its owning app has ever started.
Pub/Sub discards messages published to a topic with no subscriptions - unlike RabbitMQ, where declaring a queue is what gives it retention, here the subscription is the retention. So this must create both the direct topic and address’s own subscription on it (the same subscription that app would create for itself in _ensure_started), not just the topic - otherwise a send to a not-yet-started peer is a silent, successful-looking message loss.
- async receive(transaction_context: TransactionContext) TransportMessage | None¶
Return the next message, or None after receive_timeout seconds without one.
The bounded wait is purely local - the streaming pull consumers keep running regardless, so timing out touches neither the broker nor any consumer, and a message arriving just after the deadline is simply picked up by the next call.
Unlike the RabbitMQ transport, a None never means “consumer died” here: several independent consumers feed the one stream and their health is the periodic health check’s business (see _check_consumers_health), so receive has no self-heal path for a timeout to be disentangled from.
- async send_outgoing_messages(outgoing_message: list[OutgoingMessage], transaction_context: TransactionContext) None¶
Publish every message in the batch concurrently rather than one at a time.
The publisher client batches outgoing messages internally (a short linger window), but only across publish() calls that are in flight at the same time. Awaiting each message’s result before firing the next serializes what should be one batched RPC into N sequential ones. Running each send as its own task means every publish() call in the batch fires before any of them blocks on future.result() (anyio schedules each task up to its first real suspension point), letting the client’s batching actually kick in.
- async start_consuming_topic(topic: str) None¶
Start (idempotently) a live pull consumer for this app’s own subscription on topic’s fan-out.
Called by GCPPubSubSubscriptionStorage.register_subscriber whenever this transport’s own address subscribes to a topic. Unlike RabbitMQ - where a new binding on an already-running queue needs no new consumer - GCP requires a dedicated Subscription (and therefore a dedicated pull consumer) per subscribed topic, so subscribing to a new topic at runtime genuinely means starting a new consumer here, not just a broker-side registration.
- class mersal.gcp_pubsub.transport.GCPPubSubTransportConfig¶
Bases:
objectGCPPubSubTransportConfig(project_id: ‘str’, input_queue_name: ‘str’, send_only: ‘bool’ = False, should_declare_topics: ‘bool’ = True, should_declare_subscriptions: ‘bool’ = True, direct_topic_prefix: ‘str’ = ‘mersal-direct-’, event_topic_prefix: ‘str’ = ‘mersal-topic-’, ack_deadline_seconds: ‘int’ = 60, max_outstanding_messages: ‘int’ = 50, max_lease_duration_seconds: ‘float’ = 3600.0, consumer_health_check_interval: ‘float | None’ = 60.0, receive_timeout: ‘float’ = 5.0)
- __init__(project_id: str, input_queue_name: str, send_only: bool = False, should_declare_topics: bool = True, should_declare_subscriptions: bool = True, direct_topic_prefix: str = 'mersal-direct-', event_topic_prefix: str = 'mersal-topic-', ack_deadline_seconds: int = 60, max_outstanding_messages: int = 50, max_lease_duration_seconds: float = 3600.0, consumer_health_check_interval: float | None = 60.0, receive_timeout: float = 5.0) None¶
- ack_deadline_seconds: int = 60¶
how long Pub/Sub waits for an ack before redelivering a message.
This is a dead-puller safety net, not a processing-time budget - while this transport is alive it keeps a message’s deadline extended for as long as max_lease_duration_seconds allows, regardless of what ack_deadline_seconds is set to. It only ends up mattering when there’s no one left to extend the deadline: a puller that crashes without nacking leaves its in-flight messages stuck for up to this long before Pub/Sub redelivers them.
- Type:
The subscription’s ack deadline, in seconds
- consumer_health_check_interval: float | None = 60.0¶
How often, in seconds, to check whether any live pull consumer’s underlying stream has died (e.g. a fatal, non-retryable error - transient ones are already retried internally by the client library) and restart it if so.
Set to None to disable it entirely.
- direct_topic_prefix: str = 'mersal-direct-'¶
Prefix used to derive the GCP topic id backing a plain (point-to-point) address.
- event_topic_prefix: str = 'mersal-topic-'¶
Prefix used to derive the GCP topic id backing a pub/sub topic.
Must match the event_topic_prefix of any mersal.gcp_pubsub.subscription_storage.GCPPubSubSubscriptionStorage sharing this project - subscribing and publishing only agree on where events land if both sides derive the same topic id from a given Mersal topic name.
- max_lease_duration_seconds: float = 3600.0¶
how long since receiving a message the client library will keep auto-extending its ack deadline (via modack) on behalf of this transport before giving up and letting it lapse for redelivery.
Size this to the longest a message may legitimately take to process; the per-extension deadline is auto-tuned from recent ack latency, so this is the only knob that bounds the total.
- Type:
The processing-time budget, in seconds
- max_outstanding_messages: int = 50¶
Maximum number of received - but not yet acked/nacked - messages a single pull consumer will hold locally before pausing delivery. Sized a few times larger than the app’s expected processing concurrency (see max_parallelism on the worker) keeps the pipeline fed without letting one slow consumer buffer unbounded messages in memory.
- receive_timeout: float = 5.0¶
Maximum seconds receive waits for a message before returning None.
Transport.receive must return within a bounded time rather than blocking forever, so the worker’s heartbeat keeps advancing while idle - an unbounded wait here would make a merely-idle transport indistinguishable from a wedged one to the liveness watcher. Idle backoff between calls is the worker’s job, not this transport’s.
Subscription storage¶
- class mersal.gcp_pubsub.subscription_storage.GCPPubSubSubscriptionStorage¶
Bases:
SubscriptionStorageA SubscriptionStorage that stores subscriptions as native GCP Pub/Sub subscriptions.
Unlike the RabbitMQ transport - where subscribing is just a new binding on a queue that’s already being consumed - GCP Pub/Sub requires a dedicated Subscription (and therefore a dedicated pull consumer) per subscribed topic. This storage therefore needs a reference to the subscribing app’s own GCPPubSubTransport, to start/stop that consumer whenever that transport’s own address registers or unregisters itself. transport is optional only so a storage instance can be built without a live transport at hand (e.g. tooling that only needs to inspect or manage subscriptions for other apps); a storage used to (un)register the address of the app it’s actually paired with must be given one, or that app will never actually receive what it subscribes to.
- __init__(config: GCPPubSubSubscriptionStorageConfig, transport: GCPPubSubTransport | None = None) None¶
- async close() None¶
Close the underlying clients.
The storage can be used again afterwards; the next use reconnects.
- async connect() None¶
Eagerly create the underlying clients.
Optional: every public method also connects lazily on first use, so calling this isn’t required, but doing so up front (e.g. from an app’s startup hook) surfaces connection failures before the first register_subscriber call.
- async get_subscriber_addresses(topic: str) set[str]¶
Get addresses subscribed for the given topic.
- Parameters:
topic – topic name to get the addresses for.
- Returns:
A set of addresses subscribed to this topic.
- property is_centralized: bool¶
Whether this storage is centralized.
Centralized storage means topic subscriptions are stored in one place and registration/unregistration can be done by directly calling register_subscriber and unregister_subscriber, respectively.
Non centralized means each topic handles its own storage and registration/unregistration is performed by sending a message to the topic owner (async).
- class mersal.gcp_pubsub.subscription_storage.GCPPubSubSubscriptionStorageConfig¶
Bases:
objectGCPPubSubSubscriptionStorageConfig(project_id: ‘str’, event_topic_prefix: ‘str’ = ‘mersal-topic-’, should_declare_event_topics: ‘bool’ = True, ack_deadline_seconds: ‘int’ = 60)
- __init__(project_id: str, event_topic_prefix: str = 'mersal-topic-', should_declare_event_topics: bool = True, ack_deadline_seconds: int = 60) None¶
Plugin¶
- class mersal.gcp_pubsub.plugin.GCPPubSubPlugin¶
Bases:
Plugin- __init__(config: GCPPubSubPluginConfig) None¶
- class mersal.gcp_pubsub.plugin.GCPPubSubPluginConfig¶
Bases:
objectGCPPubSubPluginConfig(project_id: ‘str’, input_queue_name: ‘str’, should_declare_topics: ‘bool’ = True, should_declare_subscriptions: ‘bool’ = True, direct_topic_prefix: ‘str’ = ‘mersal-direct-’, event_topic_prefix: ‘str’ = ‘mersal-topic-’, ack_deadline_seconds: ‘int’ = 60, max_outstanding_messages: ‘int’ = 50, max_lease_duration_seconds: ‘float’ = 3600.0, consumer_health_check_interval: ‘float | None’ = 60.0)
- __init__(project_id: str, input_queue_name: str, should_declare_topics: bool = True, should_declare_subscriptions: bool = True, direct_topic_prefix: str = 'mersal-direct-', event_topic_prefix: str = 'mersal-topic-', ack_deadline_seconds: int = 60, max_outstanding_messages: int = 50, max_lease_duration_seconds: float = 3600.0, consumer_health_check_interval: float | None = 60.0) None¶