tachyon-api 1.3.0__cp313-cp313-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tachyon_api/__init__.py +59 -0
- tachyon_api/_server_fast.cp313-win_amd64.pyd +0 -0
- tachyon_api/_server_fast.pyx +102 -0
- tachyon_api/app/_404.py +17 -0
- tachyon_api/app/_405.py +7 -0
- tachyon_api/app/__init__.py +239 -0
- tachyon_api/app/_asgi_entry.py +33 -0
- tachyon_api/app/_asgi_handler.py +14 -0
- tachyon_api/app/_docs_routes.py +43 -0
- tachyon_api/app/_docs_schemas.py +43 -0
- tachyon_api/app/_exception_table.cp313-win_amd64.pyd +0 -0
- tachyon_api/app/_exception_table.py +66 -0
- tachyon_api/app/_exception_table.pyx +74 -0
- tachyon_api/app/_fast_asgi_factory.py +61 -0
- tachyon_api/app/_handler_factory.py +69 -0
- tachyon_api/app/_http_dispatch.py +20 -0
- tachyon_api/app/_mw_stack.py +27 -0
- tachyon_api/app/_registry.py +20 -0
- tachyon_api/app/_route_installer.py +41 -0
- tachyon_api/background.py +36 -0
- tachyon_api/cache.py +275 -0
- tachyon_api/cli/__init__.py +9 -0
- tachyon_api/cli/__main__.py +8 -0
- tachyon_api/cli/commands/__init__.py +5 -0
- tachyon_api/cli/commands/generate.py +211 -0
- tachyon_api/cli/commands/lint.py +186 -0
- tachyon_api/cli/commands/new.py +94 -0
- tachyon_api/cli/commands/openapi.py +128 -0
- tachyon_api/cli/commands/routes.py +70 -0
- tachyon_api/cli/commands/run.py +75 -0
- tachyon_api/cli/commands/skill.py +91 -0
- tachyon_api/cli/main.py +140 -0
- tachyon_api/cli/templates/__init__.py +17 -0
- tachyon_api/cli/templates/ai_skill.py +354 -0
- tachyon_api/cli/templates/project.py +215 -0
- tachyon_api/cli/templates/service.py +381 -0
- tachyon_api/cli/utils.py +39 -0
- tachyon_api/core/__init__.py +13 -0
- tachyon_api/core/lifecycle.py +64 -0
- tachyon_api/core/websocket.py +107 -0
- tachyon_api/di.py +57 -0
- tachyon_api/exceptions.py +18 -0
- tachyon_api/files.py +28 -0
- tachyon_api/middlewares/__init__.py +5 -0
- tachyon_api/middlewares/core.py +22 -0
- tachyon_api/middlewares/cors.py +159 -0
- tachyon_api/middlewares/logger.py +123 -0
- tachyon_api/middlewares/security_headers.py +80 -0
- tachyon_api/models.py +40 -0
- tachyon_api/openapi/__init__.py +28 -0
- tachyon_api/openapi/_config.py +51 -0
- tachyon_api/openapi/_factory.py +56 -0
- tachyon_api/openapi/_format_map.py +12 -0
- tachyon_api/openapi/_generator.py +60 -0
- tachyon_api/openapi/_info.py +52 -0
- tachyon_api/openapi/_param_schemas.py +40 -0
- tachyon_api/openapi/_redoc_html.py +37 -0
- tachyon_api/openapi/_route_builder.py +174 -0
- tachyon_api/openapi/_safe_json.py +15 -0
- tachyon_api/openapi/_scalar_html.py +39 -0
- tachyon_api/openapi/_server.py +16 -0
- tachyon_api/openapi/_struct_schemas.py +81 -0
- tachyon_api/openapi/_swagger_html.py +46 -0
- tachyon_api/params.py +88 -0
- tachyon_api/processing/__init__.py +15 -0
- tachyon_api/processing/_extractors/__init__.py +28 -0
- tachyon_api/processing/_extractors/_base.py +16 -0
- tachyon_api/processing/_extractors/_missing.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/_extractors/_missing.py +16 -0
- tachyon_api/processing/_extractors/_missing.pyx +19 -0
- tachyon_api/processing/_extractors/body.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/_extractors/body.pxd +15 -0
- tachyon_api/processing/_extractors/body.py +61 -0
- tachyon_api/processing/_extractors/body.pyx +60 -0
- tachyon_api/processing/_extractors/body_limit.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/_extractors/body_limit.pxd +10 -0
- tachyon_api/processing/_extractors/body_limit.py +36 -0
- tachyon_api/processing/_extractors/body_limit.pyx +38 -0
- tachyon_api/processing/_extractors/cookie.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/_extractors/cookie.pxd +6 -0
- tachyon_api/processing/_extractors/cookie.py +18 -0
- tachyon_api/processing/_extractors/cookie.pyx +14 -0
- tachyon_api/processing/_extractors/file.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/_extractors/file.pxd +6 -0
- tachyon_api/processing/_extractors/file.py +26 -0
- tachyon_api/processing/_extractors/file.pyx +23 -0
- tachyon_api/processing/_extractors/form.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/_extractors/form.pxd +6 -0
- tachyon_api/processing/_extractors/form.py +17 -0
- tachyon_api/processing/_extractors/form.pyx +14 -0
- tachyon_api/processing/_extractors/header.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/_extractors/header.pxd +12 -0
- tachyon_api/processing/_extractors/header.py +18 -0
- tachyon_api/processing/_extractors/header.pyx +18 -0
- tachyon_api/processing/_extractors/path.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/_extractors/path.pxd +6 -0
- tachyon_api/processing/_extractors/path.py +40 -0
- tachyon_api/processing/_extractors/path.pyx +91 -0
- tachyon_api/processing/_extractors/query.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/_extractors/query.pxd +6 -0
- tachyon_api/processing/_extractors/query.py +26 -0
- tachyon_api/processing/_extractors/query.pyx +80 -0
- tachyon_api/processing/_extractors/query_list.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/_extractors/query_list.pxd +6 -0
- tachyon_api/processing/_extractors/query_list.py +53 -0
- tachyon_api/processing/_extractors/query_list.pyx +54 -0
- tachyon_api/processing/compiler.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/compiler.py +227 -0
- tachyon_api/processing/compiler.pyx +219 -0
- tachyon_api/processing/dependencies/__init__.py +6 -0
- tachyon_api/processing/dependencies/_callable_factory.py +55 -0
- tachyon_api/processing/dependencies/_circular_detector.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/dependencies/_circular_detector.py +23 -0
- tachyon_api/processing/dependencies/_circular_detector.pyx +25 -0
- tachyon_api/processing/dependencies/_class_factory.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/dependencies/_class_factory.py +32 -0
- tachyon_api/processing/dependencies/_class_factory.pyx +35 -0
- tachyon_api/processing/dependencies/_override_lookup.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/dependencies/_override_lookup.py +30 -0
- tachyon_api/processing/dependencies/_override_lookup.pyx +31 -0
- tachyon_api/processing/dependencies/_resolver.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/dependencies/_resolver.py +101 -0
- tachyon_api/processing/dependencies/_resolver.pyx +89 -0
- tachyon_api/processing/dependencies/_scope_cache.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/dependencies/_scope_cache.py +45 -0
- tachyon_api/processing/dependencies/_scope_cache.pyx +36 -0
- tachyon_api/processing/dependencies/_sig_cache.py +20 -0
- tachyon_api/processing/dispatch.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/dispatch.py +87 -0
- tachyon_api/processing/dispatch.pyx +97 -0
- tachyon_api/processing/parameters.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/parameters.py +145 -0
- tachyon_api/processing/parameters.pyx +186 -0
- tachyon_api/processing/response_processor.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/response_processor.py +55 -0
- tachyon_api/processing/response_processor.pyx +46 -0
- tachyon_api/processing/scope.cp313-win_amd64.pyd +0 -0
- tachyon_api/processing/scope.py +100 -0
- tachyon_api/processing/scope.pyx +92 -0
- tachyon_api/responses/__init__.py +44 -0
- tachyon_api/responses/_bytes_response.cp313-win_amd64.pyd +0 -0
- tachyon_api/responses/_bytes_response.py +32 -0
- tachyon_api/responses/_bytes_response.pyx +41 -0
- tachyon_api/responses/_caches.py +29 -0
- tachyon_api/responses/_constants.py +9 -0
- tachyon_api/responses/_error.py +25 -0
- tachyon_api/responses/_internal_error.cp313-win_amd64.pyd +0 -0
- tachyon_api/responses/_internal_error.py +51 -0
- tachyon_api/responses/_internal_error.pyx +53 -0
- tachyon_api/responses/_json_response.cp313-win_amd64.pyd +0 -0
- tachyon_api/responses/_json_response.py +44 -0
- tachyon_api/responses/_json_response.pyx +55 -0
- tachyon_api/responses/_success.py +10 -0
- tachyon_api/responses/_validation.py +33 -0
- tachyon_api/responses/_wire.py +26 -0
- tachyon_api/router.py +82 -0
- tachyon_api/routing/__init__.py +3 -0
- tachyon_api/routing/trie.cp313-win_amd64.pyd +0 -0
- tachyon_api/routing/trie.py +137 -0
- tachyon_api/routing/trie.pyx +134 -0
- tachyon_api/security/__init__.py +21 -0
- tachyon_api/security/_api_key_base.py +30 -0
- tachyon_api/security/_api_key_cookie.py +16 -0
- tachyon_api/security/_api_key_header.py +16 -0
- tachyon_api/security/_api_key_query.py +21 -0
- tachyon_api/security/_basic_credentials.py +11 -0
- tachyon_api/security/_bearer_credentials.py +11 -0
- tachyon_api/security/_bearer_parser.cp313-win_amd64.pyd +0 -0
- tachyon_api/security/_bearer_parser.py +16 -0
- tachyon_api/security/_bearer_parser.pyx +29 -0
- tachyon_api/security/_http_basic.py +50 -0
- tachyon_api/security/_http_bearer.py +29 -0
- tachyon_api/security/_oauth2_bearer.py +32 -0
- tachyon_api/server.py +101 -0
- tachyon_api/testing.py +115 -0
- tachyon_api/utils/__init__.py +15 -0
- tachyon_api/utils/type_converter.py +86 -0
- tachyon_api/utils/type_utils.py +56 -0
- tachyon_api-1.3.0.dist-info/METADATA +463 -0
- tachyon_api-1.3.0.dist-info/RECORD +183 -0
- tachyon_api-1.3.0.dist-info/WHEEL +4 -0
- tachyon_api-1.3.0.dist-info/entry_points.txt +3 -0
- tachyon_api-1.3.0.dist-info/licenses/LICENSE +17 -0
tachyon_api/__init__.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Tachyon Web Framework
|
|
3
|
+
|
|
4
|
+
A lightweight, FastAPI-inspired web framework with built-in dependency injection,
|
|
5
|
+
automatic parameter validation, and high-performance JSON serialization.
|
|
6
|
+
|
|
7
|
+
Copyright (C) 2025 Juan Manuel Panozzo Zenere
|
|
8
|
+
|
|
9
|
+
This program is free software: you can redistribute it and/or modify
|
|
10
|
+
it under the terms of the GNU General Public License as published by
|
|
11
|
+
the Free Software Foundation, either version 3 of the License.
|
|
12
|
+
|
|
13
|
+
For more information, see the documentation and examples.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from .app import Tachyon
|
|
17
|
+
from .models import Struct
|
|
18
|
+
from .params import Query, Body, Path, Header, Cookie, Form, File
|
|
19
|
+
from .files import UploadFile
|
|
20
|
+
from .di import injectable, Depends
|
|
21
|
+
from .exceptions import HTTPException
|
|
22
|
+
from .router import Router
|
|
23
|
+
from .cache import (
|
|
24
|
+
cache,
|
|
25
|
+
CacheConfig,
|
|
26
|
+
create_cache_config,
|
|
27
|
+
set_cache_config,
|
|
28
|
+
get_cache_config,
|
|
29
|
+
InMemoryCacheBackend,
|
|
30
|
+
BaseCacheBackend,
|
|
31
|
+
RedisCacheBackend,
|
|
32
|
+
MemcachedCacheBackend,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"Tachyon",
|
|
37
|
+
"Struct",
|
|
38
|
+
"Query",
|
|
39
|
+
"Body",
|
|
40
|
+
"Path",
|
|
41
|
+
"Header",
|
|
42
|
+
"Cookie",
|
|
43
|
+
"Form",
|
|
44
|
+
"File",
|
|
45
|
+
"UploadFile",
|
|
46
|
+
"injectable",
|
|
47
|
+
"Depends",
|
|
48
|
+
"HTTPException",
|
|
49
|
+
"Router",
|
|
50
|
+
"cache",
|
|
51
|
+
"CacheConfig",
|
|
52
|
+
"create_cache_config",
|
|
53
|
+
"set_cache_config",
|
|
54
|
+
"get_cache_config",
|
|
55
|
+
"InMemoryCacheBackend",
|
|
56
|
+
"BaseCacheBackend",
|
|
57
|
+
"RedisCacheBackend",
|
|
58
|
+
"MemcachedCacheBackend",
|
|
59
|
+
]
|
|
Binary file
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# cython: language_level=3, boundscheck=False, wraparound=False
|
|
2
|
+
"""
|
|
3
|
+
Cython-compiled tachyon_direct_write for F12b.
|
|
4
|
+
|
|
5
|
+
Key optimisations vs the Python version:
|
|
6
|
+
|
|
7
|
+
1. Default-headers cache: uvicorn's default_headers list contains (server, date).
|
|
8
|
+
The Date value changes once per second. We cache the pre-joined bytes and skip
|
|
9
|
+
the loop + b"".join on every request — just a pointer comparison.
|
|
10
|
+
|
|
11
|
+
2. C-typed locals: cdef bytes / cdef object / cdef bint avoid Python name-table
|
|
12
|
+
lookups and let Cython generate direct C variable access.
|
|
13
|
+
|
|
14
|
+
3. Single b"".join for the header block (status + cached_defaults + CL + CT headers),
|
|
15
|
+
then a second transport.write(body) — avoids copying body bytes into the join buffer.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from .responses import (
|
|
19
|
+
_HTTP_CL_PREFIX,
|
|
20
|
+
_HTTP_CRLF,
|
|
21
|
+
_HTTP_CT_JSON_CRLF2,
|
|
22
|
+
_cl_bytes,
|
|
23
|
+
_http_status_line,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
# ── Default-headers cache ─────────────────────────────────────────────────────
|
|
27
|
+
# Updated when the Date header changes (≤ once per second at 50k+ req/s).
|
|
28
|
+
# At module level so it survives across requests on the same worker process.
|
|
29
|
+
|
|
30
|
+
cdef bytes _cached_default_bytes = b""
|
|
31
|
+
cdef bytes _cached_date_value = b""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
cdef bytes _get_default_bytes(list default_headers):
|
|
35
|
+
"""Return pre-joined b'name: value\\r\\n...' for uvicorn default headers."""
|
|
36
|
+
global _cached_default_bytes, _cached_date_value
|
|
37
|
+
|
|
38
|
+
# Find the Date header value — it's usually the second item
|
|
39
|
+
cdef object name, value
|
|
40
|
+
cdef bytes date_val = b""
|
|
41
|
+
for name, value in default_headers:
|
|
42
|
+
if name == b"date":
|
|
43
|
+
date_val = value
|
|
44
|
+
break
|
|
45
|
+
|
|
46
|
+
# Cache hit — same Date value as last time
|
|
47
|
+
if date_val is _cached_date_value or date_val == _cached_date_value:
|
|
48
|
+
return _cached_default_bytes
|
|
49
|
+
|
|
50
|
+
# Cache miss — rebuild (happens at most once per second)
|
|
51
|
+
_cached_date_value = date_val
|
|
52
|
+
cdef list parts = []
|
|
53
|
+
for name, value in default_headers:
|
|
54
|
+
parts.extend([name, b": ", value, b"\r\n"])
|
|
55
|
+
_cached_default_bytes = b"".join(parts)
|
|
56
|
+
return _cached_default_bytes
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ── Main function ─────────────────────────────────────────────────────────────
|
|
60
|
+
|
|
61
|
+
def tachyon_direct_write(cycle, response) -> bool:
|
|
62
|
+
"""
|
|
63
|
+
Write HTTP response directly to transport — bypasses 2× ASGI send() awaits.
|
|
64
|
+
|
|
65
|
+
Builds: STATUS_LINE + cached(default_headers) + content-length + content-type,
|
|
66
|
+
writes the header block + body as two synchronous transport.write() calls,
|
|
67
|
+
then updates the uvicorn cycle state for keep-alive / pipelining.
|
|
68
|
+
|
|
69
|
+
Returns False when flow-controlled so caller falls back to normal send().
|
|
70
|
+
"""
|
|
71
|
+
cdef bint write_paused = cycle.flow.write_paused
|
|
72
|
+
cdef bint disconnected = cycle.disconnected
|
|
73
|
+
|
|
74
|
+
if write_paused or disconnected:
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
cdef object body = response.body
|
|
78
|
+
cdef int status = response.status_code
|
|
79
|
+
cdef bint keep_alive = cycle.keep_alive
|
|
80
|
+
|
|
81
|
+
# Header bytes: STATUS + cached_defaults + CL_PREFIX + cl + CRLF + CT_CRLF2
|
|
82
|
+
cdef bytes status_line = _http_status_line(status)
|
|
83
|
+
cdef bytes default_bytes = _get_default_bytes(cycle.default_headers)
|
|
84
|
+
cdef bytes cl = _cl_bytes(len(body))
|
|
85
|
+
|
|
86
|
+
cdef bytes header_block = (
|
|
87
|
+
status_line + default_bytes
|
|
88
|
+
+ _HTTP_CL_PREFIX + cl + _HTTP_CRLF + _HTTP_CT_JSON_CRLF2
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
cdef object transport = cycle.transport
|
|
92
|
+
transport.write(header_block)
|
|
93
|
+
transport.write(body)
|
|
94
|
+
|
|
95
|
+
# Mirror uvicorn's cycle state update
|
|
96
|
+
cycle.response_started = True
|
|
97
|
+
cycle.response_complete = True
|
|
98
|
+
cycle.message_event.set()
|
|
99
|
+
if not keep_alive:
|
|
100
|
+
transport.close()
|
|
101
|
+
cycle.on_response()
|
|
102
|
+
return True
|
tachyon_api/app/_404.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# HOT PATH — Pre-built 404 ASGI messages.
|
|
2
|
+
# MappingProxyType makes the dicts read-only to defend against non-compliant
|
|
3
|
+
# ASGI servers that might mutate them.
|
|
4
|
+
|
|
5
|
+
import types as _types
|
|
6
|
+
|
|
7
|
+
_404_BODY = b"Not Found"
|
|
8
|
+
_404_HEADERS = [
|
|
9
|
+
(b"content-length", b"9"),
|
|
10
|
+
(b"content-type", b"text/plain; charset=utf-8"),
|
|
11
|
+
]
|
|
12
|
+
_404_START = _types.MappingProxyType(
|
|
13
|
+
{"type": "http.response.start", "status": 404, "headers": _404_HEADERS}
|
|
14
|
+
)
|
|
15
|
+
_404_BODY_MSG = _types.MappingProxyType(
|
|
16
|
+
{"type": "http.response.body", "body": _404_BODY}
|
|
17
|
+
)
|
tachyon_api/app/_405.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# HOT PATH — Pre-built 405 ASGI constants.
|
|
2
|
+
# The Allow header value is computed per-route at trie registration time,
|
|
3
|
+
# so only the body and content-type are static.
|
|
4
|
+
|
|
5
|
+
_405_BODY = b"Method Not Allowed"
|
|
6
|
+
_405_PLAIN_CT = b"text/plain; charset=utf-8"
|
|
7
|
+
_CL_405 = str(len(_405_BODY)).encode()
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Tachyon application facade — composes collaborators, exposes the public API."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from functools import partial
|
|
5
|
+
from typing import Any, Callable, Dict, List, Optional, Type
|
|
6
|
+
|
|
7
|
+
from starlette.applications import Starlette
|
|
8
|
+
|
|
9
|
+
from ..core.lifecycle import LifecycleManager
|
|
10
|
+
from ..core.websocket import WebSocketManager
|
|
11
|
+
from ..middlewares.core import (
|
|
12
|
+
apply_middleware_to_router,
|
|
13
|
+
create_decorated_middleware_class,
|
|
14
|
+
)
|
|
15
|
+
from ..openapi import OpenAPIConfig, OpenAPIGenerator, create_openapi_config
|
|
16
|
+
from ..processing.dependencies import DependencyResolver
|
|
17
|
+
from ..processing.dispatch import TachyonDispatcher
|
|
18
|
+
from ..processing.parameters import ParameterProcessor
|
|
19
|
+
from ..routing.trie import RadixTrie
|
|
20
|
+
|
|
21
|
+
from ._404 import _404_BODY_MSG, _404_START
|
|
22
|
+
from ._405 import _405_BODY, _405_PLAIN_CT, _CL_405
|
|
23
|
+
from ._asgi_entry import ASGIEntry
|
|
24
|
+
from ._asgi_handler import _ASGIHandler
|
|
25
|
+
from ._docs_routes import DocsRoutes
|
|
26
|
+
from ._docs_schemas import CommonSchemas
|
|
27
|
+
from ._exception_table import ExceptionTable
|
|
28
|
+
from ._fast_asgi_factory import FastASGIFactory
|
|
29
|
+
from ._handler_factory import HandlerFactory
|
|
30
|
+
from ._http_dispatch import HTTPDispatcher
|
|
31
|
+
from ._mw_stack import MiddlewareStack
|
|
32
|
+
from ._registry import RouteRegistry
|
|
33
|
+
from ._route_installer import RouteInstaller
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
from ..cache import set_cache_config
|
|
37
|
+
except ImportError: # pragma: no cover
|
|
38
|
+
set_cache_config = None # type: ignore
|
|
39
|
+
|
|
40
|
+
logger = logging.getLogger(__name__)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Tachyon:
|
|
44
|
+
"""Tachyon application — composes the framework's collaborators."""
|
|
45
|
+
|
|
46
|
+
__slots__ = (
|
|
47
|
+
# configuration
|
|
48
|
+
"max_body_size",
|
|
49
|
+
"openapi_config",
|
|
50
|
+
"openapi_generator",
|
|
51
|
+
"cache_config",
|
|
52
|
+
# collaborators (composed)
|
|
53
|
+
"_lifecycle_manager",
|
|
54
|
+
"_router",
|
|
55
|
+
"_trie",
|
|
56
|
+
"_dispatcher",
|
|
57
|
+
"_websocket_manager",
|
|
58
|
+
"_parameter_processor",
|
|
59
|
+
"_dependency_resolver",
|
|
60
|
+
"_registry",
|
|
61
|
+
"_exc_table",
|
|
62
|
+
"_mw_stack",
|
|
63
|
+
"_handler_factory",
|
|
64
|
+
"_fast_asgi_factory",
|
|
65
|
+
"_installer",
|
|
66
|
+
"_docs_routes",
|
|
67
|
+
"_asgi_entry",
|
|
68
|
+
# DI / public state
|
|
69
|
+
"_instances_cache",
|
|
70
|
+
"state",
|
|
71
|
+
"dependency_overrides",
|
|
72
|
+
# lazy HTTP app cache
|
|
73
|
+
"_http_app",
|
|
74
|
+
# HTTP method decorators bound via setattr() in __init__
|
|
75
|
+
"get", "post", "put", "delete", "patch", "options", "head",
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
def __init__(
|
|
79
|
+
self,
|
|
80
|
+
openapi_config: Optional[OpenAPIConfig] = None,
|
|
81
|
+
cache_config: Optional[Any] = None,
|
|
82
|
+
lifespan: Optional[Callable] = None,
|
|
83
|
+
max_body_size: int = 2 * 1024 * 1024,
|
|
84
|
+
):
|
|
85
|
+
self.max_body_size = max_body_size
|
|
86
|
+
self._lifecycle_manager = LifecycleManager(lifespan)
|
|
87
|
+
|
|
88
|
+
# Starlette stays for WebSocket routing and lifespan
|
|
89
|
+
self._router = Starlette(
|
|
90
|
+
lifespan=self._lifecycle_manager.create_combined_lifespan()
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
# Radix trie replaces Starlette's O(N) regex route scan
|
|
94
|
+
self._trie = RadixTrie()
|
|
95
|
+
|
|
96
|
+
# Cython dispatcher reads C-level struct fields per request
|
|
97
|
+
self._dispatcher = TachyonDispatcher(
|
|
98
|
+
trie=self._trie,
|
|
99
|
+
_404_start=_404_START,
|
|
100
|
+
_404_body=_404_BODY_MSG,
|
|
101
|
+
_405_body=_405_BODY,
|
|
102
|
+
_405_ct=_405_PLAIN_CT,
|
|
103
|
+
_405_cl=_CL_405,
|
|
104
|
+
asgi_handler_class=_ASGIHandler,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
# Route HTTP to trie, non-HTTP to Starlette
|
|
108
|
+
_original_router_app = self._router.router.app
|
|
109
|
+
self._router.router.middleware_stack = HTTPDispatcher(
|
|
110
|
+
dispatcher=self._dispatcher,
|
|
111
|
+
fallback=_original_router_app,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# Collaborators
|
|
115
|
+
self._websocket_manager = WebSocketManager(self._router)
|
|
116
|
+
self._parameter_processor = ParameterProcessor(self)
|
|
117
|
+
self._dependency_resolver = DependencyResolver(self)
|
|
118
|
+
|
|
119
|
+
self._registry = RouteRegistry()
|
|
120
|
+
self._exc_table = ExceptionTable()
|
|
121
|
+
self._mw_stack = MiddlewareStack()
|
|
122
|
+
self._handler_factory = HandlerFactory(self)
|
|
123
|
+
self._fast_asgi_factory = FastASGIFactory(self)
|
|
124
|
+
self._installer = RouteInstaller(self)
|
|
125
|
+
self._docs_routes = DocsRoutes(self)
|
|
126
|
+
self._asgi_entry = ASGIEntry(self)
|
|
127
|
+
|
|
128
|
+
# DI / state
|
|
129
|
+
self._instances_cache: Dict[Type, Any] = {}
|
|
130
|
+
self.state = self._router.state
|
|
131
|
+
self.dependency_overrides: Dict[Any, Any] = {}
|
|
132
|
+
|
|
133
|
+
# OpenAPI
|
|
134
|
+
self.openapi_config = openapi_config or create_openapi_config()
|
|
135
|
+
self.openapi_generator = OpenAPIGenerator(self.openapi_config)
|
|
136
|
+
CommonSchemas.register(self.openapi_generator)
|
|
137
|
+
|
|
138
|
+
# Cache configuration (optional)
|
|
139
|
+
self.cache_config = cache_config
|
|
140
|
+
if cache_config is not None and set_cache_config is not None:
|
|
141
|
+
try:
|
|
142
|
+
set_cache_config(cache_config)
|
|
143
|
+
except Exception as exc:
|
|
144
|
+
logger.warning("Failed to apply cache config: %s", exc)
|
|
145
|
+
|
|
146
|
+
# Lazily-built HTTP ASGI app (user middlewares → trie dispatcher)
|
|
147
|
+
self._http_app: Optional[Callable] = None
|
|
148
|
+
|
|
149
|
+
# Bind get/post/put/... decorators
|
|
150
|
+
for method in ("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"):
|
|
151
|
+
setattr(
|
|
152
|
+
self,
|
|
153
|
+
method.lower(),
|
|
154
|
+
partial(self._create_decorator, http_method=method),
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
# ── Public introspection ────────────────────────────────────────────────
|
|
158
|
+
|
|
159
|
+
@property
|
|
160
|
+
def routes(self) -> List[Dict[str, Any]]:
|
|
161
|
+
return self._registry.routes
|
|
162
|
+
|
|
163
|
+
@property
|
|
164
|
+
def middleware_stack(self) -> List[Dict[str, Any]]:
|
|
165
|
+
return self._mw_stack.middlewares
|
|
166
|
+
|
|
167
|
+
def register_instance(self, cls: Type, instance: Any) -> None:
|
|
168
|
+
"""Register a pre-built instance for a class in the DI singleton cache."""
|
|
169
|
+
self._instances_cache[cls] = instance
|
|
170
|
+
|
|
171
|
+
def get_instance(self, cls: Type) -> Optional[Any]:
|
|
172
|
+
return self._instances_cache.get(cls)
|
|
173
|
+
|
|
174
|
+
# ── Decorators ──────────────────────────────────────────────────────────
|
|
175
|
+
|
|
176
|
+
def on_event(self, event_type: str):
|
|
177
|
+
return self._lifecycle_manager.on_event_decorator(event_type)
|
|
178
|
+
|
|
179
|
+
def exception_handler(self, exc_class: Type[Exception]):
|
|
180
|
+
def decorator(func: Callable) -> Callable:
|
|
181
|
+
self._exc_table.register(exc_class, func)
|
|
182
|
+
return func
|
|
183
|
+
return decorator
|
|
184
|
+
|
|
185
|
+
def websocket(self, path: str):
|
|
186
|
+
return self._websocket_manager.websocket_decorator(path)
|
|
187
|
+
|
|
188
|
+
def middleware(self, middleware_type: str = "http"):
|
|
189
|
+
def decorator(middleware_func: Callable) -> Callable:
|
|
190
|
+
cls = create_decorated_middleware_class(middleware_func, middleware_type)
|
|
191
|
+
self.add_middleware(cls)
|
|
192
|
+
return middleware_func
|
|
193
|
+
return decorator
|
|
194
|
+
|
|
195
|
+
# ── Route registration ──────────────────────────────────────────────────
|
|
196
|
+
|
|
197
|
+
def _create_decorator(self, path: str, *, http_method: str, **kwargs: Any):
|
|
198
|
+
def decorator(endpoint_func: Callable) -> Callable:
|
|
199
|
+
self._installer.install(path, http_method, endpoint_func, **kwargs)
|
|
200
|
+
return endpoint_func
|
|
201
|
+
return decorator
|
|
202
|
+
|
|
203
|
+
def include_router(self, router, **kwargs: Any) -> None:
|
|
204
|
+
from ..router import Router
|
|
205
|
+
|
|
206
|
+
if not isinstance(router, Router):
|
|
207
|
+
raise TypeError("Expected Router instance")
|
|
208
|
+
|
|
209
|
+
for route_info in router.routes:
|
|
210
|
+
full_path = router.get_full_path(route_info["path"])
|
|
211
|
+
|
|
212
|
+
if route_info.get("is_websocket"):
|
|
213
|
+
self._websocket_manager.add_websocket_route(full_path, route_info["func"])
|
|
214
|
+
continue
|
|
215
|
+
|
|
216
|
+
route_kwargs = route_info.copy()
|
|
217
|
+
route_kwargs.pop("path", None)
|
|
218
|
+
route_kwargs.pop("method", None)
|
|
219
|
+
route_kwargs.pop("func", None)
|
|
220
|
+
route_kwargs.pop("is_websocket", None)
|
|
221
|
+
|
|
222
|
+
self._installer.install(
|
|
223
|
+
full_path, route_info["method"], route_info["func"], **route_kwargs
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
# ── Middleware ──────────────────────────────────────────────────────────
|
|
227
|
+
|
|
228
|
+
def add_middleware(self, middleware_class, **options: Any) -> None:
|
|
229
|
+
apply_middleware_to_router(self._router, middleware_class, **options)
|
|
230
|
+
self._mw_stack.add(middleware_class, **options)
|
|
231
|
+
self._http_app = None # invalidate — rebuild on next HTTP request
|
|
232
|
+
|
|
233
|
+
# ── ASGI entry ──────────────────────────────────────────────────────────
|
|
234
|
+
|
|
235
|
+
async def __call__(self, scope, receive, send) -> None:
|
|
236
|
+
await self._asgi_entry(scope, receive, send)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
__all__ = ["Tachyon"]
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# HOT PATH — Tachyon's ASGI entry point. Lazily builds the HTTP app on first
|
|
2
|
+
# request (middleware stack is mutable until then) and delegates by scope type.
|
|
3
|
+
|
|
4
|
+
from typing import Callable
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ASGIEntry:
|
|
8
|
+
"""Tachyon's __call__ — the ASGI callable surface."""
|
|
9
|
+
|
|
10
|
+
__slots__ = ("_app",)
|
|
11
|
+
|
|
12
|
+
def __init__(self, app) -> None:
|
|
13
|
+
self._app = app
|
|
14
|
+
|
|
15
|
+
async def __call__(self, scope, receive, send) -> None:
|
|
16
|
+
scope["app"] = self._app # required by Starlette middleware protocol
|
|
17
|
+
|
|
18
|
+
app = self._app
|
|
19
|
+
|
|
20
|
+
if not app._docs_routes.setup_done:
|
|
21
|
+
app._docs_routes.setup()
|
|
22
|
+
|
|
23
|
+
if scope["type"] == "http":
|
|
24
|
+
if app._http_app is None:
|
|
25
|
+
app._http_app = self._build_http_app()
|
|
26
|
+
await app._http_app(scope, receive, send)
|
|
27
|
+
else:
|
|
28
|
+
# WebSocket routing and lifespan need Starlette's full stack
|
|
29
|
+
await app._router(scope, receive, send)
|
|
30
|
+
|
|
31
|
+
def _build_http_app(self) -> Callable:
|
|
32
|
+
"""User middlewares → TachyonDispatcher (no Starlette overhead for HTTP)."""
|
|
33
|
+
return self._app._mw_stack.build(self._app._dispatcher)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# HOT PATH — cdef migration target for v1.3.x.
|
|
2
|
+
# Marker class for handlers that take (scope, receive, send) directly,
|
|
3
|
+
# skipping Request object creation in the trie dispatch path.
|
|
4
|
+
|
|
5
|
+
from typing import Callable
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class _ASGIHandler:
|
|
9
|
+
"""Marks a handler that takes (scope, receive, send) directly."""
|
|
10
|
+
|
|
11
|
+
__slots__ = ("fn",) # Callable → cdef object
|
|
12
|
+
|
|
13
|
+
def __init__(self, fn: Callable) -> None:
|
|
14
|
+
self.fn = fn
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Cold path — registers the documentation routes (/docs, /redoc, /swagger, /openapi.json).
|
|
2
|
+
# Setup is lazy: triggered on the first incoming request via ASGIEntry.
|
|
3
|
+
|
|
4
|
+
from ..responses import HTMLResponse
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class DocsRoutes:
|
|
8
|
+
"""Registers Tachyon's auto-generated documentation routes."""
|
|
9
|
+
|
|
10
|
+
__slots__ = ("_app", "_setup_done")
|
|
11
|
+
|
|
12
|
+
def __init__(self, app) -> None:
|
|
13
|
+
self._app = app
|
|
14
|
+
self._setup_done = False
|
|
15
|
+
|
|
16
|
+
@property
|
|
17
|
+
def setup_done(self) -> bool:
|
|
18
|
+
return self._setup_done
|
|
19
|
+
|
|
20
|
+
def setup(self) -> None:
|
|
21
|
+
if self._setup_done:
|
|
22
|
+
return
|
|
23
|
+
self._setup_done = True
|
|
24
|
+
|
|
25
|
+
app = self._app
|
|
26
|
+
cfg = app.openapi_config
|
|
27
|
+
gen = app.openapi_generator
|
|
28
|
+
|
|
29
|
+
@app.get(cfg.openapi_url, include_in_schema=False)
|
|
30
|
+
def get_openapi_schema():
|
|
31
|
+
return gen.get_openapi_schema()
|
|
32
|
+
|
|
33
|
+
@app.get(cfg.docs_url, include_in_schema=False)
|
|
34
|
+
def get_scalar_docs():
|
|
35
|
+
return HTMLResponse(gen.get_scalar_html(cfg.openapi_url, cfg.info.title))
|
|
36
|
+
|
|
37
|
+
@app.get("/swagger", include_in_schema=False)
|
|
38
|
+
def get_swagger_ui():
|
|
39
|
+
return HTMLResponse(gen.get_swagger_ui_html(cfg.openapi_url, cfg.info.title))
|
|
40
|
+
|
|
41
|
+
@app.get(cfg.redoc_url, include_in_schema=False)
|
|
42
|
+
def get_redoc():
|
|
43
|
+
return HTMLResponse(gen.get_redoc_html(cfg.openapi_url, cfg.info.title))
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Cold path — invoked at startup to register Tachyon's default error schemas
|
|
2
|
+
# on the OpenAPI generator.
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class CommonSchemas:
|
|
6
|
+
"""Registers Tachyon's default error response schemas on an OpenAPI generator."""
|
|
7
|
+
|
|
8
|
+
__slots__ = ()
|
|
9
|
+
|
|
10
|
+
@staticmethod
|
|
11
|
+
def register(generator) -> None:
|
|
12
|
+
generator.add_schema(
|
|
13
|
+
"ValidationErrorResponse",
|
|
14
|
+
{
|
|
15
|
+
"type": "object",
|
|
16
|
+
"properties": {
|
|
17
|
+
"success": {"type": "boolean"},
|
|
18
|
+
"error": {"type": "string"},
|
|
19
|
+
"code": {"type": "string"},
|
|
20
|
+
"errors": {
|
|
21
|
+
"type": "object",
|
|
22
|
+
"additionalProperties": {
|
|
23
|
+
"type": "array",
|
|
24
|
+
"items": {"type": "string"},
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
"required": ["success", "error", "code"],
|
|
29
|
+
},
|
|
30
|
+
)
|
|
31
|
+
generator.add_schema(
|
|
32
|
+
"ResponseValidationError",
|
|
33
|
+
{
|
|
34
|
+
"type": "object",
|
|
35
|
+
"properties": {
|
|
36
|
+
"success": {"type": "boolean"},
|
|
37
|
+
"error": {"type": "string"},
|
|
38
|
+
"detail": {"type": "string"},
|
|
39
|
+
"code": {"type": "string"},
|
|
40
|
+
},
|
|
41
|
+
"required": ["success", "error", "code"],
|
|
42
|
+
},
|
|
43
|
+
)
|
|
Binary file
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# HOT PATH — cdef migration target for v1.3.x.
|
|
2
|
+
# Registers user exception handlers and dispatches an exception to its handler.
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Callable, Dict, Optional, Type
|
|
7
|
+
|
|
8
|
+
from starlette.responses import JSONResponse, Response
|
|
9
|
+
|
|
10
|
+
from ..exceptions import HTTPException
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ExceptionTable:
|
|
16
|
+
"""Registers and dispatches user exception handlers."""
|
|
17
|
+
|
|
18
|
+
__slots__ = ("_handlers",) # Dict[Type[Exception], Callable] → cdef dict
|
|
19
|
+
|
|
20
|
+
def __init__(self) -> None:
|
|
21
|
+
self._handlers: Dict[Type[Exception], Callable] = {}
|
|
22
|
+
|
|
23
|
+
def register(self, exc_class: Type[Exception], func: Callable) -> None:
|
|
24
|
+
if not asyncio.iscoroutinefunction(func):
|
|
25
|
+
logger.warning(
|
|
26
|
+
"Exception handler %r for %s is synchronous and will block the event loop. "
|
|
27
|
+
"Consider making it async.",
|
|
28
|
+
func.__name__,
|
|
29
|
+
exc_class.__name__,
|
|
30
|
+
)
|
|
31
|
+
self._handlers[exc_class] = func
|
|
32
|
+
|
|
33
|
+
async def dispatch(self, exc: Exception, request) -> Optional[Response]:
|
|
34
|
+
"""Find a handler for exc and invoke it. Returns None if no handler matched.
|
|
35
|
+
|
|
36
|
+
Walks registered handlers in registration order — first `isinstance`
|
|
37
|
+
match wins. This is what lets users register a handler for a
|
|
38
|
+
`HTTPException` *subclass* (e.g., `MyDomainError(HTTPException)`) and
|
|
39
|
+
have it invoked instead of falling through to the default
|
|
40
|
+
`{"detail": ...}` response.
|
|
41
|
+
|
|
42
|
+
If nothing matched and `exc` is an `HTTPException`, returns the
|
|
43
|
+
default body. Other unhandled exceptions return `None` and the
|
|
44
|
+
caller emits a 500.
|
|
45
|
+
"""
|
|
46
|
+
for exc_class, handler in self._handlers.items():
|
|
47
|
+
if isinstance(exc, exc_class):
|
|
48
|
+
return await self._invoke(handler, request, exc)
|
|
49
|
+
|
|
50
|
+
if isinstance(exc, HTTPException):
|
|
51
|
+
return self._http_exception_response(exc)
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
@staticmethod
|
|
55
|
+
async def _invoke(handler: Callable, request, exc: Exception) -> Response:
|
|
56
|
+
if asyncio.iscoroutinefunction(handler):
|
|
57
|
+
return await handler(request, exc)
|
|
58
|
+
return handler(request, exc)
|
|
59
|
+
|
|
60
|
+
@staticmethod
|
|
61
|
+
def _http_exception_response(exc: HTTPException) -> Response:
|
|
62
|
+
response = JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
|
|
63
|
+
if exc.headers:
|
|
64
|
+
for key, value in exc.headers.items():
|
|
65
|
+
response.headers[key] = value
|
|
66
|
+
return response
|