|
| 1 | +import dataclasses |
| 2 | +import datetime |
| 3 | +import logging |
| 4 | +import typing as t |
| 5 | +from http.cookies import SimpleCookie |
| 6 | + |
| 7 | +from flama import Flama, types |
| 8 | +from flama.authentication.types import AccessToken, RefreshToken |
| 9 | +from flama.exceptions import HTTPException |
| 10 | +from flama.http import Request as HTTPRequest |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | +__all__ = ["Endpoint", "Authentication", "Request", "Response", "Error", "TelemetryData"] |
| 15 | + |
| 16 | + |
| 17 | +@dataclasses.dataclass |
| 18 | +class Endpoint: |
| 19 | + path: str |
| 20 | + name: t.Optional[str] |
| 21 | + tags: dict[str, t.Any] |
| 22 | + |
| 23 | + @classmethod |
| 24 | + async def from_scope(cls, *, scope: types.Scope, receive: types.Receive, send: types.Send) -> "Endpoint": |
| 25 | + app: Flama = scope["app"] |
| 26 | + route, _ = app.router.resolve_route(scope) |
| 27 | + |
| 28 | + return cls(path=str(route.path), name=route.name, tags=route.tags) |
| 29 | + |
| 30 | + def to_dict(self) -> dict[str, t.Any]: |
| 31 | + return { |
| 32 | + "path": self.path, |
| 33 | + "name": self.name, |
| 34 | + "tags": self.tags, |
| 35 | + } |
| 36 | + |
| 37 | + |
| 38 | +@dataclasses.dataclass |
| 39 | +class Authentication: |
| 40 | + access: t.Optional[AccessToken] |
| 41 | + refresh: t.Optional[RefreshToken] |
| 42 | + |
| 43 | + @classmethod |
| 44 | + async def from_scope(cls, *, scope: types.Scope, receive: types.Receive, send: types.Send) -> "Authentication": |
| 45 | + app: Flama = scope["app"] |
| 46 | + context = {"scope": scope, "request": HTTPRequest(scope, receive=receive)} |
| 47 | + |
| 48 | + try: |
| 49 | + access = await app.injector.resolve(AccessToken).value(context) |
| 50 | + except Exception: |
| 51 | + access = None |
| 52 | + |
| 53 | + try: |
| 54 | + refresh = await app.injector.resolve(RefreshToken).value(context) |
| 55 | + except Exception: |
| 56 | + refresh = None |
| 57 | + |
| 58 | + return cls(access=access, refresh=refresh) |
| 59 | + |
| 60 | + def to_dict(self) -> dict[str, t.Any]: |
| 61 | + return { |
| 62 | + "access": self.access.to_dict() if self.access else None, |
| 63 | + "refresh": self.refresh.to_dict() if self.refresh else None, |
| 64 | + } |
| 65 | + |
| 66 | + |
| 67 | +@dataclasses.dataclass |
| 68 | +class Request: |
| 69 | + headers: dict[str, t.Any] |
| 70 | + cookies: dict[str, t.Any] |
| 71 | + query_parameters: dict[str, t.Any] |
| 72 | + path_parameters: dict[str, t.Any] |
| 73 | + body: bytes = b"" |
| 74 | + timestamp: datetime.datetime = dataclasses.field( |
| 75 | + init=False, default_factory=lambda: datetime.datetime.now(datetime.timezone.utc) |
| 76 | + ) |
| 77 | + |
| 78 | + @classmethod |
| 79 | + async def from_scope(cls, *, scope: types.Scope, receive: types.Receive, send: types.Send) -> "Request": |
| 80 | + app: Flama = scope["app"] |
| 81 | + context = {"scope": scope, "request": HTTPRequest(scope, receive=receive), "route": app.resolve_route(scope)[0]} |
| 82 | + |
| 83 | + headers = dict(await app.injector.resolve(types.Headers).value(context)) |
| 84 | + cookies = dict(await app.injector.resolve(types.Cookies).value(context)) |
| 85 | + query = dict(await app.injector.resolve(types.QueryParams).value(context)) |
| 86 | + path = dict(await app.injector.resolve(types.PathParams).value(context)) |
| 87 | + |
| 88 | + return cls(headers=headers, cookies=cookies, query_parameters=query, path_parameters=path) |
| 89 | + |
| 90 | + def to_dict(self) -> dict[str, t.Any]: |
| 91 | + return { |
| 92 | + "timestamp": self.timestamp.isoformat(), |
| 93 | + "headers": self.headers, |
| 94 | + "cookies": self.cookies, |
| 95 | + "query_parameters": self.query_parameters, |
| 96 | + "path_parameters": self.path_parameters, |
| 97 | + "body": self.body, |
| 98 | + } |
| 99 | + |
| 100 | + |
| 101 | +@dataclasses.dataclass |
| 102 | +class Response: |
| 103 | + headers: t.Optional[dict[str, t.Any]] |
| 104 | + cookies: t.Optional[dict[str, t.Any]] = dataclasses.field(init=False) |
| 105 | + body: bytes = b"" |
| 106 | + status_code: t.Optional[int] = None |
| 107 | + timestamp: datetime.datetime = dataclasses.field( |
| 108 | + init=False, default_factory=lambda: datetime.datetime.now(datetime.timezone.utc) |
| 109 | + ) |
| 110 | + |
| 111 | + def __post_init__(self): |
| 112 | + if self.headers: |
| 113 | + cookie = SimpleCookie() |
| 114 | + cookie.load(self.headers.get("cookie", "")) |
| 115 | + else: |
| 116 | + cookie = {} |
| 117 | + |
| 118 | + self.cookies = { |
| 119 | + str(name): {**{str(k): str(v) for k, v in morsel.items()}, "value": morsel.value} |
| 120 | + for name, morsel in cookie.items() |
| 121 | + } |
| 122 | + |
| 123 | + def to_dict(self) -> dict[str, t.Any]: |
| 124 | + return { |
| 125 | + "timestamp": self.timestamp.isoformat(), |
| 126 | + "headers": self.headers, |
| 127 | + "cookies": self.cookies, |
| 128 | + "body": self.body, |
| 129 | + "status_code": self.status_code, |
| 130 | + } |
| 131 | + |
| 132 | + |
| 133 | +@dataclasses.dataclass |
| 134 | +class Error: |
| 135 | + detail: str |
| 136 | + status_code: t.Optional[int] = None |
| 137 | + timestamp: datetime.datetime = dataclasses.field( |
| 138 | + init=False, default_factory=lambda: datetime.datetime.now(datetime.timezone.utc) |
| 139 | + ) |
| 140 | + |
| 141 | + @classmethod |
| 142 | + async def from_exception(cls, *, exception: Exception) -> "Error": |
| 143 | + if isinstance(exception, HTTPException): |
| 144 | + return cls(status_code=exception.status_code, detail=str(exception.detail)) |
| 145 | + |
| 146 | + return cls(detail=str(exception)) |
| 147 | + |
| 148 | + def to_dict(self) -> dict[str, t.Any]: |
| 149 | + return { |
| 150 | + "timestamp": self.timestamp.isoformat(), |
| 151 | + "detail": self.detail, |
| 152 | + "status_code": self.status_code, |
| 153 | + } |
| 154 | + |
| 155 | + |
| 156 | +@dataclasses.dataclass |
| 157 | +class TelemetryData: |
| 158 | + type: t.Literal["http", "websocket"] |
| 159 | + endpoint: Endpoint |
| 160 | + authentication: Authentication |
| 161 | + request: Request |
| 162 | + response: t.Optional[Response] = None |
| 163 | + error: t.Optional[Error] = None |
| 164 | + extra: dict[t.Any, t.Any] = dataclasses.field(default_factory=dict) |
| 165 | + |
| 166 | + @classmethod |
| 167 | + async def from_scope(cls, *, scope: types.Scope, receive: types.Receive, send: types.Send) -> "TelemetryData": |
| 168 | + return cls( |
| 169 | + type=scope["type"], |
| 170 | + endpoint=await Endpoint.from_scope(scope=scope, receive=receive, send=send), |
| 171 | + authentication=await Authentication.from_scope(scope=scope, receive=receive, send=send), |
| 172 | + request=await Request.from_scope(scope=scope, receive=receive, send=send), |
| 173 | + ) |
| 174 | + |
| 175 | + def to_dict(self) -> dict[str, t.Any]: |
| 176 | + return { |
| 177 | + "type": self.type, |
| 178 | + "endpoint": self.endpoint.to_dict(), |
| 179 | + "authentication": self.authentication.to_dict(), |
| 180 | + "request": self.request.to_dict(), |
| 181 | + "response": self.response.to_dict() if self.response else None, |
| 182 | + "error": self.error.to_dict() if self.error else None, |
| 183 | + "extra": self.extra, |
| 184 | + } |
0 commit comments