API reference#
Broker#
faststream_gcp_pubsub.PubSubBroker
#
PubSubBroker(
project_id: str = EMPTY,
*,
emulator_host: str | None = EMPTY,
api_endpoint: str | None = None,
client_options: dict[str, Any] | None = None,
graceful_timeout: float | None = 15.0,
decoder: Optional[CustomCallable] = None,
parser: Optional[CustomCallable] = None,
codec: Optional[CodecProto] = None,
dependencies: Sequence[Dependant] = (),
middlewares: Sequence[BrokerMiddleware[Any, Any]] = (),
routers: Iterable[PubSubRegistrator] = (),
ack_policy: AckPolicy = EMPTY,
id_generator: IdGenerator = gen_cor_id,
specification_url: str | None = None,
protocol: str | None = None,
protocol_version: str | None = "v1",
description: str | None = None,
tags: Iterable[Tag | TagDict] = (),
security: Optional[BaseSecurity] = None,
logger: Optional[LoggerProto] = EMPTY,
log_level: int = INFO,
apply_types: bool = True,
serializer: Optional[SerializerProto] = EMPTY,
provider: Optional[Provider] = None,
context: Optional[ContextRepo] = None,
)
Bases: PubSubRegistrator, BrokerUsecase[PubSubRawMessage, PubSubConnection, PubSubBrokerConfig]
Google Cloud Pub/Sub broker.
The constructor only records the configuration; connect() (or start()) builds the
clients.
| PARAMETER | DESCRIPTION |
|---|---|
project_id
|
the project short topic and subscription names belong to; read from
TYPE:
|
emulator_host
|
TYPE:
|
api_endpoint
|
a regional or private endpoint instead of the global one.
TYPE:
|
client_options
|
other
TYPE:
|
security
|
a
TYPE:
|
Source code in faststream_gcp_pubsub/broker/broker.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
declare_topic
async
#
declare_topic(topic: str | PubSubTopic) -> str
Create a topic unless it exists.
| RETURNS | DESCRIPTION |
|---|---|
str
|
The full resource name of the topic. |
Source code in faststream_gcp_pubsub/broker/broker.py
199 200 201 202 203 204 205 206 207 208 209 | |
declare_subscription
async
#
declare_subscription(
subscription: str | PubSub, topic: str | PubSubTopic
) -> str
Create a subscription attached to topic unless it exists; the topic must exist.
| RETURNS | DESCRIPTION |
|---|---|
str
|
The full resource name of the subscription. |
Source code in faststream_gcp_pubsub/broker/broker.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |
publish
async
#
publish(
message: SendableMessage = None,
topic: str = "",
*,
headers: dict[str, str] | None = None,
ordering_key: str = "",
correlation_id: str | None = None,
reply_to: str = "",
timeout: float | None = None,
) -> str
Publish a message to a topic.
| PARAMETER | DESCRIPTION |
|---|---|
message
|
the message body.
TYPE:
|
topic
|
the topic, a short id or a full resource name.
TYPE:
|
headers
|
message attributes.
TYPE:
|
ordering_key
|
messages of one key are delivered in publish order to a subscription with message ordering; publish them one after another.
TYPE:
|
correlation_id
|
the correlation id; generated when omitted.
TYPE:
|
reply_to
|
the topic a consumer publishes its reply to.
TYPE:
|
timeout
|
the RPC deadline in seconds; the client's default when omitted.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The message id the service assigned. |
Source code in faststream_gcp_pubsub/broker/broker.py
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | |
publish_batch
async
#
publish_batch(
*messages: SendableMessage,
topic: str,
headers: dict[str, str] | None = None,
ordering_key: str = "",
correlation_id: str | None = None,
reply_to: str = "",
timeout: float | None = None,
) -> list[str]
Publish several messages to a topic in one request.
The service takes at most 1000 messages and 10 MB in one request.
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
The message ids, in the order of the messages. |
Source code in faststream_gcp_pubsub/broker/broker.py
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | |
request
async
#
request(
message: SendableMessage = None,
topic: str = "",
*,
correlation_id: str | None = None,
timeout: float | None = None,
) -> Any
Not available on Pub/Sub; raises FeatureNotSupportedException.
Publish with reply_to naming a topic your service subscribes to instead.
Source code in faststream_gcp_pubsub/broker/broker.py
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | |
ping
async
#
ping(timeout: float | None = None) -> bool
Source code in faststream_gcp_pubsub/broker/broker.py
192 193 194 195 196 197 | |
Resources#
faststream_gcp_pubsub.PubSubTopic
dataclass
#
PubSubTopic(
name: str,
declare: bool = False,
labels: dict[str, str] = dict(),
message_retention_duration: timedelta | None = None,
)
A Pub/Sub topic.
| ATTRIBUTE | DESCRIPTION |
|---|---|
name |
a short id (expanded with the broker's project) or a full resource name.
TYPE:
|
declare |
create the topic at startup when it does not exist.
TYPE:
|
labels |
labels of a created topic.
TYPE:
|
message_retention_duration |
how long a created topic keeps messages for seek.
TYPE:
|
message_retention_duration
class-attribute
instance-attribute
#
message_retention_duration: timedelta | None = None
path
#
path(project_id: str) -> str
The full resource name in the given project.
Source code in faststream_gcp_pubsub/schemas.py
89 90 91 | |
to_proto
#
to_proto(project_id: str) -> Topic
The topic resource the broker creates.
Source code in faststream_gcp_pubsub/schemas.py
93 94 95 96 97 98 99 100 | |
faststream_gcp_pubsub.PubSub
dataclass
#
PubSub(
name: str,
declare: bool = False,
ack_deadline_seconds: int | None = None,
enable_message_ordering: bool = False,
enable_exactly_once_delivery: bool = False,
filter: str = "",
dead_letter_policy: DeadLetterPolicy | None = None,
retry_policy: RetryPolicy | None = None,
message_retention_duration: timedelta | None = None,
labels: dict[str, str] = dict(),
)
A Pub/Sub subscription and the settings a created one gets.
The settings apply when the broker creates the subscription (declare=True); an existing
subscription keeps its own.
| ATTRIBUTE | DESCRIPTION |
|---|---|
name |
a short id (expanded with the broker's project) or a full resource name.
TYPE:
|
declare |
create the subscription (and its topic) at startup when it does not exist.
TYPE:
|
ack_deadline_seconds |
the server-side ack deadline of a created subscription, 10 to 600.
TYPE:
|
enable_message_ordering |
deliver messages of one ordering key in publish order.
TYPE:
|
enable_exactly_once_delivery |
let an acknowledged message never be redelivered.
TYPE:
|
filter |
a filter expression on attributes; messages it rejects are acknowledged by the service and never delivered.
TYPE:
|
dead_letter_policy |
where messages go after too many delivery attempts.
TYPE:
|
retry_policy |
the backoff between redeliveries.
TYPE:
|
message_retention_duration |
how long unacknowledged messages are kept.
TYPE:
|
labels |
labels of a created subscription.
TYPE:
|
enable_exactly_once_delivery
class-attribute
instance-attribute
#
enable_exactly_once_delivery: bool = False
dead_letter_policy
class-attribute
instance-attribute
#
dead_letter_policy: DeadLetterPolicy | None = None
message_retention_duration
class-attribute
instance-attribute
#
message_retention_duration: timedelta | None = None
path
#
path(project_id: str) -> str
The full resource name in the given project.
Source code in faststream_gcp_pubsub/schemas.py
135 136 137 | |
to_proto
#
to_proto(project_id: str, topic: str) -> Subscription
The subscription resource the broker creates, attached to topic (a full name).
Source code in faststream_gcp_pubsub/schemas.py
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | |
faststream_gcp_pubsub.DeadLetterPolicy
dataclass
#
DeadLetterPolicy(
topic: str, max_delivery_attempts: int = 5
)
Where Pub/Sub moves a message after too many delivery attempts.
| ATTRIBUTE | DESCRIPTION |
|---|---|
topic |
the dead-letter topic, a short id or a full name.
TYPE:
|
max_delivery_attempts |
attempts before the move, 5 to 100.
TYPE:
|
faststream_gcp_pubsub.RetryPolicy
dataclass
#
RetryPolicy(
minimum_backoff: timedelta = timedelta(seconds=10),
maximum_backoff: timedelta = timedelta(seconds=600),
)
The backoff Pub/Sub applies between redeliveries of a nacked message.
| ATTRIBUTE | DESCRIPTION |
|---|---|
minimum_backoff |
the shortest delay, 0 to 600 seconds.
TYPE:
|
maximum_backoff |
the longest delay, 0 to 600 seconds.
TYPE:
|
Consuming#
faststream_gcp_pubsub.FlowControl
dataclass
#
FlowControl(
*,
max_messages: int = 1000,
max_bytes: int = 100 * 1024 * 1024,
ack_deadline: int = 60,
max_lease: float = 3600.0,
ack_batch_wait: float = 0.05,
)
How a subscriber leases and settles deliveries.
| ATTRIBUTE | DESCRIPTION |
|---|---|
max_messages |
deliveries held at once, unsettled; the stream is not read further while this many are held.
TYPE:
|
max_bytes |
payload bytes held at once; the service stops sending past it.
TYPE:
|
ack_deadline |
seconds a lease lasts before it is extended, 10 to 600.
TYPE:
|
max_lease |
seconds a delivery is held at most, from its arrival; past it the lease is no longer extended and the service redelivers the message.
TYPE:
|
ack_batch_wait |
seconds acks and nacks wait to be sent together.
TYPE:
|
Publishing#
faststream_gcp_pubsub.PubSubResponse
#
PubSubResponse(
body: SendableMessage,
*,
headers: dict[str, str] | None = None,
correlation_id: str | None = None,
ordering_key: str = "",
)
Bases: Response
A handler result with Pub/Sub publish options.
Return it from a handler to set the ordering key or attributes of the reply and of every publisher the handler is decorated with.
Source code in faststream_gcp_pubsub/response.py
20 21 22 23 24 25 26 27 28 29 | |
as_publish_command
#
as_publish_command() -> PubSubPublishCommand
Source code in faststream_gcp_pubsub/response.py
31 32 33 34 35 36 37 38 39 | |
Routers#
faststream_gcp_pubsub.PubSubRouter
#
PubSubRouter(
prefix: str = "",
handlers: Iterable[PubSubRoute] = (),
*,
dependencies: Sequence[Dependant] = (),
middlewares: Sequence[BrokerMiddleware[Any, Any]] = (),
routers: Iterable[PubSubRegistrator] = (),
parser: Optional[CustomCallable] = None,
decoder: Optional[CustomCallable] = None,
include_in_schema: bool | None = None,
ack_policy: AckPolicy = EMPTY,
)
Bases: PubSubRegistrator, BrokerRouter[PubSubRawMessage, PubSubBrokerConfig]
A group of subscribers and publishers to include into a PubSubBroker.
prefix is prepended to the topic and subscription names it declares.
Source code in faststream_gcp_pubsub/broker/router.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
faststream_gcp_pubsub.PubSubRoute
#
PubSubRoute(
call: Callable[..., SendableMessage]
| Callable[..., Awaitable[SendableMessage]],
subscription: str | PubSub,
*,
topic: str | PubSubTopic | None = None,
publishers: Iterable[PubSubPublisher] = (),
flow_control: Optional[FlowControl] = None,
ack_policy: AckPolicy = EMPTY,
no_reply: bool = False,
dependencies: Sequence[Dependant] = (),
parser: Optional[CustomCallable] = None,
decoder: Optional[CustomCallable] = None,
codec: Optional[CodecProto] = None,
max_workers: int = 1,
persistent: bool = True,
title: str | None = None,
description: str | None = None,
include_in_schema: bool = True,
)
Bases: SubscriberRoute
Delayed subscriber registration: the arguments of PubSubRegistrator.subscriber.
Source code in faststream_gcp_pubsub/broker/router.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
faststream_gcp_pubsub.PubSubPublisher
#
PubSubPublisher(
topic: str | PubSubTopic,
*,
ordering_key: str = "",
headers: dict[str, str] | None = None,
persistent: bool = True,
title: str | None = None,
description: str | None = None,
schema: Any | None = None,
include_in_schema: bool = True,
)
Bases: ArgsContainer
Delayed publisher registration: the arguments of PubSubRegistrator.publisher.
Source code in faststream_gcp_pubsub/broker/router.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
Security#
faststream_gcp_pubsub.GCPSecurity
#
GCPSecurity(credentials: Credentials)
Bases: BaseSecurity
Google credentials the broker authenticates with.
Without a security object the broker uses Application Default Credentials (the
GOOGLE_APPLICATION_CREDENTIALS file, the gcloud login, or the metadata server).
Examples:
>>> def from_credentials() -> PubSubBroker:
... credentials = service_account.Credentials.from_service_account_file("key.json")
... return PubSubBroker(project_id="my-project", security=GCPSecurity(credentials))
Source code in faststream_gcp_pubsub/security.py
26 27 28 | |
from_service_account_file
classmethod
#
from_service_account_file(filename: str) -> GCPSecurity
Credentials of a service account from its JSON key file.
Source code in faststream_gcp_pubsub/security.py
30 31 32 33 34 35 | |
from_service_account_info
classmethod
#
from_service_account_info(
info: dict[str, Any],
) -> GCPSecurity
Credentials of a service account from its parsed JSON key.
Source code in faststream_gcp_pubsub/security.py
37 38 39 40 41 42 | |
get_requirement
#
get_requirement() -> list[dict[str, Any]]
Source code in faststream_gcp_pubsub/security.py
44 45 46 | |
get_schema
#
get_schema() -> dict[str, dict[str, str]]
Source code in faststream_gcp_pubsub/security.py
48 49 50 | |
Testing#
faststream_gcp_pubsub.testing.TestPubSubBroker
#
TestPubSubBroker(
broker: PubSubBroker,
/,
*,
with_real: bool = False,
connect_only: bool | None = None,
)
TestPubSubBroker(
*brokers: PubSubBroker,
with_real: bool = False,
connect_only: bool | None = None,
)
TestPubSubBroker(
*brokers: PubSubBroker,
with_real: bool = False,
connect_only: bool | None = None,
)
Bases: TestBroker[PubSubBroker, Any]
The broker in process: a publish reaches the subscriptions of its topic directly.
It routes the way the service does. A topic delivers to every subscription attached to
it; the consumers of one subscription share its messages; a subscription read by
get_one or iteration keeps what is published until it is read. A publish the service
rejects (attribute, size and name limits) raises the service's InvalidArgument.
Examples:
>>> async with TestPubSubBroker(broker) as br:
... await br.publish({"id": 1}, "orders")
...
... bill.mock.assert_called_once_with({"id": 1})
Source code in faststream_gcp_pubsub/testing.py
64 65 66 67 68 69 70 71 | |
create_publisher_fake_subscriber
#
create_publisher_fake_subscriber(
broker: PubSubBroker, publisher: PubSubPublisher
) -> tuple[PubSubBaseSubscriber, bool]
Source code in faststream_gcp_pubsub/testing.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | |
Integrations#
faststream_gcp_pubsub.fastapi.PubSubRouter
#
PubSubRouter(
project_id: str = EMPTY,
*,
emulator_host: str | None = EMPTY,
api_endpoint: str | None = None,
client_options: dict[str, Any] | None = None,
graceful_timeout: float | None = 15.0,
decoder: Optional[CustomCallable] = None,
parser: Optional[CustomCallable] = None,
codec: Optional[CodecProto] = None,
middlewares: Sequence[BrokerMiddleware[Any, Any]] = (),
ack_policy: AckPolicy = EMPTY,
id_generator: IdGenerator = gen_cor_id,
serializer: Optional[SerializerProto] = EMPTY,
security: Optional[BaseSecurity] = None,
specification_url: str | None = None,
protocol: str | None = None,
protocol_version: str | None = "v1",
description: str | None = None,
specification: Optional[SpecificationFactory] = None,
specification_tags: Iterable[Union[Tag, TagDict]] = (),
logger: Optional[LoggerProto] = EMPTY,
log_level: int = INFO,
setup_state: bool = True,
schema_url: str | None = "/asyncapi",
context: ContextRepo | None = None,
prefix: str = "",
tags: list[Union[str, Enum]] | None = None,
dependencies: Sequence[Depends] | None = None,
default_response_class: type[Response] = Default(
JSONResponse
),
responses: dict[int | str, dict[str, Any]]
| None = None,
callbacks: list[BaseRoute] | None = None,
routes: list[BaseRoute] | None = None,
redirect_slashes: bool = True,
default: Optional[ASGIApp] = None,
dependency_overrides_provider: Any | None = None,
route_class: type[APIRoute] = APIRoute,
on_startup: Sequence[Callable[[], Any]] | None = None,
on_shutdown: Sequence[Callable[[], Any]] | None = None,
lifespan: Optional[Lifespan[Any]] = None,
deprecated: bool | None = None,
include_in_schema: bool = True,
generate_unique_id_function: Callable[
[APIRoute], str
] = Default(generate_unique_id),
)
Bases: StreamRouter[PubSubRawMessage]
FastAPI router for the Pub/Sub broker.
Takes the arguments of PubSubBroker and of fastapi.APIRouter; the broker's
dependencies are the FastAPI dependencies here, and its tags are
specification_tags.
Source code in faststream_gcp_pubsub/fastapi/fastapi.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
subscriber
#
subscriber(
subscription: str | PubSub,
*,
topic: str | PubSubTopic | None = None,
flow_control: Optional[FlowControl] = None,
ack_policy: AckPolicy = EMPTY,
no_reply: bool = False,
dependencies: Iterable[Depends] = (),
parser: Optional[CustomCallable] = None,
decoder: Optional[CustomCallable] = None,
codec: Optional[CodecProto] = None,
max_workers: Literal[1] = 1,
persistent: bool = True,
title: str | None = None,
description: str | None = None,
include_in_schema: bool = True,
response_model: Any = Default(None),
response_model_include: Optional[IncEx] = None,
response_model_exclude: Optional[IncEx] = None,
response_model_by_alias: bool = True,
response_model_exclude_unset: bool = False,
response_model_exclude_defaults: bool = False,
response_model_exclude_none: bool = False,
) -> PubSubDefaultSubscriber
subscriber(
subscription: str | PubSub,
*,
topic: str | PubSubTopic | None = None,
flow_control: Optional[FlowControl] = None,
ack_policy: AckPolicy = EMPTY,
no_reply: bool = False,
dependencies: Iterable[Depends] = (),
parser: Optional[CustomCallable] = None,
decoder: Optional[CustomCallable] = None,
codec: Optional[CodecProto] = None,
max_workers: int = ...,
persistent: bool = True,
title: str | None = None,
description: str | None = None,
include_in_schema: bool = True,
response_model: Any = Default(None),
response_model_include: Optional[IncEx] = None,
response_model_exclude: Optional[IncEx] = None,
response_model_by_alias: bool = True,
response_model_exclude_unset: bool = False,
response_model_exclude_defaults: bool = False,
response_model_exclude_none: bool = False,
) -> PubSubConcurrentSubscriber
subscriber(
subscription: str | PubSub,
*,
topic: str | PubSubTopic | None = None,
flow_control: Optional[FlowControl] = None,
ack_policy: AckPolicy = EMPTY,
no_reply: bool = False,
dependencies: Iterable[Depends] = (),
parser: Optional[CustomCallable] = None,
decoder: Optional[CustomCallable] = None,
codec: Optional[CodecProto] = None,
max_workers: int = 1,
persistent: bool = True,
title: str | None = None,
description: str | None = None,
include_in_schema: bool = True,
response_model: Any = Default(None),
response_model_include: Optional[IncEx] = None,
response_model_exclude: Optional[IncEx] = None,
response_model_by_alias: bool = True,
response_model_exclude_unset: bool = False,
response_model_exclude_defaults: bool = False,
response_model_exclude_none: bool = False,
) -> PubSubDefaultSubscriber | PubSubConcurrentSubscriber
Source code in faststream_gcp_pubsub/fastapi/fastapi.py
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | |
publisher
#
publisher(
topic: str | PubSubTopic,
*,
ordering_key: str = "",
headers: dict[str, str] | None = None,
persistent: bool = True,
title: str | None = None,
description: str | None = None,
schema: Any | None = None,
include_in_schema: bool = True,
) -> PubSubPublisher
Source code in faststream_gcp_pubsub/fastapi/fastapi.py
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
faststream_gcp_pubsub.opentelemetry.PubSubTelemetryMiddleware
#
PubSubTelemetryMiddleware(
*,
tracer_provider: TracerProvider | None = None,
meter_provider: MeterProvider | None = None,
meter: Meter | None = None,
include_messages_counters: bool = True,
)
Bases: TelemetryMiddleware[PubSubPublishCommand]
Traces and measures Pub/Sub publishes and deliveries with OpenTelemetry.
Source code in faststream_gcp_pubsub/opentelemetry/middleware.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
faststream_gcp_pubsub.prometheus.PubSubPrometheusMiddleware
#
PubSubPrometheusMiddleware(
*,
registry: CollectorRegistry,
app_name: str = EMPTY,
metrics_prefix: str = "faststream",
received_messages_size_buckets: Sequence[float]
| None = None,
custom_labels: dict[str, str | Callable[[Any], str]]
| None = None,
)
Bases: PrometheusMiddleware[PubSubRawMessage, PubSubPublishCommand]
Exports Prometheus metrics of Pub/Sub publishes and deliveries.
Source code in faststream_gcp_pubsub/prometheus/middleware.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | |