Ir para o conteúdo

tempest_fastapi_sdk.asyncapi

Gerar um cliente WebSocket tipado a partir de um documento AsyncAPI 3.0.

« Geração de cliente OpenAPI


generate_stream

generate_stream(
    source: str,
    *,
    out: Path,
    name: str,
    headers: Mapping[str, str] | None = None,
    run_format: bool = True,
) -> StreamGenerationResult

Generate a WebSocket client package from an AsyncAPI document.

Parameters:

Name Type Description Default
source str

http(s):// URL, or a filesystem path.

required
out Path

Directory the package is written to. Created when missing.

required
name str

Base name for the generated client class.

required
headers Mapping[str, str] | None

Extra request headers, for a document behind authentication.

None
run_format bool

Whether to run ruff over the output.

True

Returns:

Name Type Description
StreamGenerationResult StreamGenerationResult

Files written and what they carry.

Raises:

Type Description
SpecError

When the document cannot be loaded, is not AsyncAPI 3.x, does not declare whose point of view its actions record, or declares no frames, or when an emitted module fails :func:~tempest_fastapi_sdk.openapi.source.check_generated_source — nothing is written in that case.

StreamGenerationResult dataclass

StreamGenerationResult(
    written: tuple[Path, ...],
    message_count: int,
    schema_count: int,
    unsupported: tuple[str, ...] = (),
)

What one generation run produced.

Attributes:

Name Type Description
written tuple[Path, ...]

Files written, in write order.

message_count int

Frames the document declared.

schema_count int

Payload classes emitted.

unsupported tuple[str, ...]

Notes collected while parsing.

load_asyncapi_spec

load_asyncapi_spec(
    source: str, *, headers: Mapping[str, str] | None = None, timeout: float = 30.0
) -> dict[str, Any]

Load and validate an AsyncAPI document from a URL or a local path.

Parameters:

Name Type Description Default
source str

http(s):// URL, or a filesystem path.

required
headers Mapping[str, str] | None

Extra request headers, for a document behind authentication.

None
timeout float

Per-request timeout in seconds.

30.0

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The parsed document, with internal $ref

dict[str, Any]

pointers left intact.

Raises:

Type Description
SpecError

When the file does not exist, the document does not parse, the version is not AsyncAPI 3.x, or the document does not declare whose point of view its actions are written from.

check_version

check_version(document: Mapping[str, Any], *, origin: str) -> None

Reject document versions the generator cannot represent.

Parameters:

Name Type Description Default
document Mapping[str, Any]

The parsed document.

required
origin str

URL or path, used in error messages.

required

Raises:

Type Description
SpecError

For a missing asyncapi field, for AsyncAPI 2.x — which nests operations inside channels and spells the directions publish/subscribe, a different document shape rather than a dialect — and for any other major.

check_perspective

check_perspective(document: Mapping[str, Any], *, origin: str) -> None

Reject a document that does not say whose action it records.

Parameters:

Name Type Description Default
document Mapping[str, Any]

The parsed document.

required
origin str

URL or path, used in error messages.

required

Raises:

Type Description
SpecError

When x-tempest-perspective is absent, or is not "server".

AsyncAPI's action is relative to the application that published the document: receive means that application receives. A generated client is the other end, so it inverts every one of them — and a wrong sign is invisible, because the client still compiles and still type-checks. It just sends what it should listen for.

Nothing in the specification records which end wrote the document, so this generator requires the extension rather than assuming the common case. A document without it is a document whose directions cannot be read with confidence, and refusing is cheaper than a silent inversion.

parse_asyncapi

parse_asyncapi(document: Mapping[str, Any], *, client_name: str) -> AsyncApiIR

Parse a loaded AsyncAPI document into the intermediate representation.

Parameters:

Name Type Description Default
document Mapping[str, Any]

The document, as returned by :func:tempest_fastapi_sdk.asyncapi.load_asyncapi_spec.

required
client_name str

Base name for the generated client class.

required

Returns:

Name Type Description
AsyncApiIR AsyncApiIR

Payload schemas, the stream client, cyclic class names

AsyncApiIR

and every note collected.

Raises:

Type Description
SpecError

When the document declares no channel, more than one channel, or no messages. One channel is not a simplification: WebSocket has no virtual channels, and a document with several is describing a transport this emitter does not generate for.

emit_stream

emit_stream(stream: StreamIR, *, schemas_module: str) -> str

Render the generated WebSocket client module.

Parameters:

Name Type Description Default
stream StreamIR

The parsed stream.

required
schemas_module str

Module name to import the payloads from, relative to the generated package.

required

Returns:

Name Type Description
str str

The complete module source, ending in a newline.

Raises:

Type Description
ValueError

When the inbound frames are not all tagged by the same field. Reading them would mean trying each variant in turn and reporting the last failure, which is worse than refusing.

AsyncApiIR dataclass

AsyncApiIR(
    schemas: tuple[SchemaIR, ...],
    stream: StreamIR,
    cyclic: frozenset[str] = frozenset(),
    unsupported: tuple[str, ...] = (),
)

Everything parsed out of one AsyncAPI document.

Attributes:

Name Type Description
schemas tuple[SchemaIR, ...]

Payload classes, ordered so a class appears after the ones it depends on.

stream StreamIR

The generated client.

cyclic frozenset[str]

Classes taking part in a reference cycle.

unsupported tuple[str, ...]

Notes collected while parsing.

StreamIR dataclass

StreamIR(
    class_name: str,
    title: str,
    version: str,
    default_url: str,
    channel: ChannelIR,
    operations: tuple[OperationIR, ...] = (),
    messages: tuple[MessageIR, ...] = (),
)

The generated client class.

Attributes:

Name Type Description
class_name str

Name of the generated class.

title str

info.title from the document.

version str

info.version from the document.

default_url str

ws(s):// URL built from the first server entry, or empty when the document declares none.

channel ChannelIR

The connection.

operations tuple[OperationIR, ...]

Outbound first, then inbound.

messages tuple[MessageIR, ...]

Every frame, in document order.

outbound property

outbound: tuple[MessageIR, ...]

Frames the client sends.

Returns:

Type Description
tuple[MessageIR, ...]

tuple[MessageIR, ...]: The matching messages, in document order.

inbound property

inbound: tuple[MessageIR, ...]

Frames the client receives.

Returns:

Type Description
tuple[MessageIR, ...]

tuple[MessageIR, ...]: The matching messages, in document order.

ChannelIR dataclass

ChannelIR(
    name: str,
    address: str,
    title: str = "",
    description: str = "",
    handshake_headers: tuple[tuple[str, bool], ...] = (),
)

The connection itself.

Attributes:

Name Type Description
name str

Key the channel is registered under.

address str

Path the socket is served at.

title str

One-line description, or empty.

description str

Longer prose, or empty.

handshake_headers tuple[tuple[str, bool], ...]

(name, required) for each header the upgrade declares.

WebSocket has no virtual channels — the specification is explicit that the channel is the connection — so a document describing a socket has exactly one, and the generated client takes one URL.

MessageIR dataclass

MessageIR(
    name: str,
    class_name: str,
    summary: str = "",
    description: str = "",
    content_type: str = "application/json",
    discriminant: tuple[str, str] | None = None,
)

One frame the connection carries.

Attributes:

Name Type Description
name str

Component name in the document.

class_name str

Generated Python class for the payload.

summary str

One-line description, or empty.

description str

Longer prose, or empty.

content_type str

Declared media type of the payload.

discriminant tuple[str, str] | None

(field, value) when the payload carries a single-valued enum that identifies it, which is what a tagged union needs. None when the frame cannot be told apart from its siblings by a field.

OperationIR dataclass

OperationIR(
    name: str,
    direction: Literal["outbound", "inbound"],
    summary: str = "",
    description: str = "",
    messages: tuple[str, ...] = (),
)

A set of frames travelling one way.

Attributes:

Name Type Description
name str

Key the operation is registered under.

direction Literal['outbound', 'inbound']

Which way the frames travel from the generated client's point of view.

summary str

One-line description, or empty.

description str

Longer prose, or empty.

messages tuple[str, ...]

Names of the messages it carries.

The direction is already inverted. The document's action is written from the server's point of view, so receive there — the server receiving — is outbound here.