|
| 1 | +from asyncio import iscoroutinefunction |
| 2 | +from functools import wraps |
| 3 | +from typing import List, Dict, Literal, Type, Optional |
| 4 | + |
| 5 | +from pydantic import BaseModel |
| 6 | +import pydantic_asyncapi.v3 as pa |
| 7 | + |
| 8 | + |
| 9 | +_asyncapi_registry: Dict[str, Dict[Literal["receive", "send"], List]] = { |
| 10 | + |
| 11 | +} |
| 12 | + |
| 13 | + |
| 14 | +# asyncapi_registry: Dict[str, Dict[Literal["receive", "send"], List]] = { |
| 15 | +# "chat_channel": { |
| 16 | +# "receive": [BookCreatedV1], |
| 17 | +# "send": [BookUpdatedV1], |
| 18 | +# } |
| 19 | +# } |
| 20 | + |
| 21 | + |
| 22 | +def add_channel_to_asyncapi_schema( |
| 23 | + receive: Optional[List[Type[BaseModel]]] = None, |
| 24 | + send: Optional[List[Type[BaseModel]]] = None, |
| 25 | + channel_name: Optional[str] = None, |
| 26 | +): |
| 27 | + def decorator(func): |
| 28 | + _channel_name = channel_name or func.__name__ |
| 29 | + if _asyncapi_registry.get(_channel_name) is not None: |
| 30 | + raise ValueError(f"The schema already contains a definition for function {_channel_name}. Please rename the function or provide a different channel name.") |
| 31 | + |
| 32 | + _asyncapi_registry[_channel_name] = {} |
| 33 | + if receive: |
| 34 | + _asyncapi_registry[_channel_name]["receive"] = receive |
| 35 | + if send: |
| 36 | + _asyncapi_registry[_channel_name]["send"] = send |
| 37 | + |
| 38 | + @wraps(func) |
| 39 | + def wrapper(*args, **kwargs): |
| 40 | + # You can optionally use decorator_args and decorator_kwargs here if needed |
| 41 | + return func(*args, **kwargs) |
| 42 | + |
| 43 | + @wraps(func) |
| 44 | + async def a_wrapper(*args, **kwargs): |
| 45 | + # You can optionally use decorator_args and decorator_kwargs here if needed |
| 46 | + return await func(*args, **kwargs) |
| 47 | + |
| 48 | + return a_wrapper if iscoroutinefunction(func) else wrapper |
| 49 | + |
| 50 | + return decorator |
| 51 | + |
| 52 | + |
| 53 | +def get_asyncapi_schema(): |
| 54 | + components_schemas = {} |
| 55 | + channels = {} |
| 56 | + operations = {} |
| 57 | + |
| 58 | + for channel, channel_operations in _asyncapi_registry.items(): |
| 59 | + _channel_messages = {} |
| 60 | + for operation, messages in channel_operations.items(): |
| 61 | + _operation_message_refs = [] |
| 62 | + for message in messages: |
| 63 | + # TODO: Check for overlapping model schemas, if they are different log a warning! |
| 64 | + components_schemas[message.__name__] = message.model_json_schema( |
| 65 | + mode="validation" if operation == "receive" else "serialization", |
| 66 | + ref_template="#/components/schemas/{model}" |
| 67 | + ) |
| 68 | + components_schemas.update( |
| 69 | + message.model_json_schema(mode="serialization", ref_template="#/components/schemas/{model}")[ |
| 70 | + "$defs"]) |
| 71 | + _channel_messages[message.__name__] = pa.Message( |
| 72 | + payload=pa.Reference(ref=f"#/components/schemas/{message.__name__}") |
| 73 | + ) |
| 74 | + # Cannot point to the /components path |
| 75 | + _operation_message_refs.append( |
| 76 | + pa.Reference(ref=f"#/channels/{channel}/messages/{message.__name__}")) |
| 77 | + |
| 78 | + # TODO: Define operation names in decorator |
| 79 | + operations[f"{channel}-{operation}"] = pa.Operation( |
| 80 | + action=operation, |
| 81 | + channel=pa.Reference(ref=f"#/channels/{channel}"), |
| 82 | + messages=_operation_message_refs, |
| 83 | + ) |
| 84 | + |
| 85 | + # TODO: Define channel metadata in decorator |
| 86 | + channels[channel] = pa.Channel( |
| 87 | + address=channel, |
| 88 | + description=f"Description for channel {channel}", |
| 89 | + title=f"Title for channel {channel}", |
| 90 | + servers=[pa.Reference(ref="#/servers/chat")], |
| 91 | + messages=_channel_messages, |
| 92 | + ) |
| 93 | + |
| 94 | + # TODO: Implement function to initialize application and servers |
| 95 | + schema = pa.AsyncAPI( |
| 96 | + asyncapi="3.0.0", |
| 97 | + info=pa.Info( |
| 98 | + title="Bookstore API", |
| 99 | + version="1.0.0", |
| 100 | + description="A bookstore asyncapi specification", |
| 101 | + ), |
| 102 | + components=pa.Components( |
| 103 | + schemas=components_schemas, |
| 104 | + ), |
| 105 | + servers={ |
| 106 | + "chat": pa.Server( |
| 107 | + host="localhost", |
| 108 | + protocol="ws", |
| 109 | + ) |
| 110 | + }, |
| 111 | + channels=channels, |
| 112 | + operations=operations, |
| 113 | + ) |
| 114 | + |
| 115 | + return schema |
0 commit comments