cyengine 0.1.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.
cyengine/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ from cyengine.app import App
2
+ from cyengine.limits import Limits
3
+ from cyengine.routing import Group
4
+ from cyengine.errors import (
5
+ HTTPError, BadRequest, Unauthorized, Forbidden, NotFound, Conflict, UnprocessableEntity,
6
+ )
7
+ from cyengine.core._types import Request, Response, CyEngineError, RouterNotFound, MethodNotAllowed
8
+
9
+ __all__ = [
10
+ "App",
11
+ "Limits",
12
+ "Group",
13
+ "HTTPError",
14
+ "BadRequest",
15
+ "Unauthorized",
16
+ "Forbidden",
17
+ "NotFound",
18
+ "Conflict",
19
+ "UnprocessableEntity",
20
+ "Request",
21
+ "Response",
22
+ "CyEngineError",
23
+ "RouterNotFound",
24
+ "MethodNotAllowed",
25
+ ]
cyengine/app.py ADDED
@@ -0,0 +1,143 @@
1
+ import asyncio
2
+ from collections.abc import Callable
3
+ from typing import Any, Self, TypeVar, overload
4
+
5
+ from cyengine.core._router import Router
6
+ from cyengine.core._protocol import HttpProtocol
7
+ from cyengine.handler import Handler, HandlerFunc, HandlerFunction, Middleware, chain
8
+ from cyengine.routing import Group, Routes
9
+ from cyengine.limits import Limits
10
+ from cyengine.core._types import Request, Response
11
+ from cyengine.errors import ErrorHandlerFunc, ErrorHandlers, HTTPError, NotFound
12
+
13
+ from cyengine import server as _server
14
+
15
+ _E = TypeVar("_E", bound=Exception)
16
+ _ErrorF = TypeVar("_ErrorF", bound=ErrorHandlerFunc[Any])
17
+
18
+
19
+ class App(Routes):
20
+ """
21
+ Registration of handlers and middleware + startup. Dependencies live in main():
22
+
23
+ async def main():
24
+ db = await Database.connect(dsn)
25
+ try:
26
+ app = App()
27
+ app.use(recover)
28
+ app.handle("GET", "/users/<int:id>", UserHandler(db))
29
+ await app.serve(port=8000)
30
+ finally:
31
+ await db.close()
32
+ """
33
+
34
+ def __init__(self, limits: Limits | None = None) -> None:
35
+ self._limits = limits if limits is not None else Limits()
36
+ self._routes: list[tuple[str, str, Handler, Group | None]] = [] # (method, full path, …)
37
+ self._middleware: list[Middleware] = []
38
+ self._errors = ErrorHandlers()
39
+ self._router: Router | None = None # built in serve()
40
+ self._h404: HandlerFunction | None = None # 404/405 handlers, also built in serve()
41
+ self._h405: HandlerFunction | None = None
42
+ self._tasks: dict[asyncio.Task[None], float] = {} # request task → deadline (0 — none)
43
+ self._timed_out: set[asyncio.Task[Any]] = set() # cancelled due to handler_timeout
44
+ self._protocols: set[HttpProtocol] = set() # open connections
45
+
46
+ # ── registration ─────────────────────────────────────────────────────────
47
+
48
+ def _add(self, methods: list[str], path: str, handler: Handler) -> None:
49
+ for method in methods:
50
+ self._routes.append((method, path, handler, None))
51
+
52
+ def _group_context(self) -> tuple["App", str, Group | None]:
53
+ return self, "", None
54
+
55
+ @overload
56
+ def error_handler(self, exc_type: type[_E], fn: ErrorHandlerFunc[_E]) -> Self: ...
57
+ @overload
58
+ def error_handler(self, exc_type: type[Exception],
59
+ fn: None = None) -> Callable[[_ErrorF], _ErrorF]: ...
60
+
61
+ def error_handler(self, exc_type: type[Exception],
62
+ fn: ErrorHandlerFunc[Any] | None = None) -> Any:
63
+ """
64
+ What to return to the client if a handler raises an exception of this type.
65
+
66
+ async def not_found(request, exc):
67
+ return Response.json({"error": str(exc)}, status=404)
68
+
69
+ app.error_handler(UserNotFound, not_found)
70
+
71
+ @app.error_handler(ValidationError) # decorator
72
+ async def invalid(request, exc): ...
73
+
74
+ Applies to subclasses too; the most specific type wins.
75
+ error_handler(Exception, fn) — catch everything else instead of a 500.
76
+ """
77
+ if fn is not None:
78
+ self._errors.add(exc_type, fn)
79
+ return self
80
+
81
+ def decorator(func: _ErrorF) -> _ErrorF:
82
+ self._errors.add(exc_type, func)
83
+ return func
84
+ return decorator
85
+
86
+ # ── startup ──────────────────────────────────────────────────────────────
87
+
88
+ def _build_router(self) -> Router:
89
+ """Middleware chains are built once, at startup."""
90
+ router = Router()
91
+ for method, path, handler, group in self._routes:
92
+ mw = [*self._middleware, *(group._all_middleware() if group else ())]
93
+ router.add(method, path, chain(self._errors.wrap(handler), mw).handle)
94
+
95
+ # OPTIONS: if a path has no handler of its own — automatic 204 + Allow response.
96
+ # It goes through the same chain (incl. group middleware), so CORS etc. can see it.
97
+ async def options(request: Request) -> Response:
98
+ allow = ", ".join(router.allowed(request.path))
99
+ return Response.empty(204, headers={"Allow": allow})
100
+
101
+ options_wrapped = self._errors.wrap(HandlerFunc(options))
102
+ auto_cache: dict[tuple[int, ...], HandlerFunction] = {} # one chain per set of middleware
103
+ by_path: dict[str, list[Any]] = {} # path → [methods, group]
104
+ for method, path, _, group in self._routes:
105
+ entry = by_path.setdefault(path, [set(), group])
106
+ entry[0].add(method)
107
+ for path, (methods, group) in by_path.items():
108
+ if "OPTIONS" in methods:
109
+ continue
110
+ mw = [*self._middleware, *(group._all_middleware() if group else ())]
111
+ key = tuple(id(m) for m in mw)
112
+ if key not in auto_cache:
113
+ auto_cache[key] = chain(options_wrapped, mw).handle
114
+ router.add("OPTIONS", path, auto_cache[key])
115
+
116
+ # 404/405 are handlers like any other: middleware and error handlers apply to them
117
+ async def not_found(request: Request) -> Response:
118
+ raise NotFound()
119
+
120
+ async def method_not_allowed(request: Request) -> Response:
121
+ allow = ", ".join(router.allowed(request.path))
122
+ raise HTTPError(405, headers={"Allow": allow})
123
+
124
+ for name, fn in (("_h404", not_found), ("_h405", method_not_allowed)):
125
+ wrapped = self._errors.wrap(HandlerFunc(fn))
126
+ setattr(self, name, chain(wrapped, self._middleware).handle)
127
+ return router
128
+
129
+ def _make_protocol(self, loop: asyncio.AbstractEventLoop) -> HttpProtocol:
130
+ # serve() builds the router before the first connection is accepted
131
+ return HttpProtocol(self._router, self, loop) # type: ignore[arg-type]
132
+
133
+ async def serve(self, host: str = "0.0.0.0", port: int = 8000,
134
+ grace: float = 10.0) -> None:
135
+ """Blocks until SIGINT/SIGTERM, then waits for in-flight requests."""
136
+ await _server.serve(self, host, port, grace=grace)
137
+
138
+ def run(self, host: str = "0.0.0.0", port: int = 8000) -> None:
139
+ """Sync version of serve() — for applications with nothing to close."""
140
+ _server.run(self, host=host, port=port)
141
+
142
+
143
+ __all__ = ["App"]
@@ -0,0 +1,33 @@
1
+ import asyncio
2
+ import logging
3
+
4
+ from cyengine.app import App
5
+ from cyengine.core._router import Router
6
+
7
+ log: logging.Logger
8
+
9
+ class HttpProtocol(asyncio.Protocol):
10
+ """asyncio.Protocol — one instance per TCP connection."""
11
+
12
+ # router is None only until serve() builds it, before the first connection
13
+ def __init__(self, router: Router, app: App, loop: asyncio.AbstractEventLoop) -> None: ...
14
+
15
+ # asyncio callbacks
16
+ def connection_made(self, transport: asyncio.BaseTransport) -> None: ...
17
+ def connection_lost(self, exc: BaseException | None) -> None: ...
18
+ def data_received(self, data: bytes) -> None: ...
19
+
20
+ def close(self) -> None: ...
21
+ def shutdown(self) -> None:
22
+ """Server shutdown: finish accepted requests and close the connection."""
23
+
24
+ # httptools callbacks
25
+ def on_message_begin(self) -> None: ...
26
+ def on_url(self, url: bytes) -> None: ...
27
+ def on_header(self, name: bytes, value: bytes) -> None: ...
28
+ def on_headers_complete(self) -> None: ...
29
+ def on_body(self, body: bytes) -> None: ...
30
+ def on_message_complete(self) -> None: ...
31
+
32
+ # used by the sweeper in cyengine.server
33
+ def _check_deadline(self, now: float) -> None: ...
@@ -0,0 +1,33 @@
1
+ from typing import Any
2
+
3
+ class TrieNode:
4
+ children: dict[str, TrieNode]
5
+ param_child: TrieNode | None
6
+ param_name: str
7
+ param_type: int
8
+ handlers: dict[str, Any] | None
9
+ """None — intermediate node."""
10
+
11
+ class Router:
12
+ """
13
+ Trie-based HTTP router.
14
+
15
+ router = Router()
16
+ router.add("GET", "/users/<int:id>", my_handler)
17
+ handler, params = router.match("GET", "/users/42") # params = {"id": 42}
18
+ """
19
+
20
+ def add(self, method: str, path: str, handler: object) -> None: ...
21
+ def match(self, method: str, path: str) -> tuple[Any, dict[str, Any]]:
22
+ """Return (handler, params); raises RouterNotFound or MethodNotAllowed."""
23
+
24
+ def allowed(self, path: str) -> list[str]:
25
+ """HTTP methods registered for a path (for the Allow header)."""
26
+
27
+ def get(self, path: str, handler: object) -> None: ...
28
+ def post(self, path: str, handler: object) -> None: ...
29
+ def put(self, path: str, handler: object) -> None: ...
30
+ def delete(self, path: str, handler: object) -> None: ...
31
+ def patch(self, path: str, handler: object) -> None: ...
32
+ def routes(self) -> list[tuple[str, str, Any]]:
33
+ """All registered routes as (method, path, handler)."""
Binary file
@@ -0,0 +1,175 @@
1
+ import asyncio
2
+ from datetime import datetime
3
+ from typing import Any, Self, TypeAlias, TypeVar, overload
4
+
5
+ from cyengine.app import App
6
+
7
+ _T = TypeVar("_T")
8
+
9
+ # dict is invariant, so every common spelling of a headers dict is listed separately
10
+ _HeadersArg: TypeAlias = dict[str, str] | dict[str, list[str]] | dict[str, str | list[str]]
11
+
12
+ class CyEngineError(Exception):
13
+ """Base class for all framework errors."""
14
+
15
+ class RouterNotFound(CyEngineError):
16
+ method: str
17
+ path: str
18
+ def __init__(self, method: str, path: str) -> None: ...
19
+
20
+ class MethodNotAllowed(CyEngineError):
21
+ method: str
22
+ path: str
23
+ def __init__(self, method: str, path: str) -> None: ...
24
+
25
+ def date_header() -> bytes:
26
+ """`Date: ...\\r\\n` line; formatted once per second, not for every response."""
27
+
28
+ class Request:
29
+ """HTTP request."""
30
+
31
+ method: str
32
+ path: str
33
+ query_string: bytes
34
+ headers: dict[str, str]
35
+ """Names are lowercased."""
36
+ path_params: dict[str, Any]
37
+ """Typed by the router."""
38
+
39
+ # protocol infrastructure, used by cyengine.core._protocol
40
+ _body: bytes | bytearray
41
+ _app: App | None
42
+ _transport: asyncio.Transport | None
43
+
44
+ def __init__(self) -> None: ...
45
+ def header(self, name: str, default: str = "") -> str:
46
+ """Get a header by name (case-insensitive)."""
47
+
48
+ @property
49
+ def query(self) -> dict[str, str]:
50
+ """
51
+ Lazy query string parsing.
52
+ /users?page=2&limit=10 → {"page": "2", "limit": "10"}
53
+ """
54
+
55
+ @property
56
+ def cookies(self) -> dict[str, str]:
57
+ """Request cookies: {"name": "value"}. Parsed on first access."""
58
+
59
+ @property
60
+ def client(self) -> tuple[str, int] | tuple[str, int, int, int] | None:
61
+ """
62
+ Client address: (host, port), or (host, port, flowinfo, scope_id) for IPv6;
63
+ None if the connection is already closed.
64
+ """
65
+
66
+ @property
67
+ def state(self) -> dict[str, Any]:
68
+ """
69
+ Arbitrary per-request data — for passing from middleware to the handler.
70
+
71
+ request.state["user"] = user # in middleware
72
+ user = request.state["user"] # in the handler
73
+ """
74
+
75
+ def body(self) -> bytes:
76
+ """Raw request body."""
77
+
78
+ def json(self) -> Any:
79
+ """
80
+ Deserialize the body as JSON with orjson.
81
+ Invalid or empty JSON → BadRequest (400).
82
+ """
83
+
84
+ @overload
85
+ def parse(self, model: type[_T]) -> _T:
86
+ """
87
+ Body (JSON) → instance of a pydantic model (or of any type TypeAdapter
88
+ understands: list[Model], dict[str, int]).
89
+ On failure → RequestValidationError (422).
90
+
91
+ user = request.parse(CreateUser)
92
+ """
93
+
94
+ @overload
95
+ def parse(self, model: object) -> Any: ...
96
+ @overload
97
+ def parse_query(self, model: type[_T]) -> _T:
98
+ """Query string → model (string values are coerced to the field types)."""
99
+
100
+ @overload
101
+ def parse_query(self, model: object) -> Any: ...
102
+ def text(self, encoding: str = "utf-8") -> str:
103
+ """Body as a string. If it can't be decoded → BadRequest (400)."""
104
+
105
+ class Response:
106
+ """HTTP response."""
107
+
108
+ status: int
109
+ body: bytes
110
+ headers: dict[str, str | list[str]]
111
+ """A list value produces multiple header lines."""
112
+ keep_alive: bool
113
+
114
+ # __new__, not __init__: the Cython class takes these in __cinit__
115
+ def __new__(
116
+ cls,
117
+ body: bytes = b"",
118
+ status: int = 200,
119
+ headers: _HeadersArg | None = None,
120
+ keep_alive: bool = True,
121
+ ) -> Self: ...
122
+ @classmethod
123
+ def json(cls, data: object, status: int = 200, headers: _HeadersArg | None = None) -> Self:
124
+ """
125
+ Fast constructor for a JSON response.
126
+
127
+ return Response.json({"id": 1})
128
+ return Response.json({"error": "not found"}, status=404)
129
+ """
130
+
131
+ @classmethod
132
+ def text(cls, data: str, status: int = 200, headers: _HeadersArg | None = None) -> Self: ...
133
+ @classmethod
134
+ def empty(cls, status: int = 204, headers: _HeadersArg | None = None) -> Self: ...
135
+ def set_cookie(
136
+ self,
137
+ name: str,
138
+ value: str = "",
139
+ *,
140
+ max_age: float | None = None,
141
+ expires: datetime | None = None,
142
+ path: str = "/",
143
+ domain: str | None = None,
144
+ secure: bool = False,
145
+ httponly: bool = True,
146
+ samesite: str | None = "lax",
147
+ ) -> Self:
148
+ """
149
+ Add a Set-Cookie (can be called several times — the lines accumulate).
150
+
151
+ resp.set_cookie("sid", token, max_age=3600, secure=True)
152
+
153
+ Safe defaults: HttpOnly and SameSite=Lax. Enable Secure when serving
154
+ over HTTPS. expires — datetime (naive is treated as UTC). samesite —
155
+ "lax", "strict", "none" or None. Disallowed characters in the name, value
156
+ or attributes → ValueError. Returns self.
157
+ """
158
+
159
+ def delete_cookie(
160
+ self,
161
+ name: str,
162
+ *,
163
+ path: str = "/",
164
+ domain: str | None = None,
165
+ secure: bool = False,
166
+ httponly: bool = True,
167
+ samesite: str | None = "lax",
168
+ ) -> Self:
169
+ """Delete a cookie on the client (path and domain must match those used to set it)."""
170
+
171
+ def render(self, keep_alive: bool = True, head: bool = False) -> bytes:
172
+ """
173
+ Serialize to the HTTP/1.1 wire format.
174
+ head=True (response to HEAD): headers as for GET, but no body.
175
+ """
cyengine/errors.py ADDED
@@ -0,0 +1,182 @@
1
+ """
2
+ HTTP errors: raise one from a handler — the framework turns it into a response.
3
+
4
+ async def handle(self, request):
5
+ user = await self.db.get(request.path_params["id"])
6
+ if user is None:
7
+ raise NotFound("user not found")
8
+ ...
9
+
10
+ The response body is JSON `{"error": <detail>}`; if the client asks for text/plain
11
+ (and doesn't ask for application/json) — plain text.
12
+ """
13
+
14
+ import inspect
15
+ from collections.abc import Awaitable, Callable, Mapping
16
+ from http import HTTPStatus
17
+ from typing import Any, TypeVar
18
+
19
+ import orjson
20
+
21
+ from cyengine.core._types import CyEngineError, Request, Response
22
+ from cyengine.handler import Handler, HandlerFunc
23
+
24
+ _E = TypeVar("_E", bound=Exception)
25
+ _HeadersArg = Mapping[str, str | list[str]]
26
+
27
+ # `async def f(request, exc) -> Response`; generic in the exception type: ErrorHandlerFunc[MyError]
28
+ ErrorHandlerFunc = Callable[[Request, _E], Awaitable[Response]]
29
+
30
+
31
+ class HTTPError(CyEngineError):
32
+ """
33
+ Base HTTP error.
34
+
35
+ raise HTTPError(418, "I'm a teapot")
36
+ raise HTTPError(429, {"retry_after": 5}, headers={"Retry-After": "5"})
37
+
38
+ detail — a string or any JSON-serializable object;
39
+ defaults to the standard status phrase.
40
+ """
41
+
42
+ status: int
43
+ detail: Any
44
+ headers: dict[str, str | list[str]]
45
+
46
+ def __init__(self, status: int, detail: object = None, *,
47
+ headers: _HeadersArg | None = None) -> None:
48
+ if not 400 <= status <= 599:
49
+ raise ValueError(f"HTTPError status must be 4xx or 5xx, got {status}")
50
+ if detail is None:
51
+ detail = _phrase(status)
52
+ super().__init__(f"{status} {detail}")
53
+ self.status = status
54
+ self.detail = detail
55
+ self.headers = dict(headers) if headers else {}
56
+
57
+ def response(self, request: Request | None = None) -> Response:
58
+ """Build a Response; the body format is chosen by the Accept header."""
59
+ headers = dict(self.headers)
60
+ if _wants_text(request):
61
+ text = self.detail if isinstance(self.detail, str) \
62
+ else orjson.dumps(self.detail).decode()
63
+ return Response.text(text, status=self.status, headers=headers)
64
+ return Response.json({"error": self.detail}, status=self.status, headers=headers)
65
+
66
+
67
+ def _phrase(status: int) -> str:
68
+ try:
69
+ return HTTPStatus(status).phrase
70
+ except ValueError:
71
+ return "Error"
72
+
73
+
74
+ def _wants_text(request: Request | None) -> bool:
75
+ if request is None:
76
+ return False
77
+ accept = request.header("accept")
78
+ return "text/plain" in accept and "application/json" not in accept
79
+
80
+
81
+ class BadRequest(HTTPError):
82
+ def __init__(self, detail: object = None, *,
83
+ headers: _HeadersArg | None = None) -> None:
84
+ super().__init__(400, detail, headers=headers)
85
+
86
+
87
+ class Unauthorized(HTTPError):
88
+ def __init__(self, detail: object = None, *,
89
+ headers: _HeadersArg | None = None) -> None:
90
+ super().__init__(401, detail, headers=headers)
91
+
92
+
93
+ class Forbidden(HTTPError):
94
+ def __init__(self, detail: object = None, *,
95
+ headers: _HeadersArg | None = None) -> None:
96
+ super().__init__(403, detail, headers=headers)
97
+
98
+
99
+ class NotFound(HTTPError):
100
+ def __init__(self, detail: object = None, *,
101
+ headers: _HeadersArg | None = None) -> None:
102
+ super().__init__(404, detail, headers=headers)
103
+
104
+
105
+ class Conflict(HTTPError):
106
+ def __init__(self, detail: object = None, *,
107
+ headers: _HeadersArg | None = None) -> None:
108
+ super().__init__(409, detail, headers=headers)
109
+
110
+
111
+ class UnprocessableEntity(HTTPError):
112
+ def __init__(self, detail: object = None, *,
113
+ headers: _HeadersArg | None = None) -> None:
114
+ super().__init__(422, detail, headers=headers)
115
+
116
+
117
+ class RequestValidationError(HTTPError):
118
+ """
119
+ 422: input failed pydantic validation (request.parse / request.parse_query).
120
+ detail — a list [{"type", "loc", "msg", "input"}, ...]; loc starts with
121
+ the source: ("body", "age"). The format can be replaced via app.error_handler.
122
+ """
123
+
124
+ errors: list[dict[str, Any]]
125
+
126
+ def __init__(self, errors: list[dict[str, Any]]) -> None:
127
+ super().__init__(422, errors)
128
+ self.errors = errors
129
+
130
+
131
+ # ─── Error handlers ──────────────────────────────────────────────────────────
132
+
133
+ async def _http_error_handler(request: Request, exc: HTTPError) -> Response:
134
+ return exc.response(request)
135
+
136
+
137
+ class ErrorHandlers:
138
+ """
139
+ Registry "exception type → function". Function: `async def f(request, exc) -> Response`.
140
+
141
+ The most specific registered type is chosen (by the exception's MRO).
142
+ By default only HTTPError → exc.response(request) is registered;
143
+ it can be overridden. An exception without a handler propagates further
144
+ (to recover / the protocol → 500).
145
+ """
146
+
147
+ def __init__(self) -> None:
148
+ # each function accepts its own key's exception type, hence Any
149
+ self._map: dict[type, ErrorHandlerFunc[Any]] = {HTTPError: _http_error_handler}
150
+
151
+ def add(self, exc_type: type[_E], fn: ErrorHandlerFunc[_E]) -> None:
152
+ if not (isinstance(exc_type, type) and issubclass(exc_type, Exception)):
153
+ raise TypeError(f"error_handler: {exc_type!r} is not an Exception subclass")
154
+ call = fn if inspect.isfunction(fn) or inspect.ismethod(fn) else getattr(fn, "__call__", None)
155
+ if not callable(fn) or not inspect.iscoroutinefunction(call):
156
+ raise TypeError(
157
+ f"error handler {fn!r} must be async: `async def f(request, exc) -> Response`"
158
+ )
159
+ self._map[exc_type] = fn
160
+
161
+ def find(self, exc: BaseException) -> ErrorHandlerFunc[Any] | None:
162
+ for cls in type(exc).__mro__:
163
+ fn = self._map.get(cls)
164
+ if fn is not None:
165
+ return fn
166
+ return None
167
+
168
+ def wrap(self, handler: Handler) -> HandlerFunc:
169
+ """Wrap a Handler: exception → response. Applied closest to the handler,
170
+ so middleware sees a ready-made Response."""
171
+ find = self.find
172
+
173
+ async def handle(request: Request) -> Response:
174
+ try:
175
+ return await handler.handle(request)
176
+ except Exception as exc:
177
+ fn = find(exc)
178
+ if fn is None:
179
+ raise
180
+ return await fn(request, exc)
181
+
182
+ return HandlerFunc(handle)
cyengine/handler.py ADDED
@@ -0,0 +1,86 @@
1
+ """
2
+ The handler contract — what the framework works with.
3
+
4
+ class UserHandler:
5
+ def __init__(self, db):
6
+ self.db = db
7
+
8
+ async def handle(self, request: Request) -> Response:
9
+ user = await self.db.get(request.path_params["id"])
10
+ return Response.json(user)
11
+
12
+ A plain `async def f(request) -> Response` works too —
13
+ the framework wraps it in HandlerFunc (like http.HandlerFunc in Go).
14
+
15
+ Middleware is a function Handler -> Handler:
16
+
17
+ def timing(next):
18
+ async def handle(request):
19
+ t = time.perf_counter()
20
+ resp = await next.handle(request)
21
+ resp.headers["X-Time"] = str(time.perf_counter() - t)
22
+ return resp
23
+ return HandlerFunc(handle)
24
+ """
25
+
26
+ import inspect
27
+ from collections.abc import Awaitable, Callable, Iterable
28
+ from typing import Protocol, runtime_checkable
29
+
30
+ from cyengine.core._types import Request, Response
31
+
32
+
33
+ @runtime_checkable
34
+ class Handler(Protocol):
35
+ # `def` returning Awaitable matches `async def` implementations; positional-only,
36
+ # because the framework passes the request positionally (any parameter name fits)
37
+ def handle(self, request: Request, /) -> Awaitable[Response]: ...
38
+
39
+
40
+ Middleware = Callable[[Handler], Handler]
41
+
42
+ # a plain `async def f(request) -> Response`
43
+ HandlerFunction = Callable[[Request], Awaitable[Response]]
44
+
45
+
46
+ class _BoundHandle(Protocol):
47
+ def __call__(self, request: Request, /) -> Awaitable[Response]: ...
48
+
49
+
50
+ class HandlerFunc:
51
+ """Adapter: async function -> Handler. No extra await on the hot path."""
52
+
53
+ __slots__ = ("handle",)
54
+
55
+ def __init__(self, fn: HandlerFunction) -> None:
56
+ # a callback protocol, not Callable: pyright would bind a Callable attribute
57
+ # declared in __slots__ as a method and reject HandlerFunc as a Handler
58
+ self.handle: _BoundHandle = fn
59
+
60
+
61
+ def as_handler(obj: Handler | HandlerFunction) -> Handler:
62
+ """Convert an object to a Handler. Fails at registration, not on a request."""
63
+ handle = getattr(obj, "handle", None)
64
+ result: Handler
65
+ target: object
66
+ if handle is not None and callable(handle):
67
+ # a callable `handle` attribute is what makes obj a Handler; checkers can't infer that
68
+ result, target = obj, handle # type: ignore[assignment]
69
+ elif callable(obj):
70
+ result, target = HandlerFunc(obj), obj
71
+ else:
72
+ raise TypeError(
73
+ f"{obj!r} is not a handler: expected an object with "
74
+ f"`async def handle(request)` or an async function"
75
+ )
76
+
77
+ if not inspect.iscoroutinefunction(target):
78
+ raise TypeError(f"handler {obj!r} must be async (`async def handle(request)`)")
79
+ return result
80
+
81
+
82
+ def chain(handler: Handler, middleware: Iterable[Middleware]) -> Handler:
83
+ """Wrap handler in middleware. The first in the list is the outermost."""
84
+ for mw in reversed(list(middleware)):
85
+ handler = as_handler(mw(handler))
86
+ return handler
cyengine/limits.py ADDED
@@ -0,0 +1,23 @@
1
+ from dataclasses import dataclass
2
+ from typing import Optional
3
+
4
+
5
+ @dataclass(frozen=True)
6
+ class Limits:
7
+ """
8
+ Server limits. None — unlimited.
9
+
10
+ max_header_size — URL + all headers, bytes. Exceeded → 431.
11
+ max_body_size — request body, bytes. Exceeded → 413 (by Content-Length
12
+ before the body is read, for chunked — as data arrives).
13
+ read_timeout — seconds from the first byte of a request to the full request
14
+ (slowloris protection). Expired → 408.
15
+ keepalive_timeout — idle seconds on a keep-alive connection. Expired → closed silently.
16
+ handler_timeout — seconds to run the handler (with middleware). Expired → 503.
17
+ """
18
+
19
+ max_header_size: Optional[int] = 64 * 1024
20
+ max_body_size: Optional[int] = 1024 * 1024
21
+ read_timeout: Optional[float] = 30.0
22
+ keepalive_timeout: Optional[float] = 75.0
23
+ handler_timeout: Optional[float] = 30.0
cyengine/middleware.py ADDED
@@ -0,0 +1,209 @@
1
+ """
2
+ Built-in middleware.
3
+
4
+ Order: the first one in app.use(...) is the outermost. Recommended:
5
+
6
+ app.use(access_log(), cors(allow_origins=["https://example.com"]), recover)
7
+
8
+ access_log on the outside sees everything (incl. 404s and error handler responses);
9
+ cors goes outside recover, otherwise a 500 after an exception is sent without CORS
10
+ headers and the browser reports a CORS error instead of the real one.
11
+ """
12
+
13
+ import logging
14
+ import re
15
+ from collections.abc import Iterable
16
+ from time import perf_counter
17
+
18
+ from cyengine.core._types import Request, Response
19
+ from cyengine.errors import HTTPError
20
+ from cyengine.handler import Handler, HandlerFunc, Middleware
21
+
22
+ log: logging.Logger = logging.getLogger("cyengine")
23
+
24
+
25
+ # ─── recover ─────────────────────────────────────────────────────────────────
26
+
27
+ def recover(next: Handler) -> Handler:
28
+ """HTTPError -> response with its status; any other exception -> log + 500."""
29
+
30
+ async def handle(request: Request) -> Response:
31
+ try:
32
+ return await next.handle(request)
33
+ except HTTPError as exc:
34
+ return exc.response(request)
35
+ except Exception:
36
+ log.exception("unhandled error in %s %s", request.method, request.path)
37
+ return Response.text("Internal Server Error", status=500)
38
+
39
+ return HandlerFunc(handle)
40
+
41
+
42
+ # ─── access log ──────────────────────────────────────────────────────────────
43
+
44
+ def _default_access_logger() -> logging.Logger:
45
+ """The cyengine.access logger. If logging was never configured, prints to stderr."""
46
+ lg = logging.getLogger("cyengine.access")
47
+ if not lg.handlers and not logging.getLogger().handlers:
48
+ handler = logging.StreamHandler()
49
+ handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
50
+ lg.addHandler(handler)
51
+ lg.setLevel(logging.INFO)
52
+ lg.propagate = False
53
+ return lg
54
+
55
+
56
+ def access_log(logger: logging.Logger | None = None, level: int = logging.INFO) -> Middleware:
57
+ """
58
+ One line per request:
59
+
60
+ 127.0.0.1 "GET /users/42?x=1" 200 25b 0.31ms
61
+
62
+ An exception not handled further down the chain is logged as 500 and propagates.
63
+ If the application has already configured logging (root handler), writes through it,
64
+ otherwise to stderr.
65
+ """
66
+ lg = logger if logger is not None else _default_access_logger()
67
+
68
+ def middleware(next: Handler) -> Handler:
69
+ async def handle(request: Request) -> Response:
70
+ start = perf_counter()
71
+ try:
72
+ response = await next.handle(request)
73
+ except Exception:
74
+ _emit(lg, level, request, 500, 0, start)
75
+ raise
76
+ _emit(lg, level, request, response.status, len(response.body), start)
77
+ return response
78
+
79
+ return HandlerFunc(handle)
80
+
81
+ return middleware
82
+
83
+
84
+ def _emit(lg: logging.Logger, level: int, request: Request,
85
+ status: int, size: int, start: float) -> None:
86
+ if not lg.isEnabledFor(level):
87
+ return
88
+ client = request.client
89
+ target = request.path
90
+ if request.query_string:
91
+ target += "?" + request.query_string.decode("latin-1")
92
+ lg.log(level, '%s "%s %s" %d %db %.2fms',
93
+ client[0] if client else "-", request.method, target,
94
+ status, size, (perf_counter() - start) * 1000)
95
+
96
+
97
+ # ─── CORS ────────────────────────────────────────────────────────────────────
98
+
99
+ _DEFAULT_METHODS = ("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE")
100
+
101
+
102
+ def cors(allow_origins: Iterable[str] | None = None, *,
103
+ allow_origin_regex: str | None = None,
104
+ allow_methods: Iterable[str] = _DEFAULT_METHODS,
105
+ allow_headers: Iterable[str] | None = None,
106
+ expose_headers: Iterable[str] = (),
107
+ allow_credentials: bool = False, max_age: int = 600) -> Middleware:
108
+ """
109
+ CORS.
110
+
111
+ allow_origins — exact origins ("https://example.com") or "*" for any.
112
+ Not set and no allow_origin_regex → "*".
113
+ allow_origin_regex — regex that the whole Origin must match;
114
+ can be combined with the list (either way is accepted).
115
+ allow_methods — what to return on preflight in Access-Control-Allow-Methods.
116
+ allow_headers — list of allowed headers; None — allow everything
117
+ the browser asked for (echo of Access-Control-Request-Headers).
118
+ expose_headers — which response headers are accessible to client JS code.
119
+ allow_credentials — cookies / Authorization. With "*", the concrete Origin is
120
+ returned instead of the asterisk (the spec forbids "*").
121
+ max_age — how many seconds the browser caches a preflight.
122
+
123
+ Preflight (OPTIONS + Origin + Access-Control-Request-Method) is answered here,
124
+ without calling the handler. A disallowed Origin on preflight → 403.
125
+ CORS headers are not added to regular requests without Origin or with a disallowed one.
126
+ """
127
+ if allow_origins is None:
128
+ allow_origins = () if allow_origin_regex else ("*",)
129
+ origins = set(allow_origins)
130
+ wildcard = "*" in origins
131
+ regex = re.compile(allow_origin_regex) if allow_origin_regex else None
132
+ methods = ", ".join(allow_methods)
133
+ headers_list = ", ".join(allow_headers) if allow_headers is not None else None
134
+ expose = ", ".join(expose_headers)
135
+ # ACAO depends on Origin, except in the "asterisk for everyone" case
136
+ vary_origin = not (wildcard and not allow_credentials)
137
+
138
+ def origin_allowed(origin: str) -> bool:
139
+ return wildcard or origin in origins or (
140
+ regex is not None and regex.fullmatch(origin) is not None)
141
+
142
+ def origin_value(origin: str) -> str:
143
+ return "*" if wildcard and not allow_credentials else origin
144
+
145
+ def middleware(next: Handler) -> Handler:
146
+ async def handle(request: Request) -> Response:
147
+ origin = request.header("origin")
148
+ if not origin:
149
+ response = await next.handle(request)
150
+ if vary_origin:
151
+ _add_vary(response, "Origin")
152
+ return response
153
+
154
+ allowed = origin_allowed(origin)
155
+
156
+ if (request.method == "OPTIONS"
157
+ and request.header("access-control-request-method")):
158
+ return _preflight(request, origin, allowed)
159
+
160
+ response = await next.handle(request)
161
+ if vary_origin:
162
+ _add_vary(response, "Origin")
163
+ if allowed:
164
+ h = response.headers
165
+ h["Access-Control-Allow-Origin"] = origin_value(origin)
166
+ if allow_credentials:
167
+ h["Access-Control-Allow-Credentials"] = "true"
168
+ if expose:
169
+ h["Access-Control-Expose-Headers"] = expose
170
+ return response
171
+
172
+ def _preflight(request: Request, origin: str, allowed: bool) -> Response:
173
+ if not allowed:
174
+ return HTTPError(403, "CORS origin not allowed").response(request)
175
+ h = {
176
+ "Access-Control-Allow-Origin": origin_value(origin),
177
+ "Access-Control-Allow-Methods": methods,
178
+ "Access-Control-Max-Age": str(max_age),
179
+ }
180
+ requested = request.header("access-control-request-headers")
181
+ if headers_list is not None:
182
+ h["Access-Control-Allow-Headers"] = headers_list
183
+ elif requested:
184
+ h["Access-Control-Allow-Headers"] = requested
185
+ if allow_credentials:
186
+ h["Access-Control-Allow-Credentials"] = "true"
187
+ response = Response.empty(204, headers=h)
188
+ _add_vary(response, "Origin, Access-Control-Request-Method, "
189
+ "Access-Control-Request-Headers")
190
+ return response
191
+
192
+ return HandlerFunc(handle)
193
+
194
+ return middleware
195
+
196
+
197
+ def _add_vary(response: Response, value: str) -> None:
198
+ """Append to Vary without overwriting what the handler set (key is case-insensitive)."""
199
+ headers = response.headers
200
+ for key in headers:
201
+ if key.lower() == "vary":
202
+ # Vary is expected to be a single string; a list value is not supported here
203
+ existing: str = headers[key] # type: ignore[assignment]
204
+ missing = [v for v in value.split(", ")
205
+ if v.lower() not in {p.strip().lower() for p in existing.split(",")}]
206
+ if missing:
207
+ headers[key] = existing + ", " + ", ".join(missing)
208
+ return
209
+ headers["Vary"] = value
File without changes
File without changes
File without changes
File without changes
cyengine/py.typed ADDED
File without changes
cyengine/routing.py ADDED
@@ -0,0 +1,120 @@
1
+ """Route registration: the common interface of App and Group."""
2
+
3
+ from collections.abc import Callable, Iterable
4
+ from typing import TYPE_CHECKING, Self, TypeVar
5
+
6
+ from cyengine.handler import Handler, HandlerFunction, Middleware, as_handler
7
+
8
+ if TYPE_CHECKING:
9
+ from cyengine.app import App
10
+
11
+ # decorators return the decorated function with its type unchanged
12
+ _F = TypeVar("_F", bound=HandlerFunction)
13
+
14
+
15
+ def join_path(prefix: str, path: str) -> str:
16
+ """join_path("/api/", "/users/") -> "/api/users"; join_path("/api", "/") -> "/api"."""
17
+ parts = [s for s in (prefix.strip("/"), path.strip("/")) if s]
18
+ return "/" + "/".join(parts)
19
+
20
+
21
+ class Routes:
22
+ """
23
+ Mixin: handle / get / post / ... / use / group.
24
+ A subclass defines `_middleware` (list), `_add()` and `_group_context()`.
25
+ """
26
+
27
+ _middleware: list[Middleware]
28
+
29
+ def use(self, *middleware: Middleware) -> Self:
30
+ """The first one passed is the outermost. Applies to all routes (including
31
+ ones registered earlier — chains are built at startup)."""
32
+ self._middleware.extend(middleware)
33
+ return self
34
+
35
+ def handle(self, methods: str | Iterable[str], path: str,
36
+ handler: Handler | HandlerFunction) -> Self:
37
+ """
38
+ app.handle("GET", "/users/<int:id>", UserHandler(db))
39
+ api.handle(["GET", "HEAD"], "/health", health)
40
+ """
41
+ h = as_handler(handler)
42
+ if isinstance(methods, str):
43
+ methods = [methods]
44
+ self._add([m.upper() for m in methods], path, h)
45
+ return self
46
+
47
+ def group(self, prefix: str, *middleware: Middleware) -> "Group":
48
+ """
49
+ Route group with a common prefix and its own middleware.
50
+
51
+ api = app.group("/api/v1", auth)
52
+ api.handle("GET", "/users/<int:id>", UserHandler(db)) # GET /api/v1/users/<id>
53
+ admin = api.group("/admin", require_admin) # nested
54
+
55
+ Chain order: application middleware → parent groups → this group →
56
+ error handlers → handler. 404/405 within the prefix go through application
57
+ middleware only: until a route is chosen, it's unknown which group they belong to.
58
+ """
59
+ if not isinstance(prefix, str) or (prefix not in ("", "/") and not prefix.startswith("/")):
60
+ raise ValueError(f'group prefix must start with "/", got {prefix!r}')
61
+ app, base, parent = self._group_context()
62
+ return Group(app, join_path(base, prefix), parent, list(middleware))
63
+
64
+ # sugar for function handlers: @app.get("/path")
65
+
66
+ def route(self, path: str, methods: str | Iterable[str]) -> Callable[[_F], _F]:
67
+ def decorator(func: _F) -> _F:
68
+ self.handle(methods, path, func)
69
+ return func
70
+ return decorator
71
+
72
+ def get(self, path: str) -> Callable[[_F], _F]:
73
+ return self.route(path, ["GET"])
74
+
75
+ def post(self, path: str) -> Callable[[_F], _F]:
76
+ return self.route(path, ["POST"])
77
+
78
+ def put(self, path: str) -> Callable[[_F], _F]:
79
+ return self.route(path, ["PUT"])
80
+
81
+ def delete(self, path: str) -> Callable[[_F], _F]:
82
+ return self.route(path, ["DELETE"])
83
+
84
+ def patch(self, path: str) -> Callable[[_F], _F]:
85
+ return self.route(path, ["PATCH"])
86
+
87
+ # implemented by App and Group
88
+
89
+ def _add(self, methods: list[str], path: str, handler: Handler) -> None:
90
+ raise NotImplementedError
91
+
92
+ def _group_context(self) -> "tuple[App, str, Group | None]":
93
+ raise NotImplementedError
94
+
95
+
96
+ class Group(Routes):
97
+ """Routes under a common prefix. Created via app.group(...) / group.group(...)."""
98
+
99
+ def __init__(self, app: "App", prefix: str, parent: "Group | None",
100
+ middleware: list[Middleware]) -> None:
101
+ self._app = app
102
+ self._prefix = prefix
103
+ self._parent = parent
104
+ self._middleware = middleware
105
+
106
+ def _all_middleware(self) -> list[Middleware]:
107
+ """Outside in: parent groups first, then this one."""
108
+ outer = self._parent._all_middleware() if self._parent is not None else []
109
+ return outer + self._middleware
110
+
111
+ def _add(self, methods: list[str], path: str, handler: Handler) -> None:
112
+ full = join_path(self._prefix, path)
113
+ for method in methods:
114
+ self._app._routes.append((method, full, handler, self))
115
+
116
+ def _group_context(self) -> "tuple[App, str, Group | None]":
117
+ return self._app, self._prefix, self
118
+
119
+ def __repr__(self) -> str:
120
+ return f"<Group {self._prefix}>"
cyengine/server.py ADDED
@@ -0,0 +1,146 @@
1
+ import asyncio
2
+ from collections.abc import Callable
3
+ import os
4
+ import signal
5
+ from types import ModuleType
6
+ from typing import TYPE_CHECKING
7
+
8
+ if TYPE_CHECKING:
9
+ from cyengine.app import App
10
+
11
+ uvloop: ModuleType | None = None
12
+ try:
13
+ import uvloop as _uvloop
14
+ uvloop = _uvloop
15
+ _UVLOOP = True
16
+ except ImportError:
17
+ _UVLOOP = False
18
+
19
+
20
+ async def serve(app: "App", host: str, port: int, backlog: int = 2048,
21
+ grace: float = 10.0) -> None:
22
+ """
23
+ Start the server and block until SIGINT/SIGTERM.
24
+
25
+ After the signal: stops accepting connections, waits for in-flight requests
26
+ (up to `grace` seconds), closes keep-alive connections and returns control —
27
+ the dependency cleanup code in main() runs next.
28
+ """
29
+ loop = asyncio.get_running_loop()
30
+ app._router = app._build_router()
31
+
32
+ server = await loop.create_server(
33
+ lambda: app._make_protocol(loop),
34
+ host=host,
35
+ port=port,
36
+ # Windows has no SO_REUSEPORT, and asyncio raises if it is requested
37
+ reuse_port=os.name != "nt",
38
+ backlog=backlog,
39
+ )
40
+
41
+ addr = server.sockets[0].getsockname()
42
+ print(f" cyengine http://{addr[0]}:{addr[1]}")
43
+ # the actual loop, not "is uvloop installed": serve() runs in whatever loop called it
44
+ loop_name = type(loop).__module__.split(".")[0]
45
+ hint = "" if loop_name == "uvloop" else " (uvloop is faster: uvloop.run(main()))"
46
+ print(f" loop {loop_name}{hint}")
47
+ print(f" pid {os.getpid()}")
48
+
49
+ sweeper = asyncio.create_task(_sweep(app, loop))
50
+
51
+ stop = asyncio.Event()
52
+ remove_signal_handlers = _on_stop_signal(loop, stop.set)
53
+
54
+ try:
55
+ await stop.wait()
56
+ finally:
57
+ remove_signal_handlers()
58
+ sweeper.cancel()
59
+ await _shutdown(app, server, grace)
60
+
61
+
62
+ async def _sweep(app: "App", loop: asyncio.AbstractEventLoop) -> None:
63
+ """
64
+ A single watchdog timer for the whole server instead of per-request timers:
65
+ once per `interval` it checks read/keep-alive deadlines of connections and
66
+ handler_timeout of requests. The hot path only has to store a number.
67
+ """
68
+ lim = app._limits
69
+ active = [t for t in (lim.read_timeout, lim.keepalive_timeout, lim.handler_timeout)
70
+ if t is not None]
71
+ if not active:
72
+ return
73
+ interval = min(1.0, max(0.05, min(active) / 4))
74
+
75
+ while True:
76
+ await asyncio.sleep(interval)
77
+ now = loop.time()
78
+ for task, deadline in tuple(app._tasks.items()):
79
+ if deadline and now >= deadline and task not in app._timed_out:
80
+ app._timed_out.add(task)
81
+ task.cancel()
82
+ for proto in tuple(app._protocols):
83
+ proto._check_deadline(now)
84
+
85
+
86
+ async def _shutdown(app: "App", server: asyncio.Server, grace: float) -> None:
87
+ server.close()
88
+ for proto in list(app._protocols):
89
+ proto.shutdown()
90
+
91
+ # loop: on a pipelining connection, the next task starts after the previous one
92
+ loop = asyncio.get_running_loop()
93
+ deadline = loop.time() + grace
94
+ while app._tasks and (left := deadline - loop.time()) > 0:
95
+ await asyncio.wait(set(app._tasks), timeout=left)
96
+
97
+ pending = set(app._tasks)
98
+ for task in pending:
99
+ task.cancel()
100
+ if pending:
101
+ await asyncio.gather(*pending, return_exceptions=True)
102
+
103
+ for proto in list(app._protocols):
104
+ proto.close()
105
+
106
+ try:
107
+ await asyncio.wait_for(server.wait_closed(), timeout=5)
108
+ except asyncio.TimeoutError:
109
+ pass
110
+
111
+
112
+ def run(app: "App", host: str = "0.0.0.0", port: int = 8000) -> None:
113
+ """Sync wrapper for applications without dependencies that need closing."""
114
+ coro = serve(app, host, port)
115
+ if _UVLOOP:
116
+ # _UVLOOP is True only when the import above succeeded
117
+ uvloop.run(coro) # type: ignore[union-attr]
118
+ else:
119
+ asyncio.run(coro)
120
+
121
+
122
+ def _on_stop_signal(loop: asyncio.AbstractEventLoop,
123
+ callback: Callable[[], object]) -> Callable[[], None]:
124
+ """
125
+ Call `callback` in the loop on SIGINT/SIGTERM. Returns a function that
126
+ removes the handlers.
127
+ """
128
+ signals = (signal.SIGINT, signal.SIGTERM)
129
+ try:
130
+ for sig in signals:
131
+ loop.add_signal_handler(sig, callback)
132
+ except NotImplementedError:
133
+ # Windows event loops: use the signal module and hop back into the loop
134
+ previous = {
135
+ sig: signal.signal(sig, lambda *_: loop.call_soon_threadsafe(callback))
136
+ for sig in signals
137
+ }
138
+
139
+ def remove() -> None:
140
+ for sig, handler in previous.items():
141
+ signal.signal(sig, handler)
142
+ else:
143
+ def remove() -> None:
144
+ for sig in signals:
145
+ loop.remove_signal_handler(sig)
146
+ return remove
@@ -0,0 +1,46 @@
1
+ Metadata-Version: 2.4
2
+ Name: cyengine
3
+ Version: 0.1.0
4
+ Summary: Async HTTP framework for Python with a Cython core
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/Typesh1t1337/CyEngine
7
+ Project-URL: Repository, https://github.com/Typesh1t1337/CyEngine
8
+ Project-URL: Issues, https://github.com/Typesh1t1337/CyEngine/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Cython
11
+ Classifier: Framework :: AsyncIO
12
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Operating System :: Microsoft :: Windows
16
+ Requires-Python: >=3.11
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: httptools
20
+ Requires-Dist: orjson
21
+ Provides-Extra: uvloop
22
+ Requires-Dist: uvloop; sys_platform != "win32" and extra == "uvloop"
23
+ Provides-Extra: pydantic
24
+ Requires-Dist: pydantic>=2; extra == "pydantic"
25
+ Dynamic: license-file
26
+
27
+ # CyEngine
28
+
29
+ Async HTTP framework for Python with a Cython core.
30
+
31
+ ```bash
32
+ pip install cyengine
33
+ ```
34
+
35
+ ```python
36
+ from cyengine import App, Request, Response
37
+
38
+
39
+ async def hello(request: Request) -> Response:
40
+ return Response.text("Hello, world!")
41
+
42
+
43
+ app = App()
44
+ app.handle("GET", "/", hello)
45
+ app.run(port=8000)
46
+ ```
@@ -0,0 +1,25 @@
1
+ cyengine/__init__.py,sha256=5GyFY9L98CXlDNCuUKkczymLXjnpjICi5vTEZjlLDlc,629
2
+ cyengine/app.py,sha256=FckDdq8djREhi70KHAiO8RzTugl3DoJav30A4epjGdE,6658
3
+ cyengine/errors.py,sha256=-ix8p7rezyVVZRaS_ijEq1lKaoYlGhsZEX0bZlTT7SU,6705
4
+ cyengine/handler.py,sha256=YEayIj_oLh4CJ8sAO3_LUvDyRbM1BdcfvCNpK6ZROQQ,3026
5
+ cyengine/limits.py,sha256=1BgXGcwUdhzhvTmZhviByj_778a6Gz0UBhTD39mGl8M,987
6
+ cyengine/middleware.py,sha256=y3Sjm78hr5Jk1m_RdwM38SVntuUDD8ARzUOff-B7UWE,9155
7
+ cyengine/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ cyengine/routing.py,sha256=M8kr2Lg48bzIVNk1qAtixIzLxt8PL-Fffa6uD2tStx0,4620
9
+ cyengine/server.py,sha256=RivlqeKRrGPYew-wzgMtIhu4aXClAwTdohM7xOvnLr0,4889
10
+ cyengine/core/_middleware.cp313-win_amd64.pyd,sha256=dkaR681gWuJ49Cm-dtTT04Jq1rTD1pocc3owETDdnRU,15872
11
+ cyengine/core/_protocol.cp313-win_amd64.pyd,sha256=bDpsHi5tP23nogWFELx9p9n5wr5hGAvL6vRtKF-VI7E,150528
12
+ cyengine/core/_protocol.pyi,sha256=MoQab9w6E9R-cVGVtnmEb4jdUDo7M6tNaQRuXTJRN64,1231
13
+ cyengine/core/_router.cp313-win_amd64.pyd,sha256=B7YdYfC251JDrnUOhyF5vou0c8rj5CqRxY9xZjSAGDg,89600
14
+ cyengine/core/_router.pyi,sha256=4Fdxobl4t8kng5XeWaWPmoyonaaFJVM4qJfk8O_Xbbk,1250
15
+ cyengine/core/_types.cp313-win_amd64.pyd,sha256=Kmxs8ng2n8DVA1DcbPSfNLccuBYin4KgvV70RuKg7qs,151040
16
+ cyengine/core/_types.pyi,sha256=jcR2R4jFwnq_RxUdmOj2k-pswzmYPYOEoZDdnew-FN0,5593
17
+ cyengine/providers/jwt.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ cyengine/providers/kafka.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ cyengine/providers/postgres.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
+ cyengine/providers/redis.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
+ cyengine-0.1.0.dist-info/licenses/LICENSE,sha256=mw8M2q39T_QvSOlxhMOD6kBfEuweG_8YoB0Q58CbeQU,1083
22
+ cyengine-0.1.0.dist-info/METADATA,sha256=6_zfP1yYHHPqW0YwXG4WcEV1i6muD__SpN402gsjA2w,1333
23
+ cyengine-0.1.0.dist-info/WHEEL,sha256=fOyJWI5N6P4iPL9_doBC3lf0L4Z-hcIkjNV5ilMSlqY,101
24
+ cyengine-0.1.0.dist-info/top_level.txt,sha256=5HaN4_BIlmduu9XqpxFDma8Wcc_JXVUcMAA0a9KWEKw,9
25
+ cyengine-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp313-cp313-win_amd64
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Arnur
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ cyengine