Skip to content

API reference#

Brokers#

faststream_sqs_sns.SqsBroker #

SqsBroker(
    *,
    region: str | None = None,
    endpoint_url: str | None = None,
    account_id: str | None = None,
    connect_timeout: float = 5.0,
    read_timeout: float = 30.0,
    max_connections: int | None = None,
    graceful_timeout: float | None = 25.0,
    decoder: Optional[CustomCallable] = None,
    parser: Optional[CustomCallable] = None,
    codec: Optional[CodecProto] = None,
    dependencies: Sequence[Dependant] = (),
    middlewares: Sequence[BrokerMiddleware[Any, Any]] = (),
    routers: Iterable[SqsRegistrator] = (),
    ack_policy: AckPolicy = EMPTY,
    id_generator: IdGenerator = gen_cor_id,
    specification_url: str | None = None,
    protocol: str | None = None,
    protocol_version: str | None = None,
    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: SqsRegistrator, BrokerUsecase[Any, Transport, SqsBrokerConfig]

The Amazon SQS broker with SNS publishing, whatever the backend.

Construct CapoSqsBroker or AiobotocoreSqsBroker; this class holds what they share and is exported for annotations and isinstance checks. The constructor only records the configuration; connect() (or start()) builds the clients.

PARAMETER DESCRIPTION
region

the AWS region; the backend reads AWS_REGION, AWS_DEFAULT_REGION or the profile when omitted.

TYPE: str | None DEFAULT: None

endpoint_url

one endpoint for SQS and SNS, such as LocalStack or a VPC endpoint.

TYPE: str | None DEFAULT: None

account_id

the account a bare topic name belongs to; it builds the topic ARN without listing topics.

TYPE: str | None DEFAULT: None

connect_timeout

seconds to open a connection.

TYPE: float DEFAULT: 5.0

read_timeout

seconds to wait for a response; it must exceed every subscriber's wait_time by 5 seconds.

TYPE: float DEFAULT: 30.0

max_connections

connections per host of the SQS client; one per poll loop plus 10 when omitted.

TYPE: int | None DEFAULT: None

graceful_timeout

seconds stop() waits for receives in flight and running handlers; the default lets a 20 second long poll finish.

TYPE: float | None DEFAULT: 25.0

security

an AwsSecurity with a static key pair; the backend's default credential chain when omitted.

TYPE: Optional[BaseSecurity] DEFAULT: None

Source code in faststream_sqs_sns/broker/core.py
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def __init__(
    self,
    *,
    region: str | None = None,
    endpoint_url: str | None = None,
    account_id: str | None = None,
    connect_timeout: float = 5.0,
    read_timeout: float = 30.0,
    max_connections: int | None = None,
    graceful_timeout: float | None = 25.0,
    decoder: Optional["CustomCallable"] = None,
    parser: Optional["CustomCallable"] = None,
    codec: Optional["CodecProto"] = None,
    dependencies: Sequence["Dependant"] = (),
    middlewares: Sequence["BrokerMiddleware[Any, Any]"] = (),
    routers: Iterable[SqsRegistrator] = (),
    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 = None,
    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 type(self) is SqsBroker:
        msg = (
            "SqsBroker has no backend: construct CapoSqsBroker (extra `capo`) or "
            "AiobotocoreSqsBroker (extra `aiobotocore`)"
        )
        raise TypeError(msg)

    self._settings = ConnectionSettings(
        region=region,
        endpoint_url=endpoint_url,
        credentials=parse_security(security),
        connect_timeout=connect_timeout,
        read_timeout=read_timeout,
    )
    self._max_connections = max_connections

    if specification_url is None:
        specification_url = endpoint_url or (
            f"https://sqs.{region}.amazonaws.com"
            if region
            else "https://sqs.amazonaws.com"
        )

    super().__init__(
        routers=routers,
        config=SqsBrokerConfig(
            account_id=account_id,
            producer=SqsProducer(parser=parser, decoder=decoder),
            broker_middlewares=middlewares,
            broker_parser=parser,
            broker_decoder=decoder,
            broker_codec=codec,
            logger=make_sqs_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 "sqs",
            protocol_version=protocol_version,
            tags=tags,
            security=security,
        ),
    )

declare_queue async #

declare_queue(queue: str | SqsQueue) -> str

Create a queue (and its dead-letter queue) unless it exists.

RETURNS DESCRIPTION
str

The queue URL.

Source code in faststream_sqs_sns/broker/core.py
279
280
281
282
283
284
285
286
async def declare_queue(self, queue: str | SqsQueue) -> str:
    """Create a queue (and its dead-letter queue) unless it exists.

    Returns:
        The queue URL.
    """
    queue_ = queue if isinstance(queue, SqsQueue) else SqsQueue(queue)
    return await declare_queue(self.config.transport, queue_)

declare_topic async #

declare_topic(topic: str | SnsTopic) -> str

Create a topic unless it exists.

RETURNS DESCRIPTION
str

The topic ARN.

Source code in faststream_sqs_sns/broker/core.py
288
289
290
291
292
293
294
295
async def declare_topic(self, topic: str | SnsTopic) -> str:
    """Create a topic unless it exists.

    Returns:
        The topic ARN.
    """
    topic_ = topic if isinstance(topic, SnsTopic) else SnsTopic(topic)
    return await declare_topic(self.config.transport, topic_)

publish async #

publish(
    message: SendableMessage = None,
    destination: str | SqsQueue | SnsTopic = "",
    *,
    headers: dict[str, Any] | None = None,
    correlation_id: str | None = None,
    reply_to: str = "",
    message_group_id: str | None = None,
    deduplication_id: str | None = None,
    delay: int = 0,
    timeout: float | None = None,
) -> str

Send a message to a queue or publish it to a topic.

PARAMETER DESCRIPTION
message

the message body.

TYPE: SendableMessage DEFAULT: None

destination

a queue (name, URL, ARN or SqsQueue) or a topic (SnsTopic or a topic ARN).

TYPE: str | SqsQueue | SnsTopic DEFAULT: ''

headers

message attributes: str, bytes, int or float values.

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

correlation_id

the correlation id; generated when omitted.

TYPE: str | None DEFAULT: None

reply_to

the queue (name or URL) or topic ARN a consumer replies to.

TYPE: str DEFAULT: ''

message_group_id

the FIFO message group; required by a FIFO queue or topic.

TYPE: str | None DEFAULT: None

deduplication_id

the FIFO deduplication id; required unless the queue or topic deduplicates by content.

TYPE: str | None DEFAULT: None

delay

seconds before the message becomes visible, 0 to 900; standard queues only.

TYPE: int DEFAULT: 0

timeout

seconds the call may take.

TYPE: float | None DEFAULT: None

RETURNS DESCRIPTION
str

The message id the service assigned.

Source code in faststream_sqs_sns/broker/core.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
@override
async def publish(
    self,
    message: "SendableMessage" = None,
    destination: "str | SqsQueue | SnsTopic" = "",
    *,
    headers: dict[str, Any] | None = None,
    correlation_id: str | None = None,
    reply_to: str = "",
    message_group_id: str | None = None,
    deduplication_id: str | None = None,
    delay: int = 0,
    timeout: float | None = None,
) -> str:
    """Send a message to a queue or publish it to a topic.

    Args:
        message: the message body.
        destination: a queue (name, URL, ARN or ``SqsQueue``) or a topic (``SnsTopic``
            or a topic ARN).
        headers: message attributes: ``str``, ``bytes``, ``int`` or ``float`` values.
        correlation_id: the correlation id; generated when omitted.
        reply_to: the queue (name or URL) or topic ARN a consumer replies to.
        message_group_id: the FIFO message group; required by a FIFO queue or topic.
        deduplication_id: the FIFO deduplication id; required unless the queue or topic
            deduplicates by content.
        delay: seconds before the message becomes visible, 0 to 900; standard queues
            only.
        timeout: seconds the call may take.

    Returns:
        The message id the service assigned.
    """
    cmd = SqsPublishCommand(
        message,
        destination=destination or None,
        headers=headers,
        correlation_id=correlation_id or self.config.id_generator(),
        reply_to=reply_to,
        message_group_id=message_group_id,
        deduplication_id=deduplication_id,
        delay=delay,
        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,
    destination: str | SqsQueue | SnsTopic,
    headers: dict[str, Any] | None = None,
    correlation_id: str | None = None,
    reply_to: str = "",
    message_group_id: str | None = None,
    deduplication_id: str | None = None,
    delay: int = 0,
    timeout: float | None = None,
) -> list[str]

Publish several messages, 10 per call, the calls concurrently.

RETURNS DESCRIPTION
list[str]

The message ids, in the order of the messages.

RAISES DESCRIPTION
BatchPublishError

some messages were not sent; it lists which, after every call is done.

Source code in faststream_sqs_sns/broker/core.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
async def publish_batch(  # type: ignore[override]
    self,
    *messages: "SendableMessage",
    destination: "str | SqsQueue | SnsTopic",
    headers: dict[str, Any] | None = None,
    correlation_id: str | None = None,
    reply_to: str = "",
    message_group_id: str | None = None,
    deduplication_id: str | None = None,
    delay: int = 0,
    timeout: float | None = None,
) -> list[str]:
    """Publish several messages, 10 per call, the calls concurrently.

    Returns:
        The message ids, in the order of the messages.

    Raises:
        BatchPublishError: some messages were not sent; it lists which, after every call
            is done.
    """
    cmd = SqsPublishCommand(
        *messages,
        destination=destination,
        headers=headers,
        correlation_id=correlation_id or self.config.id_generator(),
        reply_to=reply_to,
        message_group_id=message_group_id,
        deduplication_id=deduplication_id,
        delay=delay,
        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,
    destination: str | SqsQueue | SnsTopic = "",
    *,
    correlation_id: str | None = None,
    timeout: float | None = None,
) -> Any

Not available on SQS; raises FeatureNotSupportedException.

A request needs a reply queue per caller. Publish with reply_to naming a queue your service consumes, and consume the reply there.

Source code in faststream_sqs_sns/broker/core.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
@override
async def request(  # type: ignore[override]
    self,
    message: "SendableMessage" = None,
    destination: "str | SqsQueue | SnsTopic" = "",
    *,
    correlation_id: str | None = None,
    timeout: float | None = None,
) -> Any:
    """Not available on SQS; raises ``FeatureNotSupportedException``.

    A request needs a reply queue per caller. Publish with ``reply_to`` naming a queue
    your service consumes, and consume the reply there.
    """
    cmd = SqsPublishCommand(
        message,
        destination=destination or None,
        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_sqs_sns/broker/core.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
@override
async def ping(self, timeout: float | None = None) -> bool:
    if self._connection is None:
        return False
    transport: Transport = self._connection
    with anyio.move_on_after(timeout or 5.0):
        try:
            await transport.get_queue_url(PING_QUEUE)
        except ServiceUnavailableError:
            return False
        except SqsError:
            # the service answered: a missing queue or a denied call proves it is there
            return True
        return True
    return False

faststream_sqs_sns.CapoSqsBroker #

CapoSqsBroker(
    *,
    credentials_provider: Any = None,
    retry_mode: str | None = None,
    retry_max_attempts: int | None = None,
    **kwargs: Unpack[SqsBrokerOptions],
)

Bases: SqsBroker

The SQS broker over capo-sqs and capo-sns (extra capo).

It takes every argument of SqsBroker plus capo's own.

PARAMETER DESCRIPTION
credentials_provider

a capo CredentialsProvider given to both clients; it wins over security. capo's default chain (environment, assume-role, web identity, SSO, profile, process, ECS, EC2 metadata) when neither is given.

TYPE: Any DEFAULT: None

retry_mode

capo's retry mode for both clients.

TYPE: str | None DEFAULT: None

retry_max_attempts

capo's attempts per call for both clients.

TYPE: int | None DEFAULT: None

Source code in faststream_sqs_sns/broker/capo.py
29
30
31
32
33
34
35
36
37
38
39
40
def __init__(
    self,
    *,
    credentials_provider: Any = None,
    retry_mode: str | None = None,
    retry_max_attempts: int | None = None,
    **kwargs: Unpack[SqsBrokerOptions],
) -> None:
    self._credentials_provider = credentials_provider
    self._retry_mode = retry_mode
    self._retry_max_attempts = retry_max_attempts
    super().__init__(**kwargs)

faststream_sqs_sns.AiobotocoreSqsBroker #

AiobotocoreSqsBroker(
    *,
    session: AioSession | None = None,
    config: Config | None = None,
    **kwargs: Unpack[SqsBrokerOptions],
)

Bases: SqsBroker

The SQS broker over aiobotocore (extra aiobotocore).

It takes every argument of SqsBroker plus aiobotocore's own.

PARAMETER DESCRIPTION
session

an AioSession for profiles and custom credential resolvers; aiobotocore.session.get_session() when omitted.

TYPE: AioSession | None DEFAULT: None

config

a botocore.config.Config merged over the broker's own (timeouts and pool size).

TYPE: Config | None DEFAULT: None

Source code in faststream_sqs_sns/broker/aiobotocore.py
31
32
33
34
35
36
37
38
39
40
def __init__(
    self,
    *,
    session: "AioSession | None" = None,
    config: "Config | None" = None,
    **kwargs: Unpack[SqsBrokerOptions],
) -> None:
    self._session = session
    self._botocore_config = config
    super().__init__(**kwargs)

Resources#

faststream_sqs_sns.SqsQueue dataclass #

SqsQueue(
    name: str,
    *,
    declare: bool = False,
    fifo: bool | None = None,
    visibility_timeout: int | None = None,
    wait_time: int = MAX_WAIT_TIME,
    max_messages: int = MAX_BATCH_ENTRIES,
    redrive: RedrivePolicy | None = None,
    attributes: Mapping[str, str] = dict(),
)

An SQS queue.

ATTRIBUTE DESCRIPTION
name

a queue name, a queue URL (http:// or https://) or a queue ARN.

TYPE: str

declare

create the queue at start when it does not exist.

TYPE: bool

fifo

whether the queue is FIFO; None infers it from the .fifo suffix. After construction it holds the resolved value.

TYPE: bool | None

visibility_timeout

seconds, 0 to 43200; None uses the queue's own value.

TYPE: int | None

wait_time

long-poll seconds of one receive, 0 to 20.

TYPE: int

max_messages

messages of one receive, 1 to 10.

TYPE: int

redrive

the dead-letter policy applied on declaration.

TYPE: RedrivePolicy | None

attributes

queue attributes in the service's spelling, applied on declaration; the typed fields win over the same key.

TYPE: Mapping[str, str]

RAISES DESCRIPTION
SetupError

a value is out of range, fifo disagrees with the name or an ARN is malformed.

name instance-attribute #

name: str

declare class-attribute instance-attribute #

declare: bool = False

fifo class-attribute instance-attribute #

fifo: bool | None = None

visibility_timeout class-attribute instance-attribute #

visibility_timeout: int | None = None

wait_time class-attribute instance-attribute #

wait_time: int = limits.MAX_WAIT_TIME

max_messages class-attribute instance-attribute #

max_messages: int = limits.MAX_BATCH_ENTRIES

redrive class-attribute instance-attribute #

redrive: RedrivePolicy | None = None

attributes class-attribute instance-attribute #

attributes: Mapping[str, str] = field(
    default_factory=dict, hash=False
)

is_url property #

is_url: bool

Whether the name is a queue URL.

is_arn property #

is_arn: bool

Whether the name is a queue ARN.

queue_name property #

queue_name: str

The bare queue name: the last path segment of a URL, the name part of an ARN.

account_id property #

account_id: str | None

The owner account an ARN or a URL path (/<account>/<name>) names.

content_based_deduplication property #

content_based_deduplication: bool

Whether the declaration enables content-based deduplication.

with_prefix #

with_prefix(prefix: str) -> SqsQueue

The queue with a router prefix; a URL or an ARN is returned as is.

Source code in faststream_sqs_sns/schemas.py
216
217
218
219
220
def with_prefix(self, prefix: str) -> "SqsQueue":
    """The queue with a router prefix; a URL or an ARN is returned as is."""
    if not prefix or self.is_url or self.is_arn:
        return self
    return replace(self, name=prefix + self.name)

declare_attributes #

declare_attributes(
    dead_letter_arn: str | None = None,
) -> dict[str, str]

The attributes CreateQueue takes: the user's, then the typed fields.

RAISES DESCRIPTION
ValueError

redrive is set and dead_letter_arn is missing.

Source code in faststream_sqs_sns/schemas.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def declare_attributes(self, dead_letter_arn: str | None = None) -> dict[str, str]:
    """The attributes ``CreateQueue`` takes: the user's, then the typed fields.

    Raises:
        ValueError: ``redrive`` is set and ``dead_letter_arn`` is missing.
    """
    attributes = dict(self.attributes)
    if self.fifo:
        attributes["FifoQueue"] = "true"
    if self.visibility_timeout is not None:
        attributes["VisibilityTimeout"] = str(self.visibility_timeout)
    attributes["ReceiveMessageWaitTimeSeconds"] = str(self.wait_time)
    if self.redrive is not None:
        if dead_letter_arn is None:
            msg = "dead_letter_arn is required when the queue has a redrive policy"
            raise ValueError(msg)
        attributes["RedrivePolicy"] = json_dumps({
            "deadLetterTargetArn": dead_letter_arn,
            "maxReceiveCount": self.redrive.max_receive_count,
        }).decode()
    return attributes

faststream_sqs_sns.SnsTopic dataclass #

SnsTopic(
    name: str,
    *,
    declare: bool = False,
    fifo: bool | None = None,
    attributes: Mapping[str, str] = dict(),
)

An SNS topic.

ATTRIBUTE DESCRIPTION
name

a topic name or a topic ARN.

TYPE: str

declare

create the topic at start when it does not exist.

TYPE: bool

fifo

whether the topic is FIFO; None infers it from the .fifo suffix. After construction it holds the resolved value.

TYPE: bool | None

attributes

topic attributes in the service's spelling, applied on declaration.

TYPE: Mapping[str, str]

RAISES DESCRIPTION
SetupError

fifo disagrees with the name or an ARN is malformed.

name instance-attribute #

name: str

declare class-attribute instance-attribute #

declare: bool = False

fifo class-attribute instance-attribute #

fifo: bool | None = None

attributes class-attribute instance-attribute #

attributes: Mapping[str, str] = field(
    default_factory=dict, hash=False
)

is_arn property #

is_arn: bool

Whether the name is a topic ARN.

topic_name property #

topic_name: str

The bare topic name: the name part of an ARN.

content_based_deduplication property #

content_based_deduplication: bool

Whether the declaration enables content-based deduplication.

with_prefix #

with_prefix(prefix: str) -> SnsTopic

The topic with a router prefix; an ARN is returned as is.

Source code in faststream_sqs_sns/schemas.py
293
294
295
296
297
def with_prefix(self, prefix: str) -> "SnsTopic":
    """The topic with a router prefix; an ARN is returned as is."""
    if not prefix or self.is_arn:
        return self
    return replace(self, name=prefix + self.name)

declare_attributes #

declare_attributes() -> dict[str, str]

The attributes CreateTopic takes: the user's, then FifoTopic.

Source code in faststream_sqs_sns/schemas.py
299
300
301
302
303
304
def declare_attributes(self) -> dict[str, str]:
    """The attributes ``CreateTopic`` takes: the user's, then ``FifoTopic``."""
    attributes = dict(self.attributes)
    if self.fifo:
        attributes["FifoTopic"] = "true"
    return attributes

faststream_sqs_sns.RedrivePolicy dataclass #

RedrivePolicy(
    dead_letter_queue: str | SqsQueue,
    max_receive_count: int,
)

Where a queue sends a message that was received too many times.

ATTRIBUTE DESCRIPTION
dead_letter_queue

the dead-letter queue, a name, URL, ARN or a queue schema.

TYPE: str | SqsQueue

max_receive_count

receives after which the message moves, 1 to 1000.

TYPE: int

dead_letter_queue instance-attribute #

dead_letter_queue: str | SqsQueue

max_receive_count instance-attribute #

max_receive_count: int

dead_letter_queue_schema property #

dead_letter_queue_schema: SqsQueue

The dead-letter queue as a schema.

Consuming#

faststream_sqs_sns.FlowControl dataclass #

FlowControl(
    *,
    polls: int = 1,
    max_in_flight: int | None = None,
    settle_wait: float = 0.05,
    max_hold: float = 3600.0,
)

How a subscriber polls, holds and settles messages.

ATTRIBUTE DESCRIPTION
polls

concurrent ReceiveMessage loops.

TYPE: int

max_in_flight

messages received and not settled, at most; None means max_workers + polls * max_messages. A poll asks only for free slots, so a slow handler stops polling instead of letting messages age invisibly.

TYPE: int | None

settle_wait

seconds deletes and visibility changes wait to be sent together.

TYPE: float

max_hold

seconds a message is held at most; past it its visibility is no longer extended and SQS redelivers it. Capped at 43140 seconds, the 12 hours SQS allows a receive, less a minute.

TYPE: float

polls class-attribute instance-attribute #

polls: int = 1

max_in_flight class-attribute instance-attribute #

max_in_flight: int | None = None

settle_wait class-attribute instance-attribute #

settle_wait: float = 0.05

max_hold class-attribute instance-attribute #

max_hold: float = 3600.0

faststream_sqs_sns.SqsMessage module-attribute #

SqsMessage = SM

faststream_sqs_sns.message.SqsBatchMessage #

Bases: StreamMessage[SqsBatchRawMessage]

The messages of one receive in a batch handler; settling settles every one.

receive_counts property #

receive_counts: list[int]

The receive count of each message.

message_group_ids property #

message_group_ids: list[str | None]

The FIFO message group of each message.

queue property #

queue: str

The name of the queue the messages came from.

ack async #

ack() -> None
Source code in faststream_sqs_sns/message.py
157
158
159
160
161
162
@override
async def ack(self) -> None:
    if self.committed is None:
        for m in self.raw_message.messages:
            await m.acker.ack(m)
    await super().ack()

nack async #

nack() -> None
Source code in faststream_sqs_sns/message.py
164
165
166
167
168
169
@override
async def nack(self) -> None:
    if self.committed is None:
        for m in self.raw_message.messages:
            await m.acker.nack(m)
    await super().nack()

reject async #

reject() -> None
Source code in faststream_sqs_sns/message.py
171
172
173
174
175
176
@override
async def reject(self) -> None:
    if self.committed is None:
        for m in self.raw_message.messages:
            await m.acker.reject(m)
    await super().reject()

Publishing#

faststream_sqs_sns.SqsResponse #

SqsResponse(
    body: SendableMessage,
    *,
    headers: dict[str, Any] | None = None,
    correlation_id: str | None = None,
    message_group_id: str | None = None,
    deduplication_id: str | None = None,
    delay: int = 0,
)

Bases: Response

A handler result with SQS publish options.

Return it from a handler to set FIFO fields, a delay or attributes on the reply and on every publisher the handler is decorated with.

Source code in faststream_sqs_sns/response.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def __init__(
    self,
    body: "SendableMessage",
    *,
    headers: dict[str, Any] | None = None,
    correlation_id: str | None = None,
    message_group_id: str | None = None,
    deduplication_id: str | None = None,
    delay: int = 0,
) -> None:
    super().__init__(body=body, headers=headers, correlation_id=correlation_id)
    self.message_group_id = message_group_id
    self.deduplication_id = deduplication_id
    self.delay = delay

message_group_id instance-attribute #

message_group_id = message_group_id

deduplication_id instance-attribute #

deduplication_id = deduplication_id

delay instance-attribute #

delay = delay

as_publish_command #

as_publish_command() -> SqsPublishCommand
Source code in faststream_sqs_sns/response.py
55
56
57
58
59
60
61
62
63
64
65
@override
def as_publish_command(self) -> "SqsPublishCommand":
    return SqsPublishCommand(
        self.body,
        headers=self.headers,
        correlation_id=self.correlation_id,
        message_group_id=self.message_group_id,
        deduplication_id=self.deduplication_id,
        delay=self.delay,
        _publish_type=PublishType.PUBLISH,
    )

Routers#

faststream_sqs_sns.SqsRouter #

SqsRouter(
    prefix: str = "",
    handlers: Iterable[SqsRoute] = (),
    *,
    dependencies: Sequence[Dependant] = (),
    middlewares: Sequence[BrokerMiddleware[Any, Any]] = (),
    routers: Iterable[SqsRegistrator] = (),
    parser: Optional[CustomCallable] = None,
    decoder: Optional[CustomCallable] = None,
    include_in_schema: bool | None = None,
    ack_policy: AckPolicy = EMPTY,
)

Bases: SqsRegistrator, BrokerRouter[Any, SqsBrokerConfig]

A group of subscribers and publishers to include into an SQS broker.

prefix is prepended to the queue and topic names it declares; URLs and ARNs are kept as they are.

Source code in faststream_sqs_sns/broker/router.py
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
def __init__(
    self,
    prefix: str = "",
    handlers: Iterable[SqsRoute] = (),
    *,
    dependencies: Sequence["Dependant"] = (),
    middlewares: Sequence["BrokerMiddleware[Any, Any]"] = (),
    routers: Iterable[SqsRegistrator] = (),
    parser: Optional["CustomCallable"] = None,
    decoder: Optional["CustomCallable"] = None,
    include_in_schema: bool | None = None,
    ack_policy: AckPolicy = EMPTY,
) -> None:
    super().__init__(
        handlers=handlers,
        config=SqsBrokerConfig(
            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_sqs_sns.SqsRoute #

SqsRoute(
    call: Callable[..., SendableMessage]
    | Callable[..., Awaitable[SendableMessage]],
    queue: str | SqsQueue,
    *,
    topic: str | SnsTopic | None = None,
    batch: bool = False,
    publishers: Iterable[SqsPublisher] = (),
    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 SqsRegistrator.subscriber.

Source code in faststream_sqs_sns/broker/router.py
56
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
96
def __init__(
    self,
    call: Callable[..., "SendableMessage"]
    | Callable[..., Awaitable["SendableMessage"]],
    queue: "str | SqsQueue",
    *,
    topic: "str | SnsTopic | None" = None,
    batch: bool = False,
    publishers: Iterable[SqsPublisher] = (),
    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,
        queue,
        publishers=publishers,
        batch=batch,
        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_sqs_sns.SqsPublisher #

SqsPublisher(
    destination: str | SqsQueue | SnsTopic,
    *,
    message_group_id: str | None = None,
    headers: dict[str, Any] | 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 SqsRegistrator.publisher.

Source code in faststream_sqs_sns/broker/router.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def __init__(
    self,
    destination: "str | SqsQueue | SnsTopic",
    *,
    message_group_id: str | None = None,
    headers: dict[str, Any] | 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__(
        destination,
        message_group_id=message_group_id,
        headers=headers,
        persistent=persistent,
        title=title,
        description=description,
        schema=schema,
        include_in_schema=include_in_schema,
    )

Security#

faststream_sqs_sns.AwsSecurity #

AwsSecurity(
    access_key_id: str,
    secret_access_key: str,
    session_token: str | None = None,
)

Bases: BaseSecurity

A static AWS access key pair the broker signs its requests with.

Without a security object the backend resolves credentials on its own (environment, shared config, instance or container role).

Examples:

>>> def from_keys() -> CapoSqsBroker:
...     security = AwsSecurity("AKIA...", "secret", session_token="token")
...     return CapoSqsBroker(region="eu-west-1", security=security)
Source code in faststream_sqs_sns/security.py
25
26
27
28
29
30
31
32
33
34
def __init__(
    self,
    access_key_id: str,
    secret_access_key: str,
    session_token: str | None = None,
) -> None:
    super().__init__(use_ssl=True)
    self.access_key_id = access_key_id
    self.secret_access_key = secret_access_key
    self.session_token = session_token

access_key_id instance-attribute #

access_key_id = access_key_id

secret_access_key instance-attribute #

secret_access_key = secret_access_key

session_token instance-attribute #

session_token = session_token

get_requirement #

get_requirement() -> list[dict[str, Any]]
Source code in faststream_sqs_sns/security.py
36
37
38
@override
def get_requirement(self) -> list[dict[str, Any]]:
    return [{"aws": []}]

get_schema #

get_schema() -> dict[str, dict[str, str]]
Source code in faststream_sqs_sns/security.py
40
41
42
43
44
45
46
47
@override
def get_schema(self) -> dict[str, dict[str, str]]:
    return {
        "aws": {
            "type": "userPassword",
            "description": "AWS access key pair, requests signed with Signature Version 4",
        }
    }

Exceptions#

faststream_sqs_sns.exceptions #

The errors the broker raises, whatever the backend.

Each backend's exceptions are mapped by class into this set, so user code catches the same classes with capo and with aiobotocore. The backend's exception is kept as __cause__.

SqsError #

SqsError(
    message: str = "", *, retryable: bool | None = None
)

Bases: Exception

The base of every SQS and SNS error the broker raises.

ATTRIBUTE DESCRIPTION
retryable

whether the same call may succeed when repeated later.

TYPE: bool

Source code in faststream_sqs_sns/exceptions.py
32
33
34
35
def __init__(self, message: str = "", *, retryable: bool | None = None) -> None:
    super().__init__(message)
    if retryable is not None:
        self.retryable = retryable

retryable class-attribute instance-attribute #

retryable: bool = False

QueueNotFoundError #

QueueNotFoundError(
    message: str = "", *, retryable: bool | None = None
)

Bases: SqsError

The queue does not exist, or the caller may not see it.

Source code in faststream_sqs_sns/exceptions.py
32
33
34
35
def __init__(self, message: str = "", *, retryable: bool | None = None) -> None:
    super().__init__(message)
    if retryable is not None:
        self.retryable = retryable

TopicNotFoundError #

TopicNotFoundError(
    message: str = "", *, retryable: bool | None = None
)

Bases: SqsError

The topic does not exist, or the caller may not see it.

Source code in faststream_sqs_sns/exceptions.py
32
33
34
35
def __init__(self, message: str = "", *, retryable: bool | None = None) -> None:
    super().__init__(message)
    if retryable is not None:
        self.retryable = retryable

ThrottledError #

ThrottledError(
    message: str = "", *, retryable: bool | None = None
)

Bases: SqsError

The service throttled the call (request rate or KMS).

Source code in faststream_sqs_sns/exceptions.py
32
33
34
35
def __init__(self, message: str = "", *, retryable: bool | None = None) -> None:
    super().__init__(message)
    if retryable is not None:
        self.retryable = retryable

retryable class-attribute instance-attribute #

retryable = True

InvalidReceiptError #

InvalidReceiptError(
    message: str = "", *, retryable: bool | None = None
)

Bases: SqsError

A receipt handle is invalid or its message is no longer in flight.

Source code in faststream_sqs_sns/exceptions.py
32
33
34
35
def __init__(self, message: str = "", *, retryable: bool | None = None) -> None:
    super().__init__(message)
    if retryable is not None:
        self.retryable = retryable

ServiceUnavailableError #

ServiceUnavailableError(
    message: str = "", *, retryable: bool | None = None
)

Bases: SqsError

The service could not be reached: a connection failure or a timeout.

Source code in faststream_sqs_sns/exceptions.py
32
33
34
35
def __init__(self, message: str = "", *, retryable: bool | None = None) -> None:
    super().__init__(message)
    if retryable is not None:
        self.retryable = retryable

retryable class-attribute instance-attribute #

retryable = True

SqsServiceError #

SqsServiceError(
    message: str = "", *, code: str, retryable: bool = False
)

Bases: SqsError

Any other error the service answered with.

ATTRIBUTE DESCRIPTION
code

the service's error code, such as "AccessDenied" or "QueueNameExists".

Source code in faststream_sqs_sns/exceptions.py
69
70
71
def __init__(self, message: str = "", *, code: str, retryable: bool = False) -> None:
    super().__init__(message, retryable=retryable)
    self.code = code

code instance-attribute #

code = code

BatchFailure dataclass #

BatchFailure(id: str, code: str, message: str)

One entry a batch call did not take.

ATTRIBUTE DESCRIPTION
id

the entry id; for publish_batch the index of the message in the call.

TYPE: str

code

the service's error code for the entry.

TYPE: str

message

the service's text for the entry.

TYPE: str

id instance-attribute #

id: str

code instance-attribute #

code: str

message instance-attribute #

message: str

BatchPublishError #

BatchPublishError(
    message_ids: Sequence[str | None],
    failures: Sequence[BatchFailure],
)

Bases: SqsError

Some messages of a publish_batch were not sent.

ATTRIBUTE DESCRIPTION
message_ids

the id of each sent message and None for each failed one, in the order of the call.

failures

the entries the service refused.

Source code in faststream_sqs_sns/exceptions.py
 98
 99
100
101
102
103
104
105
106
107
108
def __init__(
    self,
    message_ids: Sequence[str | None],
    failures: Sequence[BatchFailure],
) -> None:
    detail = ", ".join(f"#{f.id} {f.code}" for f in failures)
    super().__init__(
        f"{len(failures)} of {len(message_ids)} messages failed: {detail}"
    )
    self.message_ids = list(message_ids)
    self.failures = list(failures)

message_ids instance-attribute #

message_ids = list(message_ids)

failures instance-attribute #

failures = list(failures)

Testing#

faststream_sqs_sns.testing.TestSqsBroker #

TestSqsBroker(
    broker: SqsBroker,
    /,
    *,
    with_real: bool = False,
    connect_only: bool | None = None,
)
TestSqsBroker(
    *brokers: SqsBroker,
    with_real: bool = False,
    connect_only: bool | None = None,
)
TestSqsBroker(
    *brokers: SqsBroker,
    with_real: bool = False,
    connect_only: bool | None = None,
)

Bases: TestBroker[SqsBroker, Any]

The broker in process: a publish reaches the subscribers of its queue or topic directly.

It routes the way SQS and SNS do. A queue publish reaches one subscriber of that queue, in turn; a topic publish reaches every queue subscribed to the topic (topic= on a subscriber); a queue read by get_one or iteration keeps what is published until it is read. A publish AWS refuses (sizes, attribute names and count, FIFO fields, delays) raises the same SqsServiceError with AWS's error code. Settlement is recorded on the message; nothing is redelivered.

Examples:

>>> async with TestSqsBroker(broker) as br:
...     await br.publish({"id": 1}, "orders")
...
...     handle.mock.assert_called_once_with({"id": 1})
Source code in faststream_sqs_sns/testing.py
90
91
92
93
94
95
96
97
def __init__(
    self,
    *brokers: SqsBroker,
    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: SqsBroker, publisher: Any
) -> tuple[SqsBaseSubscriber, bool]
Source code in faststream_sqs_sns/testing.py
 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
def create_publisher_fake_subscriber(
    self,
    broker: SqsBroker,
    publisher: Any,
) -> tuple["SqsBaseSubscriber", bool]:
    pub = cast("SqsPublisher", publisher)
    destination = pub.destination
    for b in self.brokers:
        for s in b.subscribers:
            sub = cast("SqsBaseSubscriber", s)
            if _reaches(sub, destination):
                return sub, True

    # Under `with_real` resources are declared only when the publisher declares them: a
    # test never adds resources nobody asked for.
    if isinstance(destination, SnsTopic):
        queue = SqsQueue(
            destination.topic_name,
            declare=destination.declare,
            fifo=destination.fifo,
        )
        fake = broker.subscriber(queue, topic=destination, persistent=False)
    else:
        # the publisher's own declaration: its wait time and attributes hold here too
        fake = broker.subscriber(destination, persistent=False)
    return cast("SqsBaseSubscriber", fake), False

Integrations#

faststream_sqs_sns.fastapi.CapoSqsRouter #

CapoSqsRouter(
    *,
    credentials_provider: Any = None,
    retry_mode: str | None = None,
    retry_max_attempts: int | None = None,
    **kwargs: Unpack[SqsRouterOptions],
)

Bases: SqsRouterBase

FastAPI router over CapoSqsBroker (extra capo).

Takes the arguments of CapoSqsBroker and of fastapi.APIRouter: the broker's dependencies are the FastAPI dependencies here and its tags are specification_tags.

PARAMETER DESCRIPTION
credentials_provider

a capo CredentialsProvider given to both clients.

TYPE: Any DEFAULT: None

retry_mode

capo's retry mode for both clients.

TYPE: str | None DEFAULT: None

retry_max_attempts

capo's attempts per call for both clients.

TYPE: int | None DEFAULT: None

Source code in faststream_sqs_sns/fastapi/capo.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def __init__(
    self,
    *,
    credentials_provider: Any = None,
    retry_mode: str | None = None,
    retry_max_attempts: int | None = None,
    **kwargs: Unpack[SqsRouterOptions],
) -> None:
    super().__init__(
        backend_options={
            "credentials_provider": credentials_provider,
            "retry_mode": retry_mode,
            "retry_max_attempts": retry_max_attempts,
        },
        **kwargs,
    )

broker_class class-attribute instance-attribute #

broker_class = CapoSqsBroker

broker instance-attribute #

broker: CapoSqsBroker

faststream_sqs_sns.fastapi.AiobotocoreSqsRouter #

AiobotocoreSqsRouter(
    *,
    session: AioSession | None = None,
    config: Config | None = None,
    **kwargs: Unpack[SqsRouterOptions],
)

Bases: SqsRouterBase

FastAPI router over AiobotocoreSqsBroker (extra aiobotocore).

Takes the arguments of AiobotocoreSqsBroker and of fastapi.APIRouter: the broker's dependencies are the FastAPI dependencies here and its tags are specification_tags.

PARAMETER DESCRIPTION
session

an AioSession for profiles and custom credential resolvers.

TYPE: AioSession | None DEFAULT: None

config

a botocore.config.Config merged over the broker's own.

TYPE: Config | None DEFAULT: None

Source code in faststream_sqs_sns/fastapi/aiobotocore.py
32
33
34
35
36
37
38
39
40
41
42
def __init__(
    self,
    *,
    session: "AioSession | None" = None,
    config: "Config | None" = None,
    **kwargs: Unpack[SqsRouterOptions],
) -> None:
    super().__init__(
        backend_options={"session": session, "config": config},
        **kwargs,
    )

broker_class class-attribute instance-attribute #

broker_class = AiobotocoreSqsBroker

broker instance-attribute #

faststream_sqs_sns.opentelemetry.SqsTelemetryMiddleware #

SqsTelemetryMiddleware(
    *,
    tracer_provider: TracerProvider | None = None,
    meter_provider: MeterProvider | None = None,
    meter: Meter | None = None,
    include_messages_counters: bool = True,
)

Bases: TelemetryMiddleware[SqsPublishCommand]

Traces and measures SQS and SNS publishes and SQS deliveries with OpenTelemetry.

Source code in faststream_sqs_sns/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 _: SqsTelemetrySettingsProvider(),
        tracer_provider=tracer_provider,
        meter_provider=meter_provider,
        meter=meter,
        include_messages_counters=include_messages_counters,
    )

faststream_sqs_sns.prometheus.SqsPrometheusMiddleware #

SqsPrometheusMiddleware(
    *,
    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[SqsRawMessage | SqsBatchRawMessage, SqsPublishCommand]

Exports Prometheus metrics of SQS and SNS publishes and SQS deliveries.

Source code in faststream_sqs_sns/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 _: SqsMetricsSettingsProvider(),
        registry=registry,
        app_name=app_name,
        metrics_prefix=metrics_prefix,
        received_messages_size_buckets=received_messages_size_buckets,
        custom_labels=custom_labels,
    )