Skip to content

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 GOOGLE_CLOUD_PROJECT when omitted.

TYPE: str DEFAULT: EMPTY

emulator_host

host:port of a Pub/Sub emulator; read from PUBSUB_EMULATOR_HOST when omitted. None connects to Google Cloud even when the variable is set.

TYPE: str | None DEFAULT: EMPTY

api_endpoint

a regional or private endpoint instead of the global one.

TYPE: str | None DEFAULT: None

client_options

other google.api_core.client_options for both clients.

TYPE: dict[str, Any] | None DEFAULT: None

security

a GCPSecurity with the credentials to use; Application Default Credentials when omitted.

TYPE: Optional[BaseSecurity] DEFAULT: None

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
def __init__(
    self,
    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,
    # AsyncAPI args
    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,
    # logging args
    logger: Optional["LoggerProto"] = EMPTY,
    log_level: int = logging.INFO,
    # FastDepends args
    apply_types: bool = True,
    serializer: Optional["SerializerProto"] = EMPTY,
    provider: Optional["Provider"] = None,
    context: Optional["ContextRepo"] = None,
) -> None:
    if project_id is EMPTY:
        project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "")
    if emulator_host is EMPTY:
        emulator_host = os.environ.get("PUBSUB_EMULATOR_HOST") or None

    self._connection_options = ConnectionOptions(
        emulator_host=emulator_host,
        credentials=parse_security(security),
        api_endpoint=api_endpoint,
        client_options=client_options,
    )

    if specification_url is None:
        specification_url = emulator_host or api_endpoint or DEFAULT_ENDPOINT

    super().__init__(
        # broker config
        routers=routers,
        config=PubSubBrokerConfig(
            project_id=project_id,
            producer=PubSubProducer(parser=parser, decoder=decoder),
            broker_middlewares=middlewares,
            broker_parser=parser,
            broker_decoder=decoder,
            broker_codec=codec,
            logger=make_pubsub_logger_state(
                logger=logger,
                log_level=log_level,
            ),
            fd_config=FastDependsConfig(
                use_fastdepends=apply_types,
                serializer=serializer,
                provider=provider or dependency_provider,
                context=context or ContextRepo(),
            ),
            broker_dependencies=dependencies,
            graceful_timeout=graceful_timeout,
            ack_policy=ack_policy,
            id_generator=id_generator,
            extra_context={
                "broker": self,
            },
        ),
        specification=BrokerSpec(
            description=description,
            url=[specification_url],
            protocol=protocol or "googlepubsub",
            protocol_version=protocol_version,
            tags=tags,
            security=security,
        ),
    )

project_id property #

project_id: str

The project short names belong to.

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
async def declare_topic(self, topic: str | PubSubTopic) -> str:
    """Create a topic unless it exists.

    Returns:
        The full resource name of the topic.
    """
    topic_ = topic if isinstance(topic, PubSubTopic) else PubSubTopic(topic)
    request = topic_.to_proto(self.config.project_id)
    with contextlib.suppress(AlreadyExists):
        await self.config.connection.publisher.create_topic(request=request)
    return str(request.name)

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
async def declare_subscription(
    self,
    subscription: str | PubSub,
    topic: str | PubSubTopic,
) -> str:
    """Create a subscription attached to ``topic`` unless it exists; the topic must exist.

    Returns:
        The full resource name of the subscription.
    """
    subscription_ = (
        subscription if isinstance(subscription, PubSub) else PubSub(subscription)
    )
    topic_name = topic.name if isinstance(topic, PubSubTopic) else topic
    project = self.config.project_id
    request = subscription_.to_proto(
        project, resource_path(project, "topics", topic_name)
    )
    with contextlib.suppress(AlreadyExists):
        await self.config.connection.subscriber.create_subscription(request=request)
    return str(request.name)

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: SendableMessage DEFAULT: None

topic

the topic, a short id or a full resource name.

TYPE: str DEFAULT: ''

headers

message attributes.

TYPE: dict[str, str] | None DEFAULT: None

ordering_key

messages of one key are delivered in publish order to a subscription with message ordering; publish them one after another.

TYPE: str DEFAULT: ''

correlation_id

the correlation id; generated when omitted.

TYPE: str | None DEFAULT: None

reply_to

the topic a consumer publishes its reply to.

TYPE: str DEFAULT: ''

timeout

the RPC deadline in seconds; the client's default when omitted.

TYPE: float | None DEFAULT: None

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
@override
async def publish(
    self,
    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.

    Args:
        message: the message body.
        topic: the topic, a short id or a full resource name.
        headers: message attributes.
        ordering_key: messages of one key are delivered in publish order to a subscription
            with message ordering; publish them one after another.
        correlation_id: the correlation id; generated when omitted.
        reply_to: the topic a consumer publishes its reply to.
        timeout: the RPC deadline in seconds; the client's default when omitted.

    Returns:
        The message id the service assigned.
    """
    cmd = PubSubPublishCommand(
        message,
        topic=topic,
        headers=headers,
        ordering_key=ordering_key,
        correlation_id=correlation_id or self.config.id_generator(),
        reply_to=reply_to,
        timeout=timeout,
        _publish_type=PublishType.PUBLISH,
    )
    result: str = await self._basic_publish(cmd, producer=self.config.producer)
    return result

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
async def publish_batch(  # type: ignore[override]
    self,
    *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:
        The message ids, in the order of the messages.
    """
    cmd = PubSubPublishCommand(
        *messages,
        topic=topic,
        headers=headers,
        ordering_key=ordering_key,
        correlation_id=correlation_id or self.config.id_generator(),
        reply_to=reply_to,
        timeout=timeout,
        _publish_type=PublishType.PUBLISH,
    )
    result: list[str] = await self._basic_publish_batch(
        cmd, producer=self.config.producer
    )
    return result

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
@override
async def request(  # type: ignore[override]
    self,
    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.
    """
    cmd = PubSubPublishCommand(
        message,
        topic=topic,
        correlation_id=correlation_id or self.config.id_generator(),
        timeout=timeout,
        _publish_type=PublishType.REQUEST,
    )
    return await self._basic_request(cmd, producer=self.config.producer)

ping async #

ping(timeout: float | None = None) -> bool
Source code in faststream_gcp_pubsub/broker/broker.py
192
193
194
195
196
197
@override
async def ping(self, timeout: float | None = None) -> bool:
    if self._connection is None:
        return False
    connection: PubSubConnection = self._connection
    return await connection.ready(timeout or 5.0)

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: str

declare

create the topic at startup when it does not exist.

TYPE: bool

labels

labels of a created topic.

TYPE: dict[str, str]

message_retention_duration

how long a created topic keeps messages for seek.

TYPE: timedelta | None

name instance-attribute #

name: str

declare class-attribute instance-attribute #

declare: bool = False

labels class-attribute instance-attribute #

labels: dict[str, str] = field(default_factory=dict)

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
def path(self, project_id: str) -> str:
    """The full resource name in the given project."""
    return resource_path(project_id, "topics", self.name)

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
def to_proto(self, project_id: str) -> "Topic":
    """The topic resource the broker creates."""
    from google.pubsub_v1 import Topic  # ruff: ignore[import-outside-top-level]

    options: dict[str, Any] = {"name": self.path(project_id), "labels": self.labels}
    if self.message_retention_duration is not None:
        options["message_retention_duration"] = self.message_retention_duration
    return Topic(**options)

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: str

declare

create the subscription (and its topic) at startup when it does not exist.

TYPE: bool

ack_deadline_seconds

the server-side ack deadline of a created subscription, 10 to 600.

TYPE: int | None

enable_message_ordering

deliver messages of one ordering key in publish order.

TYPE: bool

enable_exactly_once_delivery

let an acknowledged message never be redelivered.

TYPE: bool

filter

a filter expression on attributes; messages it rejects are acknowledged by the service and never delivered.

TYPE: str

dead_letter_policy

where messages go after too many delivery attempts.

TYPE: DeadLetterPolicy | None

retry_policy

the backoff between redeliveries.

TYPE: RetryPolicy | None

message_retention_duration

how long unacknowledged messages are kept.

TYPE: timedelta | None

labels

labels of a created subscription.

TYPE: dict[str, str]

name instance-attribute #

name: str

declare class-attribute instance-attribute #

declare: bool = False

ack_deadline_seconds class-attribute instance-attribute #

ack_deadline_seconds: int | None = None

enable_message_ordering class-attribute instance-attribute #

enable_message_ordering: bool = False

enable_exactly_once_delivery class-attribute instance-attribute #

enable_exactly_once_delivery: bool = False

filter class-attribute instance-attribute #

filter: str = ''

dead_letter_policy class-attribute instance-attribute #

dead_letter_policy: DeadLetterPolicy | None = None

retry_policy class-attribute instance-attribute #

retry_policy: RetryPolicy | None = None

message_retention_duration class-attribute instance-attribute #

message_retention_duration: timedelta | None = None

labels class-attribute instance-attribute #

labels: dict[str, str] = field(default_factory=dict)

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
def path(self, project_id: str) -> str:
    """The full resource name in the given project."""
    return resource_path(project_id, "subscriptions", self.name)

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
def to_proto(self, project_id: str, topic: str) -> "Subscription":
    """The subscription resource the broker creates, attached to ``topic`` (a full name)."""
    from google.pubsub_v1 import Subscription  # ruff: ignore[import-outside-top-level]

    options: dict[str, Any] = {
        "name": self.path(project_id),
        "topic": topic,
        "enable_message_ordering": self.enable_message_ordering,
        "enable_exactly_once_delivery": self.enable_exactly_once_delivery,
        "filter": self.filter,
        "labels": self.labels,
    }
    if self.ack_deadline_seconds is not None:
        options["ack_deadline_seconds"] = self.ack_deadline_seconds
    if self.message_retention_duration is not None:
        options["message_retention_duration"] = self.message_retention_duration
    if self.dead_letter_policy is not None:
        options["dead_letter_policy"] = {
            "dead_letter_topic": resource_path(
                project_id, "topics", self.dead_letter_policy.topic
            ),
            "max_delivery_attempts": self.dead_letter_policy.max_delivery_attempts,
        }
    if self.retry_policy is not None:
        options["retry_policy"] = {
            "minimum_backoff": self.retry_policy.minimum_backoff,
            "maximum_backoff": self.retry_policy.maximum_backoff,
        }
    return Subscription(**options)

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: str

max_delivery_attempts

attempts before the move, 5 to 100.

TYPE: int

topic instance-attribute #

topic: str

max_delivery_attempts class-attribute instance-attribute #

max_delivery_attempts: int = 5

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: timedelta

maximum_backoff

the longest delay, 0 to 600 seconds.

TYPE: timedelta

minimum_backoff class-attribute instance-attribute #

minimum_backoff: timedelta = timedelta(seconds=10)

maximum_backoff class-attribute instance-attribute #

maximum_backoff: timedelta = timedelta(seconds=600)

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: int

max_bytes

payload bytes held at once; the service stops sending past it.

TYPE: int

ack_deadline

seconds a lease lasts before it is extended, 10 to 600.

TYPE: int

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: float

ack_batch_wait

seconds acks and nacks wait to be sent together.

TYPE: float

max_messages class-attribute instance-attribute #

max_messages: int = 1000

max_bytes class-attribute instance-attribute #

max_bytes: int = 100 * 1024 * 1024

ack_deadline class-attribute instance-attribute #

ack_deadline: int = 60

max_lease class-attribute instance-attribute #

max_lease: float = 3600.0

ack_batch_wait class-attribute instance-attribute #

ack_batch_wait: float = 0.05

faststream_gcp_pubsub.PubSubMessage module-attribute #

PubSubMessage = PSM

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
def __init__(
    self,
    body: "SendableMessage",
    *,
    headers: dict[str, str] | None = None,
    correlation_id: str | None = None,
    ordering_key: str = "",
) -> None:
    super().__init__(body=body, headers=headers, correlation_id=correlation_id)
    self.ordering_key = ordering_key

ordering_key instance-attribute #

ordering_key = ordering_key

as_publish_command #

as_publish_command() -> PubSubPublishCommand
Source code in faststream_gcp_pubsub/response.py
31
32
33
34
35
36
37
38
39
@override
def as_publish_command(self) -> "PubSubPublishCommand":
    return PubSubPublishCommand(
        self.body,
        headers=self.headers,
        correlation_id=self.correlation_id,
        ordering_key=self.ordering_key,
        _publish_type=PublishType.PUBLISH,
    )

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
def __init__(
    self,
    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,
) -> None:
    super().__init__(
        handlers=handlers,
        config=PubSubBrokerConfig(
            prefix=prefix,
            ack_policy=ack_policy,
            broker_dependencies=dependencies,
            broker_middlewares=middlewares,
            broker_parser=parser,
            broker_decoder=decoder,
            include_in_schema=include_in_schema,
        ),
        routers=routers,
    )

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
def __init__(
    self,
    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,
) -> None:
    super().__init__(
        call,
        subscription,
        publishers=publishers,
        persistent=persistent,
        topic=topic,
        flow_control=flow_control,
        ack_policy=ack_policy,
        no_reply=no_reply,
        dependencies=dependencies,
        parser=parser,
        decoder=decoder,
        codec=codec,
        max_workers=max_workers,
        title=title,
        description=description,
        include_in_schema=include_in_schema,
    )

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
def __init__(
    self,
    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,
) -> None:
    super().__init__(
        topic,
        ordering_key=ordering_key,
        headers=headers,
        persistent=persistent,
        title=title,
        description=description,
        schema=schema,
        include_in_schema=include_in_schema,
    )

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
def __init__(self, credentials: "Credentials") -> None:
    super().__init__(use_ssl=True)
    self.credentials = credentials

credentials instance-attribute #

credentials = credentials

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
@classmethod
def from_service_account_file(cls, filename: str) -> "GCPSecurity":
    """Credentials of a service account from its JSON key file."""
    from google.oauth2 import service_account  # ruff: ignore[import-outside-top-level]

    return cls(service_account.Credentials.from_service_account_file(filename))

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
@classmethod
def from_service_account_info(cls, info: dict[str, Any]) -> "GCPSecurity":
    """Credentials of a service account from its parsed JSON key."""
    from google.oauth2 import service_account  # ruff: ignore[import-outside-top-level]

    return cls(service_account.Credentials.from_service_account_info(info))

get_requirement #

get_requirement() -> list[dict[str, Any]]
Source code in faststream_gcp_pubsub/security.py
44
45
46
@override
def get_requirement(self) -> list[dict[str, Any]]:
    return [{"google-oauth2": []}]

get_schema #

get_schema() -> dict[str, dict[str, str]]
Source code in faststream_gcp_pubsub/security.py
48
49
50
@override
def get_schema(self) -> dict[str, dict[str, str]]:
    return {"google-oauth2": {"type": "oauth2"}}

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
def __init__(
    self,
    *brokers: PubSubBroker,
    with_real: bool = False,
    connect_only: bool | None = None,
) -> None:
    super().__init__(*brokers, with_real=with_real, connect_only=connect_only)
    self.service = InMemoryService()

service instance-attribute #

service = InMemoryService()

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
def create_publisher_fake_subscriber(
    self,
    broker: PubSubBroker,
    publisher: "PubSubPublisher",
) -> tuple["PubSubBaseSubscriber", bool]:
    project = broker.config.project_id
    topic = resource_path(project, "topics", publisher.topic)
    for b in self.brokers:
        for s in b.subscribers:
            sub = cast("PubSubBaseSubscriber", s)
            if resource_path(b.config.project_id, "topics", sub.topic) == topic:
                return sub, True

    # Under `with_real` the subscription is created on the service only when the
    # publisher declares its topic: a test never adds resources nobody asked for.
    subscription = PubSub(publisher.topic, declare=publisher.topic_schema.declare)
    sub = cast(
        "PubSubBaseSubscriber", broker.subscriber(subscription, persistent=False)
    )
    return sub, False

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
def __init__(
    self,
    project_id: str = EMPTY,
    *,
    emulator_host: str | None = EMPTY,
    api_endpoint: str | None = None,
    client_options: dict[str, Any] | None = None,
    # broker base args
    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,
    # AsyncAPI args
    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"]] = (),
    # logging args
    logger: Optional["LoggerProto"] = EMPTY,
    log_level: int = logging.INFO,
    # StreamRouter options
    setup_state: bool = True,
    schema_url: str | None = "/asyncapi",
    context: ContextRepo | None = None,
    # FastAPI args
    prefix: str = "",
    tags: list[Union[str, "Enum"]] | None = None,
    dependencies: Sequence["params.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
    ),
) -> None:
    super().__init__(
        project_id,
        emulator_host=emulator_host,
        api_endpoint=api_endpoint,
        client_options=client_options,
        graceful_timeout=graceful_timeout,
        decoder=decoder,
        parser=parser,
        codec=codec,
        middlewares=middlewares,
        ack_policy=ack_policy,
        id_generator=id_generator,
        serializer=serializer,
        schema_url=schema_url,
        setup_state=setup_state,
        context=context,
        logger=logger,
        log_level=log_level,
        security=security,
        protocol=protocol,
        description=description,
        protocol_version=protocol_version,
        specification_tags=specification_tags,
        specification_url=specification_url,
        specification=specification,
        # FastAPI args
        prefix=prefix,
        tags=tags,
        dependencies=dependencies,
        default_response_class=default_response_class,
        responses=responses,
        callbacks=callbacks,
        routes=routes,
        redirect_slashes=redirect_slashes,
        default=default,
        dependency_overrides_provider=dependency_overrides_provider,
        route_class=route_class,
        on_startup=on_startup,
        on_shutdown=on_shutdown,
        deprecated=deprecated,
        include_in_schema=include_in_schema,
        lifespan=lifespan,
        generate_unique_id_function=generate_unique_id_function,
    )

broker_class class-attribute instance-attribute #

broker_class = PubSubBroker

broker instance-attribute #

broker: PubSubBroker

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
@override
def subscriber(
    self,
    subscription: "str | PubSub",
    *,
    topic: "str | PubSubTopic | None" = None,
    flow_control: Optional["FlowControl"] = None,
    # broker arguments
    ack_policy: AckPolicy = EMPTY,
    no_reply: bool = False,
    dependencies: Iterable["params.Depends"] = (),
    parser: Optional["CustomCallable"] = None,
    decoder: Optional["CustomCallable"] = None,
    codec: Optional["CodecProto"] = None,
    max_workers: int = 1,
    persistent: bool = True,
    # AsyncAPI information
    title: str | None = None,
    description: str | None = None,
    include_in_schema: bool = True,
    # FastAPI args
    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":
    return cast(
        "PubSubDefaultSubscriber | PubSubConcurrentSubscriber",
        super().subscriber(
            # The base annotates the name as a string; the broker's registrator it forwards
            # to takes a `PubSub` as well.
            subscription,  # type: ignore[arg-type]
            topic=topic,
            flow_control=flow_control,
            ack_policy=ack_policy,
            no_reply=no_reply,
            dependencies=dependencies,
            parser=parser,
            decoder=decoder,
            codec=codec,
            max_workers=max_workers,
            persistent=persistent,
            title=title,
            description=description,
            include_in_schema=include_in_schema,
            # FastAPI args
            response_model=response_model,
            response_model_include=response_model_include,
            response_model_exclude=response_model_exclude,
            response_model_by_alias=response_model_by_alias,
            response_model_exclude_unset=response_model_exclude_unset,
            response_model_exclude_defaults=response_model_exclude_defaults,
            response_model_exclude_none=response_model_exclude_none,
        ),
    )

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
@override
def publisher(  # type: ignore[override]
    self,
    topic: "str | PubSubTopic",
    *,
    ordering_key: str = "",
    headers: dict[str, str] | None = None,
    persistent: bool = True,
    # AsyncAPI information
    title: str | None = None,
    description: str | None = None,
    schema: Any | None = None,
    include_in_schema: bool = True,
) -> "PubSubPublisher":
    return self.broker.publisher(
        topic,
        ordering_key=ordering_key,
        headers=headers,
        persistent=persistent,
        title=title,
        description=description,
        schema=schema,
        include_in_schema=include_in_schema,
    )

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
def __init__(
    self,
    *,
    tracer_provider: TracerProvider | None = None,
    meter_provider: MeterProvider | None = None,
    meter: Meter | None = None,
    include_messages_counters: bool = True,
) -> None:
    super().__init__(
        settings_provider_factory=lambda _: PubSubTelemetrySettingsProvider(),
        tracer_provider=tracer_provider,
        meter_provider=meter_provider,
        meter=meter,
        include_messages_counters=include_messages_counters,
    )

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
def __init__(
    self,
    *,
    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,
) -> None:
    super().__init__(
        settings_provider_factory=lambda _: PubSubMetricsSettingsProvider(),
        registry=registry,
        app_name=app_name,
        metrics_prefix=metrics_prefix,
        received_messages_size_buckets=received_messages_size_buckets,
        custom_labels=custom_labels,
    )