swiftpy-framework 0.1.0__py3-none-any.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.
- swiftpy/.gitignore +0 -0
- swiftpy/__init__.py +572 -0
- swiftpy/admin/__init__.py +50 -0
- swiftpy/admin/auth.py +522 -0
- swiftpy/admin/registry.py +567 -0
- swiftpy/admin/views.py +1583 -0
- swiftpy/ai/__init__.py +199 -0
- swiftpy/ai/_deterministic.py +40 -0
- swiftpy/ai/_fake.py +604 -0
- swiftpy/ai/agents/__init__.py +30 -0
- swiftpy/ai/agents/base_agent.py +506 -0
- swiftpy/ai/agents/memory.py +864 -0
- swiftpy/ai/client.py +1011 -0
- swiftpy/ai/conversation.py +171 -0
- swiftpy/ai/embeddings.py +321 -0
- swiftpy/ai/exceptions.py +75 -0
- swiftpy/ai/history_strategies.py +157 -0
- swiftpy/ai/middleware.py +918 -0
- swiftpy/ai/observability/__init__.py +28 -0
- swiftpy/ai/observability/drivers.py +763 -0
- swiftpy/ai/observability/observer.py +364 -0
- swiftpy/ai/pool.py +102 -0
- swiftpy/ai/pricing.py +101 -0
- swiftpy/ai/prompts/__init__.py +6 -0
- swiftpy/ai/prompts/loader.py +343 -0
- swiftpy/ai/providers/__init__.py +22 -0
- swiftpy/ai/providers/anthropic_provider.py +353 -0
- swiftpy/ai/providers/base.py +273 -0
- swiftpy/ai/providers/openai_provider.py +275 -0
- swiftpy/ai/rag/__init__.py +53 -0
- swiftpy/ai/rag/context_formatter.py +263 -0
- swiftpy/ai/rag/pipeline_builder.py +544 -0
- swiftpy/ai/rag/reranker.py +484 -0
- swiftpy/ai/rag/result.py +78 -0
- swiftpy/ai/rag/retriever.py +315 -0
- swiftpy/ai/redis_store.py +227 -0
- swiftpy/ai/streaming.py +115 -0
- swiftpy/ai/tools/__init__.py +22 -0
- swiftpy/ai/tools/base_tool.py +489 -0
- swiftpy/ai/tools/first_party.py +384 -0
- swiftpy/ai/tools/tool_loop.py +417 -0
- swiftpy/ai/vectorstore/__init__.py +46 -0
- swiftpy/ai/vectorstore/base.py +542 -0
- swiftpy/ai/vectorstore/chroma_adapter.py +435 -0
- swiftpy/ai/vectorstore/in_memory_adapter.py +321 -0
- swiftpy/ai/vectorstore/lancedb_adapter.py +370 -0
- swiftpy/ai/vectorstore/pgvector_adapter.py +496 -0
- swiftpy/ai/vectorstore/pinecone_adapter.py +445 -0
- swiftpy/ai/vectorstore/qdrant_adapter.py +418 -0
- swiftpy/auth/__init__.py +50 -0
- swiftpy/auth/api_key_guard.py +544 -0
- swiftpy/auth/auth_manager.py +259 -0
- swiftpy/auth/exceptions.py +71 -0
- swiftpy/auth/jwt_guard.py +230 -0
- swiftpy/auth/jwt_issuer.py +658 -0
- swiftpy/auth/token_blacklist.py +300 -0
- swiftpy/cache/__init__.py +14 -0
- swiftpy/cache/cache.py +251 -0
- swiftpy/cache/driver.py +216 -0
- swiftpy/cache/drivers/memory.py +199 -0
- swiftpy/cache/drivers/redis.py +421 -0
- swiftpy/console/__init__.py +0 -0
- swiftpy/console/cli.py +68 -0
- swiftpy/console/commands/__init__.py +0 -0
- swiftpy/console/commands/cache.py +164 -0
- swiftpy/console/commands/make.py +935 -0
- swiftpy/console/commands/migrate.py +280 -0
- swiftpy/console/commands/new.py +1806 -0
- swiftpy/console/commands/queue.py +306 -0
- swiftpy/console/commands/seed.py +252 -0
- swiftpy/console/commands/start.py +171 -0
- swiftpy/console/commands/storage.py +104 -0
- swiftpy/console/loader.py +21 -0
- swiftpy/console/stubs/__init__.py +26 -0
- swiftpy/console/stubs/controller.stub +14 -0
- swiftpy/console/stubs/event.stub +14 -0
- swiftpy/console/stubs/job.stub +22 -0
- swiftpy/console/stubs/listener.stub +14 -0
- swiftpy/console/stubs/mail.stub +20 -0
- swiftpy/console/stubs/middleware.stub +16 -0
- swiftpy/console/stubs/migration.alter.stub +17 -0
- swiftpy/console/stubs/migration.api_keys.stub +22 -0
- swiftpy/console/stubs/migration.blank.stub +11 -0
- swiftpy/console/stubs/migration.create.stub +15 -0
- swiftpy/console/stubs/migration.stub +11 -0
- swiftpy/console/stubs/migration.update.stub +17 -0
- swiftpy/console/stubs/model.stub +17 -0
- swiftpy/console/stubs/provider.stub +18 -0
- swiftpy/console/stubs/repository.stub +10 -0
- swiftpy/console/stubs/request.stub +16 -0
- swiftpy/console/stubs/resource.stub +21 -0
- swiftpy/console/stubs/schema.stub +12 -0
- swiftpy/console/stubs/seeder.stub +14 -0
- swiftpy/console/stubs/service.stub +10 -0
- swiftpy/core/__init__.py +0 -0
- swiftpy/core/application.py +1306 -0
- swiftpy/core/bootstrap.py +30 -0
- swiftpy/core/config.py +432 -0
- swiftpy/core/container.py +596 -0
- swiftpy/core/container_exceptions.py +18 -0
- swiftpy/core/context.py +148 -0
- swiftpy/core/exceptions.py +352 -0
- swiftpy/core/providers/base.py +35 -0
- swiftpy/database/__init__.py +41 -0
- swiftpy/database/exceptions.py +42 -0
- swiftpy/database/identifiers.py +105 -0
- swiftpy/database/migrations/__init__.py +36 -0
- swiftpy/database/migrations/blueprint.py +431 -0
- swiftpy/database/migrations/lock.py +104 -0
- swiftpy/database/migrations/migration.py +22 -0
- swiftpy/database/migrations/migrator.py +507 -0
- swiftpy/database/migrations/schema.py +435 -0
- swiftpy/database/orm/__init__.py +33 -0
- swiftpy/database/orm/fields.py +92 -0
- swiftpy/database/orm/model.py +2034 -0
- swiftpy/database/orm/registry.py +33 -0
- swiftpy/database/orm/relationships.py +836 -0
- swiftpy/database/pagination/__init__.py +16 -0
- swiftpy/database/pagination/contracts.py +60 -0
- swiftpy/database/pagination/paginator.py +112 -0
- swiftpy/database/pagination/simple_paginator.py +97 -0
- swiftpy/database/pool.py +218 -0
- swiftpy/database/query_builder.py +1803 -0
- swiftpy/database/seeder.py +39 -0
- swiftpy/database/transaction.py +276 -0
- swiftpy/events/__init__.py +10 -0
- swiftpy/events/dispatcher.py +308 -0
- swiftpy/events/redis_bus.py +552 -0
- swiftpy/filesystem/__init__.py +227 -0
- swiftpy/filesystem/disk.py +378 -0
- swiftpy/filesystem/drivers/__init__.py +11 -0
- swiftpy/filesystem/drivers/base.py +156 -0
- swiftpy/filesystem/drivers/local.py +559 -0
- swiftpy/filesystem/drivers/s3.py +655 -0
- swiftpy/filesystem/events.py +37 -0
- swiftpy/filesystem/exceptions.py +127 -0
- swiftpy/filesystem/manager.py +138 -0
- swiftpy/filesystem/metadata.py +22 -0
- swiftpy/filesystem/paths.py +99 -0
- swiftpy/filesystem/service_provider.py +17 -0
- swiftpy/filesystem/uploads/__init__.py +13 -0
- swiftpy/filesystem/uploads/handlers.py +362 -0
- swiftpy/filesystem/uploads/uploaded_file.py +222 -0
- swiftpy/filesystem/uploads/validators.py +186 -0
- swiftpy/filesystem/visibility.py +22 -0
- swiftpy/helpers/__init__.py +42 -0
- swiftpy/helpers/helper.py +180 -0
- swiftpy/http/exceptions.py +41 -0
- swiftpy/http/middleware.py +307 -0
- swiftpy/http/request.py +375 -0
- swiftpy/http/response.py +442 -0
- swiftpy/http/router.py +1050 -0
- swiftpy/mail/__init__.py +58 -0
- swiftpy/mail/attachments.py +255 -0
- swiftpy/mail/config.py +71 -0
- swiftpy/mail/envelope.py +183 -0
- swiftpy/mail/exceptions.py +90 -0
- swiftpy/mail/facade.py +312 -0
- swiftpy/mail/mailable.py +53 -0
- swiftpy/mail/manager.py +240 -0
- swiftpy/mail/message.py +186 -0
- swiftpy/mail/models.py +19 -0
- swiftpy/mail/queue/__init__.py +5 -0
- swiftpy/mail/queue/job.py +279 -0
- swiftpy/mail/service_provider.py +19 -0
- swiftpy/mail/templates/__init__.py +5 -0
- swiftpy/mail/templates/renderer.py +173 -0
- swiftpy/mail/transports/__init__.py +21 -0
- swiftpy/mail/transports/api/__init__.py +13 -0
- swiftpy/mail/transports/api/base.py +194 -0
- swiftpy/mail/transports/api/mailgun.py +158 -0
- swiftpy/mail/transports/api/resend.py +156 -0
- swiftpy/mail/transports/api/sendgrid.py +172 -0
- swiftpy/mail/transports/base.py +24 -0
- swiftpy/mail/transports/console.py +91 -0
- swiftpy/mail/transports/sendmail.py +128 -0
- swiftpy/mail/transports/smtp.py +466 -0
- swiftpy/queue/__init__.py +13 -0
- swiftpy/queue/dispatcher.py +813 -0
- swiftpy/queue/job.py +541 -0
- swiftpy/queue/worker.py +556 -0
- swiftpy/support/__init__.py +12 -0
- swiftpy/support/keys.py +108 -0
- swiftpy/support/redis_config.py +223 -0
- swiftpy/support/strings.py +114 -0
- swiftpy/testing/__init__.py +20 -0
- swiftpy/testing/fakes/__init__.py +11 -0
- swiftpy/testing/fakes/ai_fake.py +21 -0
- swiftpy/testing/fakes/vectorstore_fake.py +194 -0
- swiftpy/testing/fixtures.py +124 -0
- swiftpy/testing/http_client.py +730 -0
- swiftpy/testing/test_case.py +126 -0
- swiftpy/validation/__init__.py +97 -0
- swiftpy/validation/exceptions.py +26 -0
- swiftpy/validation/form_request.py +302 -0
- swiftpy/validation/protocols.py +33 -0
- swiftpy/validation/rules/__init__.py +89 -0
- swiftpy/validation/rules/builtin.py +391 -0
- swiftpy/validation/rules/exists.py +86 -0
- swiftpy/validation/rules/registry.py +290 -0
- swiftpy/validation/rules/required.py +55 -0
- swiftpy/validation/rules/unique.py +138 -0
- swiftpy/validation/validator.py +612 -0
- swiftpy/websockets/__init__.py +19 -0
- swiftpy/websockets/connection.py +317 -0
- swiftpy/websockets/manager.py +271 -0
- swiftpy_framework-0.1.0.dist-info/METADATA +603 -0
- swiftpy_framework-0.1.0.dist-info/RECORD +211 -0
- swiftpy_framework-0.1.0.dist-info/WHEEL +4 -0
- swiftpy_framework-0.1.0.dist-info/entry_points.txt +2 -0
- swiftpy_framework-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1306 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
import inspect
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
9
|
+
from importlib.util import module_from_spec, spec_from_file_location
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Self, TypeVar
|
|
12
|
+
from urllib.parse import urlsplit
|
|
13
|
+
|
|
14
|
+
from swiftpy.ai.pool import AIHttpPool
|
|
15
|
+
from swiftpy.auth.auth_manager import AuthManager, CurrentUser
|
|
16
|
+
from swiftpy.auth.exceptions import AuthenticationError
|
|
17
|
+
from swiftpy.auth.jwt_issuer import JWTIssuer
|
|
18
|
+
from swiftpy.auth.token_blacklist import TokenBlacklist, is_token_blacklist_enabled
|
|
19
|
+
from swiftpy.cache.cache import Cache
|
|
20
|
+
from swiftpy.core.config import Config, ConfigurationError
|
|
21
|
+
from swiftpy.core.container import Container, bind_container, set_container
|
|
22
|
+
from swiftpy.core.context import Context
|
|
23
|
+
from swiftpy.core.exceptions import ExceptionHandler
|
|
24
|
+
from swiftpy.core.providers.base import ServiceProvider
|
|
25
|
+
from swiftpy.database.pool import DatabasePool
|
|
26
|
+
from swiftpy.events.dispatcher import EventDispatcher
|
|
27
|
+
from swiftpy.events.redis_bus import RedisEventBus
|
|
28
|
+
from swiftpy.filesystem.manager import FilesystemManager
|
|
29
|
+
from swiftpy.http.exceptions import ClientDisconnect, HttpException
|
|
30
|
+
from swiftpy.http.middleware import Middleware, MiddlewarePipeline
|
|
31
|
+
from swiftpy.http.request import (
|
|
32
|
+
DEFAULT_MAX_BODY_SIZE,
|
|
33
|
+
DEFAULT_MAX_JSON_DEPTH,
|
|
34
|
+
Request,
|
|
35
|
+
)
|
|
36
|
+
from swiftpy.http.response import (
|
|
37
|
+
Response,
|
|
38
|
+
json_response,
|
|
39
|
+
not_found,
|
|
40
|
+
)
|
|
41
|
+
from swiftpy.http.router import PathParamCoercionError, Route, RouteGroup, Router
|
|
42
|
+
from swiftpy.mail.manager import MailManager
|
|
43
|
+
from swiftpy.queue.dispatcher import QueueDispatcher
|
|
44
|
+
from swiftpy.support.keys import (
|
|
45
|
+
resolve_configured_app_key,
|
|
46
|
+
validate_signing_key,
|
|
47
|
+
)
|
|
48
|
+
from swiftpy.validation.exceptions import ValidationException
|
|
49
|
+
from swiftpy.validation.form_request import FormRequest
|
|
50
|
+
from swiftpy.validation.validator import validate
|
|
51
|
+
from swiftpy.websockets.connection import (
|
|
52
|
+
WebSocketConnection,
|
|
53
|
+
WebSocketDisconnect,
|
|
54
|
+
WebSocketState,
|
|
55
|
+
)
|
|
56
|
+
from swiftpy.websockets.manager import WebSocketManager
|
|
57
|
+
|
|
58
|
+
logger = logging.getLogger("swiftpy")
|
|
59
|
+
|
|
60
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class FrameworkServiceProvider(ServiceProvider):
|
|
64
|
+
"""
|
|
65
|
+
Built-in framework service provider managing core infrastructure lifecycle:
|
|
66
|
+
- Initializes and closes `DatabasePool` (when database configuration is present).
|
|
67
|
+
- Stops `RedisEventBus` and closes Redis clients (`Cache`, `QueueDispatcher`, `TokenBlacklist`).
|
|
68
|
+
- Closes active WebSocket connections with code 1001 (`Going Away`) on shutdown.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def register(self) -> None:
|
|
72
|
+
if self.container.has(Config):
|
|
73
|
+
cfg = self.container.resolve(Config)
|
|
74
|
+
db_cfg = cfg.get("database")
|
|
75
|
+
if (
|
|
76
|
+
isinstance(db_cfg, dict)
|
|
77
|
+
and (db_cfg.get("connections") or db_cfg.get("default"))
|
|
78
|
+
and not self.container.has(DatabasePool)
|
|
79
|
+
):
|
|
80
|
+
self.container.singleton(DatabasePool)
|
|
81
|
+
|
|
82
|
+
if not self.container.has(JWTIssuer):
|
|
83
|
+
self.container.singleton(
|
|
84
|
+
JWTIssuer,
|
|
85
|
+
lambda c: JWTIssuer.from_config(
|
|
86
|
+
c.resolve(Config) if c.has(Config) else None
|
|
87
|
+
),
|
|
88
|
+
)
|
|
89
|
+
auth_cfg: Config | None = (
|
|
90
|
+
self.container.resolve(Config) if self.container.has(Config) else None
|
|
91
|
+
)
|
|
92
|
+
if not self.container.has(TokenBlacklist) and is_token_blacklist_enabled(
|
|
93
|
+
auth_cfg
|
|
94
|
+
):
|
|
95
|
+
self.container.singleton(
|
|
96
|
+
TokenBlacklist,
|
|
97
|
+
lambda c: TokenBlacklist(
|
|
98
|
+
config=c.resolve(Config) if c.has(Config) else None,
|
|
99
|
+
container=c,
|
|
100
|
+
),
|
|
101
|
+
)
|
|
102
|
+
if not self.container.has(AuthManager):
|
|
103
|
+
self.container.singleton(AuthManager, lambda c: AuthManager(c))
|
|
104
|
+
if not self.container.has(QueueDispatcher):
|
|
105
|
+
self.container.singleton(QueueDispatcher, lambda _: QueueDispatcher())
|
|
106
|
+
if not self.container.has(EventDispatcher):
|
|
107
|
+
self.container.singleton(EventDispatcher, lambda _: EventDispatcher())
|
|
108
|
+
if not self.container.has(RedisEventBus):
|
|
109
|
+
self.container.singleton(
|
|
110
|
+
RedisEventBus,
|
|
111
|
+
lambda c: RedisEventBus(
|
|
112
|
+
dispatcher=c.resolve(EventDispatcher)
|
|
113
|
+
if c.has(EventDispatcher)
|
|
114
|
+
else None
|
|
115
|
+
),
|
|
116
|
+
)
|
|
117
|
+
if not self.container.has(Cache):
|
|
118
|
+
self.container.singleton(
|
|
119
|
+
Cache,
|
|
120
|
+
lambda c: Cache(config=c.resolve(Config) if c.has(Config) else None),
|
|
121
|
+
)
|
|
122
|
+
if not self.container.has(MailManager):
|
|
123
|
+
self.container.singleton(
|
|
124
|
+
MailManager,
|
|
125
|
+
lambda c: MailManager(
|
|
126
|
+
config=c.resolve(Config) if c.has(Config) else None
|
|
127
|
+
),
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
async def startup(self) -> None:
|
|
131
|
+
if self.container.has(Config) and self.container.has(DatabasePool):
|
|
132
|
+
cfg = self.container.resolve(Config)
|
|
133
|
+
db_cfg = cfg.get("database")
|
|
134
|
+
if isinstance(db_cfg, dict) and (
|
|
135
|
+
db_cfg.get("connections") or db_cfg.get("default")
|
|
136
|
+
):
|
|
137
|
+
pool = self.container.resolve(DatabasePool)
|
|
138
|
+
await pool.init()
|
|
139
|
+
|
|
140
|
+
if self.container.has(RedisEventBus) and self.container.has(WebSocketManager):
|
|
141
|
+
bus = self.container.resolve(RedisEventBus)
|
|
142
|
+
ws_manager = self.container.resolve(WebSocketManager)
|
|
143
|
+
ws_manager.subscribe_to_bus(bus)
|
|
144
|
+
|
|
145
|
+
async def shutdown(self) -> None:
|
|
146
|
+
# 1. Close active WebSocket connections with 1001 (Going Away)
|
|
147
|
+
ws_manager = self.container.get_singleton(WebSocketManager)
|
|
148
|
+
bus = self.container.get_singleton(RedisEventBus)
|
|
149
|
+
if isinstance(ws_manager, WebSocketManager):
|
|
150
|
+
if isinstance(bus, RedisEventBus):
|
|
151
|
+
ws_manager.unsubscribe_from_bus(bus)
|
|
152
|
+
for conn in list(ws_manager.get_connections()):
|
|
153
|
+
try:
|
|
154
|
+
if conn.is_connected:
|
|
155
|
+
await conn.close(code=1001, reason="Server shutting down")
|
|
156
|
+
except Exception:
|
|
157
|
+
logger.exception("Error closing WebSocket connection during shutdown")
|
|
158
|
+
try:
|
|
159
|
+
await ws_manager.disconnect(conn)
|
|
160
|
+
except Exception:
|
|
161
|
+
logger.exception(
|
|
162
|
+
"Error disconnecting WebSocket connection during shutdown"
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
# 2. Stop RedisEventBus and close its Redis connection
|
|
166
|
+
if isinstance(bus, RedisEventBus):
|
|
167
|
+
try:
|
|
168
|
+
await bus.close()
|
|
169
|
+
except Exception:
|
|
170
|
+
logger.exception("Error closing RedisEventBus during shutdown")
|
|
171
|
+
|
|
172
|
+
# 3. Close background clients (Cache, QueueDispatcher, TokenBlacklist, FilesystemManager, MailManager)
|
|
173
|
+
for service_cls in (
|
|
174
|
+
Cache,
|
|
175
|
+
QueueDispatcher,
|
|
176
|
+
TokenBlacklist,
|
|
177
|
+
FilesystemManager,
|
|
178
|
+
MailManager,
|
|
179
|
+
):
|
|
180
|
+
inst = self.container.get_singleton(service_cls)
|
|
181
|
+
if inst is not None and hasattr(inst, "close"):
|
|
182
|
+
try:
|
|
183
|
+
await inst.close()
|
|
184
|
+
except Exception:
|
|
185
|
+
logger.exception(
|
|
186
|
+
"Error closing %s during shutdown", service_cls.__name__
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
# 4. Close AIHttpPool (container singleton and global fallback if any)
|
|
190
|
+
closed_ai_pools: set[int] = set()
|
|
191
|
+
ai_pool = self.container.get_singleton(AIHttpPool)
|
|
192
|
+
if isinstance(ai_pool, AIHttpPool):
|
|
193
|
+
closed_ai_pools.add(id(ai_pool))
|
|
194
|
+
try:
|
|
195
|
+
await ai_pool.aclose()
|
|
196
|
+
except Exception:
|
|
197
|
+
logger.exception("Error closing AIHttpPool during shutdown")
|
|
198
|
+
global_ai_pool = AIHttpPool._instance
|
|
199
|
+
if isinstance(global_ai_pool, AIHttpPool) and id(global_ai_pool) not in closed_ai_pools:
|
|
200
|
+
try:
|
|
201
|
+
await global_ai_pool.aclose()
|
|
202
|
+
except Exception:
|
|
203
|
+
logger.exception("Error closing global AIHttpPool during shutdown")
|
|
204
|
+
|
|
205
|
+
# 5. Close DatabasePool
|
|
206
|
+
pool = self.container.get_singleton(DatabasePool)
|
|
207
|
+
if isinstance(pool, DatabasePool):
|
|
208
|
+
try:
|
|
209
|
+
await pool.close()
|
|
210
|
+
except Exception:
|
|
211
|
+
logger.exception("Error closing DatabasePool during shutdown")
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _deep_merge_config(target: dict[str, Any], updates: Mapping[str, Any]) -> None:
|
|
215
|
+
"""Merge `updates` into `target` in-place, giving `updates` top precedence."""
|
|
216
|
+
for key, val in updates.items():
|
|
217
|
+
if isinstance(val, Mapping) and isinstance(target.get(key), dict):
|
|
218
|
+
_deep_merge_config(target[key], val)
|
|
219
|
+
elif isinstance(val, Mapping):
|
|
220
|
+
target[key] = dict(val)
|
|
221
|
+
else:
|
|
222
|
+
target[key] = val
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def discover_providers(
|
|
226
|
+
providers_path: str | Path | None = None,
|
|
227
|
+
*,
|
|
228
|
+
project_root: str | Path | None = None,
|
|
229
|
+
strict: bool = True,
|
|
230
|
+
) -> list[type[ServiceProvider]]:
|
|
231
|
+
"""
|
|
232
|
+
Dynamically discover all ServiceProvider subclasses in the application providers directory.
|
|
233
|
+
Imports providers by package path (`app.providers.<name>`) relative to `project_root`
|
|
234
|
+
without leaking `root` into `sys.path`.
|
|
235
|
+
When `strict=True` (the default), import or syntax errors in provider modules raise `ConfigurationError`.
|
|
236
|
+
"""
|
|
237
|
+
if project_root is not None:
|
|
238
|
+
root = Path(project_root).resolve()
|
|
239
|
+
elif providers_path is not None:
|
|
240
|
+
resolved_prov = Path(providers_path).resolve()
|
|
241
|
+
if resolved_prov.name == "providers" and resolved_prov.parent.name == "app":
|
|
242
|
+
root = resolved_prov.parent.parent
|
|
243
|
+
else:
|
|
244
|
+
root = Path.cwd().resolve()
|
|
245
|
+
else:
|
|
246
|
+
root = Path.cwd().resolve()
|
|
247
|
+
|
|
248
|
+
if providers_path is not None:
|
|
249
|
+
target_dir = Path(providers_path)
|
|
250
|
+
if not target_dir.is_absolute():
|
|
251
|
+
target_dir = (root / target_dir).resolve()
|
|
252
|
+
else:
|
|
253
|
+
target_dir = target_dir.resolve()
|
|
254
|
+
else:
|
|
255
|
+
target_dir = (root / "app" / "providers").resolve()
|
|
256
|
+
|
|
257
|
+
if not target_dir.is_dir():
|
|
258
|
+
return []
|
|
259
|
+
|
|
260
|
+
discovered: list[type[ServiceProvider]] = []
|
|
261
|
+
|
|
262
|
+
for file in sorted(target_dir.glob("*.py")):
|
|
263
|
+
if file.name.startswith(("_", ".")):
|
|
264
|
+
continue
|
|
265
|
+
|
|
266
|
+
resolved_file = file.resolve()
|
|
267
|
+
package_module_name: str | None = None
|
|
268
|
+
try:
|
|
269
|
+
rel_path = resolved_file.relative_to(root).with_suffix("")
|
|
270
|
+
if len(rel_path.parts) >= 2:
|
|
271
|
+
package_module_name = ".".join(rel_path.parts)
|
|
272
|
+
except ValueError:
|
|
273
|
+
package_module_name = None
|
|
274
|
+
|
|
275
|
+
can_use_package_import = False
|
|
276
|
+
if package_module_name is not None:
|
|
277
|
+
top_pkg = package_module_name.split(".", 1)[0]
|
|
278
|
+
existing_top = sys.modules.get(top_pkg)
|
|
279
|
+
if existing_top is None:
|
|
280
|
+
can_use_package_import = True
|
|
281
|
+
else:
|
|
282
|
+
top_file = getattr(existing_top, "__file__", None)
|
|
283
|
+
top_paths = getattr(existing_top, "__path__", None)
|
|
284
|
+
if (top_file and Path(top_file).resolve().is_relative_to(root)) or (
|
|
285
|
+
top_paths
|
|
286
|
+
and any(Path(p).resolve().is_relative_to(root) for p in top_paths)
|
|
287
|
+
):
|
|
288
|
+
can_use_package_import = True
|
|
289
|
+
|
|
290
|
+
display_name = package_module_name or file.stem
|
|
291
|
+
try:
|
|
292
|
+
if can_use_package_import and package_module_name is not None:
|
|
293
|
+
root_str = str(root)
|
|
294
|
+
inserted_root = False
|
|
295
|
+
if root_str not in sys.path:
|
|
296
|
+
sys.path.insert(0, root_str)
|
|
297
|
+
inserted_root = True
|
|
298
|
+
try:
|
|
299
|
+
mod = importlib.import_module(package_module_name)
|
|
300
|
+
finally:
|
|
301
|
+
if inserted_root and root_str in sys.path:
|
|
302
|
+
sys.path.remove(root_str)
|
|
303
|
+
else:
|
|
304
|
+
synthetic_name = f"_swiftpy_providers.{file.stem}"
|
|
305
|
+
spec = spec_from_file_location(synthetic_name, resolved_file)
|
|
306
|
+
if spec is None or spec.loader is None:
|
|
307
|
+
continue
|
|
308
|
+
mod = module_from_spec(spec)
|
|
309
|
+
sys.modules[synthetic_name] = mod
|
|
310
|
+
try:
|
|
311
|
+
spec.loader.exec_module(mod)
|
|
312
|
+
except Exception:
|
|
313
|
+
sys.modules.pop(synthetic_name, None)
|
|
314
|
+
raise
|
|
315
|
+
except Exception as exc:
|
|
316
|
+
if strict:
|
|
317
|
+
raise ConfigurationError(
|
|
318
|
+
f"Failed to load service provider '{file.stem}' ({display_name}): {exc}"
|
|
319
|
+
) from exc
|
|
320
|
+
logger.warning(
|
|
321
|
+
"Could not auto-load provider module %s: %s", display_name, exc
|
|
322
|
+
)
|
|
323
|
+
continue
|
|
324
|
+
|
|
325
|
+
for attr_name in dir(mod):
|
|
326
|
+
attr = getattr(mod, attr_name)
|
|
327
|
+
if (
|
|
328
|
+
isinstance(attr, type)
|
|
329
|
+
and issubclass(attr, ServiceProvider)
|
|
330
|
+
and attr is not ServiceProvider
|
|
331
|
+
and attr not in discovered
|
|
332
|
+
):
|
|
333
|
+
discovered.append(attr)
|
|
334
|
+
|
|
335
|
+
# Ensure AppServiceProvider is loaded first if present
|
|
336
|
+
discovered.sort(key=lambda cls: 0 if cls.__name__ == "AppServiceProvider" else 1)
|
|
337
|
+
return discovered
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
class Application:
|
|
341
|
+
"""
|
|
342
|
+
Root SwiftPY application.
|
|
343
|
+
"""
|
|
344
|
+
|
|
345
|
+
def __init__(
|
|
346
|
+
self,
|
|
347
|
+
title: str = "SwiftPY Application",
|
|
348
|
+
version: str = "0.1.0",
|
|
349
|
+
debug: bool | None = None,
|
|
350
|
+
config: dict[str, Any] | Config | None = None,
|
|
351
|
+
providers: Sequence[type[ServiceProvider]] | None = None,
|
|
352
|
+
middleware: Sequence[type[Middleware]] | None = None,
|
|
353
|
+
auto_discover_providers: bool = True,
|
|
354
|
+
providers_path: str | Path | None = None,
|
|
355
|
+
project_root: str | Path | None = None,
|
|
356
|
+
strict_providers: bool = True,
|
|
357
|
+
max_body_size: int | None = None,
|
|
358
|
+
max_content_length: int | None = None,
|
|
359
|
+
max_json_depth: int | None = None,
|
|
360
|
+
allowed_origins: Sequence[str] | set[str] | None = None,
|
|
361
|
+
max_ws_message_size: int | None = None,
|
|
362
|
+
ws_idle_timeout: float | None = None,
|
|
363
|
+
**kwargs: Any,
|
|
364
|
+
) -> None:
|
|
365
|
+
self.title = title
|
|
366
|
+
self.version = version
|
|
367
|
+
self.debug = debug
|
|
368
|
+
self.extra = kwargs
|
|
369
|
+
|
|
370
|
+
self.container = Container()
|
|
371
|
+
self.router = Router(container=self.container)
|
|
372
|
+
self._providers: list[ServiceProvider] = []
|
|
373
|
+
self._started_providers: list[ServiceProvider] = []
|
|
374
|
+
self._middleware: list[type[Middleware]] = list(middleware or [])
|
|
375
|
+
self._booted = False
|
|
376
|
+
self._started = False
|
|
377
|
+
|
|
378
|
+
# 1. Load or bind configuration
|
|
379
|
+
if config is None:
|
|
380
|
+
config_dir = (
|
|
381
|
+
Path(project_root) / "config" if project_root is not None else "config"
|
|
382
|
+
)
|
|
383
|
+
self.config = Config.load(config_dir)
|
|
384
|
+
elif isinstance(config, Config):
|
|
385
|
+
self.config = config
|
|
386
|
+
else:
|
|
387
|
+
self.config = Config(config)
|
|
388
|
+
|
|
389
|
+
# Merge additional kwargs into config (explicit kwargs always take top precedence)
|
|
390
|
+
if kwargs:
|
|
391
|
+
_deep_merge_config(self.config._data, kwargs)
|
|
392
|
+
|
|
393
|
+
cfg_max_body = self.config.get("http.max_body_size")
|
|
394
|
+
if max_body_size is not None:
|
|
395
|
+
self.max_body_size: int = int(max_body_size)
|
|
396
|
+
elif cfg_max_body is not None:
|
|
397
|
+
self.max_body_size = int(cfg_max_body)
|
|
398
|
+
else:
|
|
399
|
+
self.max_body_size = DEFAULT_MAX_BODY_SIZE
|
|
400
|
+
|
|
401
|
+
cfg_max_content = self.config.get("http.max_content_length")
|
|
402
|
+
if max_content_length is not None:
|
|
403
|
+
self.max_content_length: int | None = int(max_content_length)
|
|
404
|
+
elif cfg_max_content is not None:
|
|
405
|
+
self.max_content_length = int(cfg_max_content)
|
|
406
|
+
else:
|
|
407
|
+
self.max_content_length = None
|
|
408
|
+
|
|
409
|
+
cfg_max_depth = self.config.get("http.max_json_depth")
|
|
410
|
+
if max_json_depth is not None:
|
|
411
|
+
self.max_json_depth: int = int(max_json_depth)
|
|
412
|
+
elif cfg_max_depth is not None:
|
|
413
|
+
self.max_json_depth = int(cfg_max_depth)
|
|
414
|
+
else:
|
|
415
|
+
self.max_json_depth = DEFAULT_MAX_JSON_DEPTH
|
|
416
|
+
|
|
417
|
+
# WebSocket origin, message size, and idle timeout limits (D-14, P9-W1, P9-W2, WS-2)
|
|
418
|
+
if allowed_origins is not None:
|
|
419
|
+
raw_allowed_origins = allowed_origins
|
|
420
|
+
elif self.config.has("websockets.allowed_origins"):
|
|
421
|
+
raw_allowed_origins = self.config.get("websockets.allowed_origins")
|
|
422
|
+
else:
|
|
423
|
+
raw_allowed_origins = self.config.get("websocket.allowed_origins")
|
|
424
|
+
|
|
425
|
+
if raw_allowed_origins is not None:
|
|
426
|
+
if isinstance(raw_allowed_origins, str):
|
|
427
|
+
self.allowed_origins: set[str] | None = {
|
|
428
|
+
o.strip() for o in raw_allowed_origins.split(",") if o.strip()
|
|
429
|
+
}
|
|
430
|
+
else:
|
|
431
|
+
self.allowed_origins = set(raw_allowed_origins)
|
|
432
|
+
else:
|
|
433
|
+
self.allowed_origins = None
|
|
434
|
+
|
|
435
|
+
if max_ws_message_size is not None:
|
|
436
|
+
self.max_ws_message_size: int = int(max_ws_message_size)
|
|
437
|
+
else:
|
|
438
|
+
cfg_ws_max = (
|
|
439
|
+
self.config.get("websockets.max_message_size")
|
|
440
|
+
if self.config.has("websockets.max_message_size")
|
|
441
|
+
else self.config.get("websocket.max_message_size")
|
|
442
|
+
)
|
|
443
|
+
self.max_ws_message_size = (
|
|
444
|
+
int(cfg_ws_max) if cfg_ws_max is not None else 1_048_576
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
if ws_idle_timeout is not None:
|
|
448
|
+
self.ws_idle_timeout: float | None = float(ws_idle_timeout)
|
|
449
|
+
else:
|
|
450
|
+
cfg_ws_idle = (
|
|
451
|
+
self.config.get("websockets.idle_timeout")
|
|
452
|
+
if self.config.has("websockets.idle_timeout")
|
|
453
|
+
else self.config.get("websocket.idle_timeout")
|
|
454
|
+
)
|
|
455
|
+
self.ws_idle_timeout = (
|
|
456
|
+
float(cfg_ws_idle) if cfg_ws_idle is not None else None
|
|
457
|
+
)
|
|
458
|
+
|
|
459
|
+
# 2. Configure debug mode and exception handler (refuse debug=True in production)
|
|
460
|
+
app_env = (
|
|
461
|
+
str(self.config.get("app.env") or self.config.get("env") or "development")
|
|
462
|
+
.strip()
|
|
463
|
+
.lower()
|
|
464
|
+
)
|
|
465
|
+
if debug is not None:
|
|
466
|
+
self.debug = bool(debug)
|
|
467
|
+
else:
|
|
468
|
+
cfg_debug = self.config.get("app.debug")
|
|
469
|
+
if cfg_debug is None:
|
|
470
|
+
cfg_debug = self.config.get("debug", False)
|
|
471
|
+
self.debug = bool(cfg_debug)
|
|
472
|
+
|
|
473
|
+
if self.debug and app_env in ("production", "prod"):
|
|
474
|
+
raise ConfigurationError(
|
|
475
|
+
"Cannot enable debug mode (debug=True) when APP_ENV is 'production'."
|
|
476
|
+
)
|
|
477
|
+
|
|
478
|
+
self.exception_handler = ExceptionHandler(debug=self.debug)
|
|
479
|
+
|
|
480
|
+
# 3. Register core singletons and default scoped bindings into container
|
|
481
|
+
self.websocket_manager = WebSocketManager()
|
|
482
|
+
self.container.instance(Application, self)
|
|
483
|
+
self.container.instance(Container, self.container)
|
|
484
|
+
self.container.instance(Router, self.router)
|
|
485
|
+
self.container.instance(Config, self.config)
|
|
486
|
+
self.container.instance(ExceptionHandler, self.exception_handler)
|
|
487
|
+
self.container.instance(WebSocketManager, self.websocket_manager)
|
|
488
|
+
self.container.scoped(
|
|
489
|
+
CurrentUser,
|
|
490
|
+
lambda _: CurrentUser(),
|
|
491
|
+
)
|
|
492
|
+
|
|
493
|
+
# 4. Bind active container globally
|
|
494
|
+
set_container(self.container)
|
|
495
|
+
|
|
496
|
+
# 5. Register built-in framework lifecycle provider first (starts first, shuts down last)
|
|
497
|
+
self.register(FrameworkServiceProvider)
|
|
498
|
+
|
|
499
|
+
# 6. Auto-discover and register service providers from app/providers
|
|
500
|
+
if auto_discover_providers:
|
|
501
|
+
discovered = discover_providers(
|
|
502
|
+
providers_path,
|
|
503
|
+
project_root=project_root,
|
|
504
|
+
strict=strict_providers,
|
|
505
|
+
)
|
|
506
|
+
for provider_cls in discovered:
|
|
507
|
+
self.register(provider_cls)
|
|
508
|
+
|
|
509
|
+
# 7. Register explicitly passed service providers
|
|
510
|
+
if providers:
|
|
511
|
+
for provider_cls in providers:
|
|
512
|
+
if not any(isinstance(p, provider_cls) for p in self._providers):
|
|
513
|
+
self.register(provider_cls)
|
|
514
|
+
|
|
515
|
+
def register(self, provider_class: type[ServiceProvider]) -> ServiceProvider:
|
|
516
|
+
"""Instantiate and register a service provider."""
|
|
517
|
+
provider = provider_class(self.container)
|
|
518
|
+
provider.register()
|
|
519
|
+
self._providers.append(provider)
|
|
520
|
+
|
|
521
|
+
if self._booted:
|
|
522
|
+
provider.boot()
|
|
523
|
+
|
|
524
|
+
return provider
|
|
525
|
+
|
|
526
|
+
def boot(self) -> None:
|
|
527
|
+
"""
|
|
528
|
+
Boot all registered service providers once all bindings are configured.
|
|
529
|
+
"""
|
|
530
|
+
if self._booted:
|
|
531
|
+
return
|
|
532
|
+
|
|
533
|
+
for provider in self._providers:
|
|
534
|
+
provider.boot()
|
|
535
|
+
|
|
536
|
+
self._booted = True
|
|
537
|
+
self._compile_routes()
|
|
538
|
+
|
|
539
|
+
async def startup(self) -> None:
|
|
540
|
+
"""
|
|
541
|
+
Execute asynchronous startup hooks on all registered service providers in registration order.
|
|
542
|
+
If any provider fails to start, already-started providers are shut down in reverse order.
|
|
543
|
+
"""
|
|
544
|
+
if self._started:
|
|
545
|
+
return
|
|
546
|
+
|
|
547
|
+
app_env = (
|
|
548
|
+
str(self.config.get("app.env") or self.config.get("env") or "development")
|
|
549
|
+
.strip()
|
|
550
|
+
.lower()
|
|
551
|
+
)
|
|
552
|
+
configured_app_key = resolve_configured_app_key(self.config)
|
|
553
|
+
if app_env in ("production", "prod") or configured_app_key is not None:
|
|
554
|
+
validate_signing_key(configured_app_key, purpose="APP_KEY")
|
|
555
|
+
|
|
556
|
+
with bind_container(self.container):
|
|
557
|
+
if not self._booted:
|
|
558
|
+
self.boot()
|
|
559
|
+
|
|
560
|
+
started: list[ServiceProvider] = []
|
|
561
|
+
try:
|
|
562
|
+
for provider in self._providers:
|
|
563
|
+
await provider.startup()
|
|
564
|
+
started.append(provider)
|
|
565
|
+
except Exception:
|
|
566
|
+
for provider in reversed(started):
|
|
567
|
+
try:
|
|
568
|
+
await provider.shutdown()
|
|
569
|
+
except Exception:
|
|
570
|
+
logger.exception(
|
|
571
|
+
"Error rolling back provider %s after startup failure",
|
|
572
|
+
type(provider).__name__,
|
|
573
|
+
)
|
|
574
|
+
raise
|
|
575
|
+
|
|
576
|
+
self._started_providers = started
|
|
577
|
+
self._started = True
|
|
578
|
+
|
|
579
|
+
async def shutdown(self) -> None:
|
|
580
|
+
"""
|
|
581
|
+
Execute asynchronous shutdown hooks in reverse registration order.
|
|
582
|
+
Errors in individual providers are logged and do not block remaining shutdown hooks.
|
|
583
|
+
"""
|
|
584
|
+
with bind_container(self.container):
|
|
585
|
+
providers_to_stop = (
|
|
586
|
+
list(reversed(self._started_providers))
|
|
587
|
+
if self._started_providers
|
|
588
|
+
else list(reversed(self._providers))
|
|
589
|
+
)
|
|
590
|
+
self._started_providers = []
|
|
591
|
+
self._started = False
|
|
592
|
+
|
|
593
|
+
for provider in providers_to_stop:
|
|
594
|
+
try:
|
|
595
|
+
await provider.shutdown()
|
|
596
|
+
except Exception:
|
|
597
|
+
logger.exception(
|
|
598
|
+
"Error during shutdown of provider %s", type(provider).__name__
|
|
599
|
+
)
|
|
600
|
+
|
|
601
|
+
def _wrap_handler(self, route: Route) -> Any:
|
|
602
|
+
handler = route.handler
|
|
603
|
+
param_specs = self.router.ensure_route_analyzed(route)
|
|
604
|
+
has_var_keyword = route.has_var_keyword
|
|
605
|
+
is_coro = inspect.iscoroutinefunction(handler)
|
|
606
|
+
|
|
607
|
+
async def dispatched_handler(
|
|
608
|
+
request: Request, *args: Any, **params: Any
|
|
609
|
+
) -> Response:
|
|
610
|
+
try:
|
|
611
|
+
call_kwargs: dict[str, Any] = {}
|
|
612
|
+
for spec in param_specs:
|
|
613
|
+
if spec.kind == "request":
|
|
614
|
+
call_kwargs[spec.name] = request
|
|
615
|
+
elif spec.kind == "path":
|
|
616
|
+
call_kwargs[spec.name] = params[spec.name]
|
|
617
|
+
elif spec.kind == "form":
|
|
618
|
+
ann: type[FormRequest] = spec.annotation
|
|
619
|
+
content_type = request.headers.get("content-type", "")
|
|
620
|
+
media_type = content_type.split(";", 1)[0].strip().lower()
|
|
621
|
+
|
|
622
|
+
if media_type in (
|
|
623
|
+
"application/x-www-form-urlencoded",
|
|
624
|
+
"multipart/form-data",
|
|
625
|
+
):
|
|
626
|
+
if media_type == "application/x-www-form-urlencoded":
|
|
627
|
+
raw_body = await request.body()
|
|
628
|
+
if not raw_body.strip():
|
|
629
|
+
raise ValidationException(
|
|
630
|
+
{"body": ["Request body is required."]}
|
|
631
|
+
)
|
|
632
|
+
try:
|
|
633
|
+
form_data = await request.form()
|
|
634
|
+
except HttpException as exc:
|
|
635
|
+
if exc.status_code == 400:
|
|
636
|
+
raise ValidationException(
|
|
637
|
+
{"body": [exc.message]}
|
|
638
|
+
) from None
|
|
639
|
+
raise
|
|
640
|
+
except (ValueError, UnicodeDecodeError) as exc:
|
|
641
|
+
raise ValidationException(
|
|
642
|
+
{"body": [str(exc)]}
|
|
643
|
+
) from None
|
|
644
|
+
|
|
645
|
+
if (
|
|
646
|
+
media_type == "multipart/form-data"
|
|
647
|
+
and not form_data.fields_list
|
|
648
|
+
and not form_data.files_list
|
|
649
|
+
):
|
|
650
|
+
raise ValidationException(
|
|
651
|
+
{"body": ["Request body is required."]}
|
|
652
|
+
)
|
|
653
|
+
|
|
654
|
+
data: dict[str, Any] = {}
|
|
655
|
+
for k, vals in form_data.fields_list.items():
|
|
656
|
+
data[k] = vals[0] if len(vals) == 1 else list(vals)
|
|
657
|
+
for k, flist in form_data.files_list.items():
|
|
658
|
+
if k not in data:
|
|
659
|
+
data[k] = flist[0] if len(flist) == 1 else list(flist)
|
|
660
|
+
else:
|
|
661
|
+
raw_body = await request.body()
|
|
662
|
+
if not raw_body.strip():
|
|
663
|
+
raise ValidationException(
|
|
664
|
+
{"body": ["Request body is required."]}
|
|
665
|
+
)
|
|
666
|
+
try:
|
|
667
|
+
raw_data = await request.json()
|
|
668
|
+
if not isinstance(raw_data, dict):
|
|
669
|
+
raise ValidationException(
|
|
670
|
+
{
|
|
671
|
+
"body": [
|
|
672
|
+
"The request payload must be a JSON object."
|
|
673
|
+
]
|
|
674
|
+
}
|
|
675
|
+
)
|
|
676
|
+
data = raw_data
|
|
677
|
+
except (
|
|
678
|
+
json.JSONDecodeError,
|
|
679
|
+
UnicodeDecodeError,
|
|
680
|
+
ValueError,
|
|
681
|
+
):
|
|
682
|
+
raise ValidationException(
|
|
683
|
+
{"body": ["Invalid JSON payload"]}
|
|
684
|
+
) from None
|
|
685
|
+
except HttpException as exc:
|
|
686
|
+
if (
|
|
687
|
+
exc.status_code == 400
|
|
688
|
+
and exc.message == "Invalid JSON payload"
|
|
689
|
+
):
|
|
690
|
+
raise ValidationException(
|
|
691
|
+
{"body": ["Invalid JSON payload"]}
|
|
692
|
+
) from None
|
|
693
|
+
raise
|
|
694
|
+
|
|
695
|
+
form_instance, rules, messages = ann.prepare_validation(
|
|
696
|
+
request=request, container=self.container
|
|
697
|
+
)
|
|
698
|
+
result = await validate(data, rules, messages=messages)
|
|
699
|
+
if result.fails():
|
|
700
|
+
raise ValidationException(result.errors)
|
|
701
|
+
|
|
702
|
+
form_instance.data = result.validated_data
|
|
703
|
+
form_instance.raw_data = data
|
|
704
|
+
form_instance.request = request
|
|
705
|
+
form_instance.validation_result = result
|
|
706
|
+
call_kwargs[spec.name] = form_instance
|
|
707
|
+
elif spec.kind == "di":
|
|
708
|
+
call_kwargs[spec.name] = self.container.resolve(spec.annotation)
|
|
709
|
+
elif spec.kind == "file":
|
|
710
|
+
call_kwargs[spec.name] = await request.file(spec.name)
|
|
711
|
+
elif spec.kind == "files":
|
|
712
|
+
call_kwargs[spec.name] = await request.files(spec.name)
|
|
713
|
+
elif spec.kind == "default" and spec.name in params:
|
|
714
|
+
call_kwargs[spec.name] = params[spec.name]
|
|
715
|
+
|
|
716
|
+
if has_var_keyword:
|
|
717
|
+
for k, v in params.items():
|
|
718
|
+
if k not in call_kwargs:
|
|
719
|
+
call_kwargs[k] = v
|
|
720
|
+
|
|
721
|
+
if is_coro:
|
|
722
|
+
res = await handler(**call_kwargs)
|
|
723
|
+
else:
|
|
724
|
+
res = handler(**call_kwargs)
|
|
725
|
+
if inspect.isawaitable(res):
|
|
726
|
+
res = await res
|
|
727
|
+
|
|
728
|
+
if isinstance(res, Response):
|
|
729
|
+
return res
|
|
730
|
+
if isinstance(res, (dict, list)):
|
|
731
|
+
return json_response(res)
|
|
732
|
+
raise TypeError(
|
|
733
|
+
f"Route handler must return a Response, dict, or list, got {type(res).__name__}"
|
|
734
|
+
)
|
|
735
|
+
except ClientDisconnect:
|
|
736
|
+
raise
|
|
737
|
+
except Exception as exc: # noqa: BLE001
|
|
738
|
+
return await self._handle_exception_safely(exc, request=request)
|
|
739
|
+
|
|
740
|
+
return dispatched_handler
|
|
741
|
+
|
|
742
|
+
def _wrap_websocket_handler(self, route: Route) -> Any:
|
|
743
|
+
handler = route.handler
|
|
744
|
+
param_specs = self.router.ensure_route_analyzed(route)
|
|
745
|
+
has_var_keyword = route.has_var_keyword
|
|
746
|
+
is_coro = inspect.iscoroutinefunction(handler)
|
|
747
|
+
|
|
748
|
+
async def dispatched_ws_handler(
|
|
749
|
+
websocket: WebSocketConnection, *args: Any, **params: Any
|
|
750
|
+
) -> Any:
|
|
751
|
+
call_kwargs: dict[str, Any] = {}
|
|
752
|
+
for spec in param_specs:
|
|
753
|
+
if spec.kind == "websocket":
|
|
754
|
+
call_kwargs[spec.name] = websocket
|
|
755
|
+
elif spec.kind == "path":
|
|
756
|
+
call_kwargs[spec.name] = params[spec.name]
|
|
757
|
+
elif spec.kind == "di":
|
|
758
|
+
call_kwargs[spec.name] = self.container.resolve(spec.annotation)
|
|
759
|
+
elif spec.kind == "default" and spec.name in params:
|
|
760
|
+
call_kwargs[spec.name] = params[spec.name]
|
|
761
|
+
|
|
762
|
+
if has_var_keyword:
|
|
763
|
+
for k, v in params.items():
|
|
764
|
+
if k not in call_kwargs:
|
|
765
|
+
call_kwargs[k] = v
|
|
766
|
+
|
|
767
|
+
if is_coro:
|
|
768
|
+
return await handler(**call_kwargs)
|
|
769
|
+
res = handler(**call_kwargs)
|
|
770
|
+
if inspect.isawaitable(res):
|
|
771
|
+
return await res
|
|
772
|
+
return res
|
|
773
|
+
|
|
774
|
+
return dispatched_ws_handler
|
|
775
|
+
|
|
776
|
+
@staticmethod
|
|
777
|
+
def _parse_origin(raw: str) -> tuple[str, str, int] | None:
|
|
778
|
+
"""Parse an HTTP/HTTPS Origin into (scheme, host, port), rejecting malformed values."""
|
|
779
|
+
cleaned = raw.strip()
|
|
780
|
+
if not cleaned or any(ch.isspace() for ch in cleaned):
|
|
781
|
+
return None
|
|
782
|
+
try:
|
|
783
|
+
parsed = urlsplit(cleaned)
|
|
784
|
+
port = parsed.port
|
|
785
|
+
except ValueError:
|
|
786
|
+
return None
|
|
787
|
+
scheme = parsed.scheme.lower()
|
|
788
|
+
if scheme not in {"http", "https"}:
|
|
789
|
+
return None
|
|
790
|
+
if parsed.username is not None or parsed.password is not None:
|
|
791
|
+
return None
|
|
792
|
+
if parsed.query or parsed.fragment or parsed.path not in {"", "/"}:
|
|
793
|
+
return None
|
|
794
|
+
host = parsed.hostname
|
|
795
|
+
if not host:
|
|
796
|
+
return None
|
|
797
|
+
effective_port = port if port is not None else (443 if scheme == "https" else 80)
|
|
798
|
+
return scheme, host.lower(), effective_port
|
|
799
|
+
|
|
800
|
+
@staticmethod
|
|
801
|
+
def _parse_host_authority(
|
|
802
|
+
raw_host: str, *, default_port: int
|
|
803
|
+
) -> tuple[str, int, bool] | None:
|
|
804
|
+
"""Parse a Host header authority into (host, port, has_explicit_port)."""
|
|
805
|
+
cleaned = raw_host.strip()
|
|
806
|
+
if not cleaned or any(ch.isspace() for ch in cleaned):
|
|
807
|
+
return None
|
|
808
|
+
try:
|
|
809
|
+
parsed = urlsplit(f"//{cleaned}")
|
|
810
|
+
port = parsed.port
|
|
811
|
+
except ValueError:
|
|
812
|
+
return None
|
|
813
|
+
if parsed.username is not None or parsed.password is not None:
|
|
814
|
+
return None
|
|
815
|
+
if parsed.path or parsed.query or parsed.fragment:
|
|
816
|
+
return None
|
|
817
|
+
host = parsed.hostname
|
|
818
|
+
if not host:
|
|
819
|
+
return None
|
|
820
|
+
return host.lower(), (port if port is not None else default_port), port is not None
|
|
821
|
+
|
|
822
|
+
def _is_origin_allowed(
|
|
823
|
+
self,
|
|
824
|
+
origin: str | None,
|
|
825
|
+
host_header: str | None,
|
|
826
|
+
scope: dict[str, Any] | None = None,
|
|
827
|
+
) -> bool:
|
|
828
|
+
"""
|
|
829
|
+
Validate incoming WebSocket Origin against allowed_origins or same-origin policy (Decision D-14).
|
|
830
|
+
If origin is None (non-browser clients like mobile/CLI/tests without Origin), allow.
|
|
831
|
+
If allowed_origins is configured:
|
|
832
|
+
- If "*" in allowed_origins: allow all.
|
|
833
|
+
- If origin matches a configured origin URL or authority: allow.
|
|
834
|
+
If allowed_origins is not configured (default None):
|
|
835
|
+
- Enforce same-origin: origin scheme, host, and port must match the request scheme and Host.
|
|
836
|
+
"""
|
|
837
|
+
if origin is None:
|
|
838
|
+
return True
|
|
839
|
+
|
|
840
|
+
parsed_origin = self._parse_origin(origin)
|
|
841
|
+
if parsed_origin is None:
|
|
842
|
+
return False
|
|
843
|
+
|
|
844
|
+
if self.allowed_origins is not None:
|
|
845
|
+
if "*" in self.allowed_origins:
|
|
846
|
+
return True
|
|
847
|
+
_, origin_host, origin_port = parsed_origin
|
|
848
|
+
for allowed in self.allowed_origins:
|
|
849
|
+
entry = allowed.strip()
|
|
850
|
+
if not entry:
|
|
851
|
+
continue
|
|
852
|
+
if "://" in entry:
|
|
853
|
+
if self._parse_origin(entry) == parsed_origin:
|
|
854
|
+
return True
|
|
855
|
+
continue
|
|
856
|
+
parsed_entry = self._parse_host_authority(
|
|
857
|
+
entry, default_port=origin_port
|
|
858
|
+
)
|
|
859
|
+
if parsed_entry is None:
|
|
860
|
+
continue
|
|
861
|
+
entry_host, entry_port, has_explicit_port = parsed_entry
|
|
862
|
+
if origin_host == entry_host and (
|
|
863
|
+
not has_explicit_port or origin_port == entry_port
|
|
864
|
+
):
|
|
865
|
+
return True
|
|
866
|
+
return False
|
|
867
|
+
|
|
868
|
+
effective_host = host_header
|
|
869
|
+
if not effective_host and scope:
|
|
870
|
+
server_info = scope.get("server")
|
|
871
|
+
if server_info and len(server_info) == 2:
|
|
872
|
+
s_host, s_port = server_info
|
|
873
|
+
s_host_str = str(s_host)
|
|
874
|
+
if ":" in s_host_str and not s_host_str.startswith("["):
|
|
875
|
+
s_host_str = f"[{s_host_str}]"
|
|
876
|
+
effective_host = (
|
|
877
|
+
f"{s_host_str}:{s_port}"
|
|
878
|
+
if s_port not in (80, 443, None)
|
|
879
|
+
else s_host_str
|
|
880
|
+
)
|
|
881
|
+
|
|
882
|
+
if not effective_host:
|
|
883
|
+
return False
|
|
884
|
+
|
|
885
|
+
raw_scheme = str((scope or {}).get("scheme", "ws")).lower()
|
|
886
|
+
expected_scheme = "https" if raw_scheme in {"wss", "https"} else "http"
|
|
887
|
+
default_port = 443 if expected_scheme == "https" else 80
|
|
888
|
+
parsed_host = self._parse_host_authority(
|
|
889
|
+
effective_host, default_port=default_port
|
|
890
|
+
)
|
|
891
|
+
if parsed_host is None:
|
|
892
|
+
return False
|
|
893
|
+
host_name, host_port, _ = parsed_host
|
|
894
|
+
return parsed_origin == (expected_scheme, host_name, host_port)
|
|
895
|
+
|
|
896
|
+
def _compile_http_handler(self, route: Route) -> Any:
|
|
897
|
+
wrapped = self._wrap_handler(route)
|
|
898
|
+
pipeline = MiddlewarePipeline(self.container, route.middleware)
|
|
899
|
+
return pipeline.wrap(
|
|
900
|
+
wrapped,
|
|
901
|
+
exception_handler=self._handle_exception_safely,
|
|
902
|
+
)
|
|
903
|
+
|
|
904
|
+
def _compile_routes(self) -> None:
|
|
905
|
+
for route in self.router.routes:
|
|
906
|
+
self.router.ensure_route_analyzed(route)
|
|
907
|
+
if route.is_websocket or route.method == "WEBSOCKET":
|
|
908
|
+
route.compiled_handler = self._wrap_websocket_handler(route)
|
|
909
|
+
else:
|
|
910
|
+
route.compiled_handler = self._compile_http_handler(route)
|
|
911
|
+
|
|
912
|
+
def websocket(self, path: str) -> Callable[[F], F]:
|
|
913
|
+
return self.router.websocket(path)
|
|
914
|
+
|
|
915
|
+
def get(
|
|
916
|
+
self,
|
|
917
|
+
path: str,
|
|
918
|
+
*,
|
|
919
|
+
max_body_size: int | None = None,
|
|
920
|
+
max_content_length: int | None = None,
|
|
921
|
+
max_json_depth: int | None = None,
|
|
922
|
+
) -> Callable[[F], F]:
|
|
923
|
+
return self.router.get(
|
|
924
|
+
path,
|
|
925
|
+
max_body_size=max_body_size,
|
|
926
|
+
max_content_length=max_content_length,
|
|
927
|
+
max_json_depth=max_json_depth,
|
|
928
|
+
)
|
|
929
|
+
|
|
930
|
+
def post(
|
|
931
|
+
self,
|
|
932
|
+
path: str,
|
|
933
|
+
*,
|
|
934
|
+
max_body_size: int | None = None,
|
|
935
|
+
max_content_length: int | None = None,
|
|
936
|
+
max_json_depth: int | None = None,
|
|
937
|
+
) -> Callable[[F], F]:
|
|
938
|
+
return self.router.post(
|
|
939
|
+
path,
|
|
940
|
+
max_body_size=max_body_size,
|
|
941
|
+
max_content_length=max_content_length,
|
|
942
|
+
max_json_depth=max_json_depth,
|
|
943
|
+
)
|
|
944
|
+
|
|
945
|
+
def put(
|
|
946
|
+
self,
|
|
947
|
+
path: str,
|
|
948
|
+
*,
|
|
949
|
+
max_body_size: int | None = None,
|
|
950
|
+
max_content_length: int | None = None,
|
|
951
|
+
max_json_depth: int | None = None,
|
|
952
|
+
) -> Callable[[F], F]:
|
|
953
|
+
return self.router.put(
|
|
954
|
+
path,
|
|
955
|
+
max_body_size=max_body_size,
|
|
956
|
+
max_content_length=max_content_length,
|
|
957
|
+
max_json_depth=max_json_depth,
|
|
958
|
+
)
|
|
959
|
+
|
|
960
|
+
def patch(
|
|
961
|
+
self,
|
|
962
|
+
path: str,
|
|
963
|
+
*,
|
|
964
|
+
max_body_size: int | None = None,
|
|
965
|
+
max_content_length: int | None = None,
|
|
966
|
+
max_json_depth: int | None = None,
|
|
967
|
+
) -> Callable[[F], F]:
|
|
968
|
+
return self.router.patch(
|
|
969
|
+
path,
|
|
970
|
+
max_body_size=max_body_size,
|
|
971
|
+
max_content_length=max_content_length,
|
|
972
|
+
max_json_depth=max_json_depth,
|
|
973
|
+
)
|
|
974
|
+
|
|
975
|
+
def delete(
|
|
976
|
+
self,
|
|
977
|
+
path: str,
|
|
978
|
+
*,
|
|
979
|
+
max_body_size: int | None = None,
|
|
980
|
+
max_content_length: int | None = None,
|
|
981
|
+
max_json_depth: int | None = None,
|
|
982
|
+
) -> Callable[[F], F]:
|
|
983
|
+
return self.router.delete(
|
|
984
|
+
path,
|
|
985
|
+
max_body_size=max_body_size,
|
|
986
|
+
max_content_length=max_content_length,
|
|
987
|
+
max_json_depth=max_json_depth,
|
|
988
|
+
)
|
|
989
|
+
|
|
990
|
+
def head(
|
|
991
|
+
self,
|
|
992
|
+
path: str,
|
|
993
|
+
*,
|
|
994
|
+
max_body_size: int | None = None,
|
|
995
|
+
max_content_length: int | None = None,
|
|
996
|
+
max_json_depth: int | None = None,
|
|
997
|
+
) -> Callable[[F], F]:
|
|
998
|
+
return self.router.head(
|
|
999
|
+
path,
|
|
1000
|
+
max_body_size=max_body_size,
|
|
1001
|
+
max_content_length=max_content_length,
|
|
1002
|
+
max_json_depth=max_json_depth,
|
|
1003
|
+
)
|
|
1004
|
+
|
|
1005
|
+
def options(
|
|
1006
|
+
self,
|
|
1007
|
+
path: str,
|
|
1008
|
+
*,
|
|
1009
|
+
max_body_size: int | None = None,
|
|
1010
|
+
max_content_length: int | None = None,
|
|
1011
|
+
max_json_depth: int | None = None,
|
|
1012
|
+
) -> Callable[[F], F]:
|
|
1013
|
+
return self.router.options(
|
|
1014
|
+
path,
|
|
1015
|
+
max_body_size=max_body_size,
|
|
1016
|
+
max_content_length=max_content_length,
|
|
1017
|
+
max_json_depth=max_json_depth,
|
|
1018
|
+
)
|
|
1019
|
+
|
|
1020
|
+
def middleware(self, middleware_list: Sequence[type[Middleware]]) -> Self:
|
|
1021
|
+
"""Register global HTTP middleware classes that run for every HTTP request."""
|
|
1022
|
+
self._middleware.extend(middleware_list)
|
|
1023
|
+
return self
|
|
1024
|
+
|
|
1025
|
+
def group(
|
|
1026
|
+
self,
|
|
1027
|
+
prefix: str,
|
|
1028
|
+
middleware: list[type[Any]] | None = None,
|
|
1029
|
+
) -> Callable[[Callable[[RouteGroup], None]], Callable[[RouteGroup], None]]:
|
|
1030
|
+
return self.router.group(prefix, middleware=middleware)
|
|
1031
|
+
|
|
1032
|
+
def include_router(
|
|
1033
|
+
self,
|
|
1034
|
+
router: Router,
|
|
1035
|
+
prefix: str = "",
|
|
1036
|
+
middleware: list[type[Any]] | None = None,
|
|
1037
|
+
) -> None:
|
|
1038
|
+
"""
|
|
1039
|
+
Mount a child router under an optional prefix and middleware pipeline.
|
|
1040
|
+
"""
|
|
1041
|
+
self.router.include_router(router, prefix=prefix, middleware=middleware)
|
|
1042
|
+
if self._booted:
|
|
1043
|
+
self._compile_routes()
|
|
1044
|
+
|
|
1045
|
+
def exception_handler_for(
|
|
1046
|
+
self, exc_type: type[Any]
|
|
1047
|
+
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
|
1048
|
+
"""Decorator to register a custom exception handler."""
|
|
1049
|
+
|
|
1050
|
+
def decorator(handler: Callable[..., Any]) -> Callable[..., Any]:
|
|
1051
|
+
self.exception_handler.register(exc_type, handler)
|
|
1052
|
+
return handler
|
|
1053
|
+
|
|
1054
|
+
return decorator
|
|
1055
|
+
|
|
1056
|
+
async def _handle_exception_safely(
|
|
1057
|
+
self,
|
|
1058
|
+
exc: Exception,
|
|
1059
|
+
request: Request | None = None,
|
|
1060
|
+
) -> Response:
|
|
1061
|
+
try:
|
|
1062
|
+
return await self.exception_handler.handle(exc, request=request)
|
|
1063
|
+
except Exception:
|
|
1064
|
+
logger.exception("ExceptionHandler.handle raised an unhandled error")
|
|
1065
|
+
return json_response(
|
|
1066
|
+
{"detail": "Internal Server Error"},
|
|
1067
|
+
status_code=500,
|
|
1068
|
+
)
|
|
1069
|
+
|
|
1070
|
+
async def _dispatch_http(self, request: Request) -> Response:
|
|
1071
|
+
try:
|
|
1072
|
+
route, params = self.router.match(request.method, request.path)
|
|
1073
|
+
if route is None:
|
|
1074
|
+
return not_found()
|
|
1075
|
+
|
|
1076
|
+
if route.max_body_size is not None:
|
|
1077
|
+
request.max_body_size = route.max_body_size
|
|
1078
|
+
if route.max_content_length is not None:
|
|
1079
|
+
request.max_content_length = route.max_content_length
|
|
1080
|
+
if route.max_json_depth is not None:
|
|
1081
|
+
request.max_json_depth = route.max_json_depth
|
|
1082
|
+
|
|
1083
|
+
handler = route.compiled_handler
|
|
1084
|
+
if handler is None:
|
|
1085
|
+
handler = self._compile_http_handler(route)
|
|
1086
|
+
route.compiled_handler = handler
|
|
1087
|
+
|
|
1088
|
+
res: Response = await handler(request, **params)
|
|
1089
|
+
return res
|
|
1090
|
+
except ClientDisconnect:
|
|
1091
|
+
raise
|
|
1092
|
+
except Exception as exc: # noqa: BLE001
|
|
1093
|
+
return await self._handle_exception_safely(exc, request=request)
|
|
1094
|
+
|
|
1095
|
+
async def __call__(
|
|
1096
|
+
self,
|
|
1097
|
+
scope: dict[str, Any],
|
|
1098
|
+
receive: Callable[[], Awaitable[dict[str, Any]]],
|
|
1099
|
+
send: Callable[[dict[str, Any]], Awaitable[None]],
|
|
1100
|
+
) -> None:
|
|
1101
|
+
try:
|
|
1102
|
+
if scope["type"] == "lifespan":
|
|
1103
|
+
while True:
|
|
1104
|
+
message = await receive()
|
|
1105
|
+
if message["type"] == "lifespan.startup":
|
|
1106
|
+
try:
|
|
1107
|
+
await self.startup()
|
|
1108
|
+
await send({"type": "lifespan.startup.complete"})
|
|
1109
|
+
except Exception as exc:
|
|
1110
|
+
logger.exception("Lifespan startup failed")
|
|
1111
|
+
await send(
|
|
1112
|
+
{
|
|
1113
|
+
"type": "lifespan.startup.failed",
|
|
1114
|
+
"message": str(exc),
|
|
1115
|
+
}
|
|
1116
|
+
)
|
|
1117
|
+
return
|
|
1118
|
+
elif message["type"] == "lifespan.shutdown":
|
|
1119
|
+
await self.shutdown()
|
|
1120
|
+
await send({"type": "lifespan.shutdown.complete"})
|
|
1121
|
+
return
|
|
1122
|
+
|
|
1123
|
+
if scope["type"] == "websocket":
|
|
1124
|
+
if not self._booted:
|
|
1125
|
+
self.boot()
|
|
1126
|
+
|
|
1127
|
+
with bind_container(self.container):
|
|
1128
|
+
connection = WebSocketConnection(
|
|
1129
|
+
scope,
|
|
1130
|
+
receive,
|
|
1131
|
+
send,
|
|
1132
|
+
max_message_size=self.max_ws_message_size,
|
|
1133
|
+
idle_timeout=self.ws_idle_timeout,
|
|
1134
|
+
)
|
|
1135
|
+
Context.set("websocket", connection)
|
|
1136
|
+
try:
|
|
1137
|
+
try:
|
|
1138
|
+
route, params = self.router.match_websocket(connection.path)
|
|
1139
|
+
except PathParamCoercionError:
|
|
1140
|
+
await connection.close(code=1002, reason="Invalid path parameter")
|
|
1141
|
+
return
|
|
1142
|
+
|
|
1143
|
+
if route is None:
|
|
1144
|
+
await connection.close(code=1000, reason="Not Found")
|
|
1145
|
+
return
|
|
1146
|
+
|
|
1147
|
+
# 1. Origin validation (Decision D-14)
|
|
1148
|
+
host_header = connection.headers.get("host")
|
|
1149
|
+
if not self._is_origin_allowed(connection.origin, host_header, connection.scope):
|
|
1150
|
+
await connection.close(code=1008, reason="Origin not allowed")
|
|
1151
|
+
return
|
|
1152
|
+
|
|
1153
|
+
# 2. Handshake middleware pipeline (P9-W1)
|
|
1154
|
+
# Global middleware + route group middleware
|
|
1155
|
+
all_middleware = list(self._middleware) + list(route.middleware)
|
|
1156
|
+
if all_middleware:
|
|
1157
|
+
handshake_request = Request(
|
|
1158
|
+
scope,
|
|
1159
|
+
receive,
|
|
1160
|
+
max_body_size=self.max_body_size,
|
|
1161
|
+
max_content_length=self.max_content_length,
|
|
1162
|
+
max_json_depth=self.max_json_depth,
|
|
1163
|
+
)
|
|
1164
|
+
Context.set("request", handshake_request)
|
|
1165
|
+
|
|
1166
|
+
pipeline = MiddlewarePipeline(self.container, all_middleware)
|
|
1167
|
+
|
|
1168
|
+
async def _handshake_terminal(req: Request) -> Response:
|
|
1169
|
+
return Response("OK", status_code=200)
|
|
1170
|
+
|
|
1171
|
+
try:
|
|
1172
|
+
entry = pipeline.wrap(_handshake_terminal)
|
|
1173
|
+
resp = await entry(handshake_request)
|
|
1174
|
+
if resp.status_code >= 400:
|
|
1175
|
+
await connection.close(code=1008, reason="Unauthorized")
|
|
1176
|
+
return
|
|
1177
|
+
# Propagate request state to connection state
|
|
1178
|
+
connection.state.update(handshake_request.state)
|
|
1179
|
+
except (AuthenticationError, HttpException):
|
|
1180
|
+
await connection.close(code=1008, reason="Unauthorized")
|
|
1181
|
+
return
|
|
1182
|
+
except Exception:
|
|
1183
|
+
logger.exception("Error in WebSocket handshake middleware")
|
|
1184
|
+
await connection.close(code=1008, reason="Handshake error")
|
|
1185
|
+
return
|
|
1186
|
+
|
|
1187
|
+
handler = route.compiled_handler
|
|
1188
|
+
if handler is None:
|
|
1189
|
+
handler = self._wrap_websocket_handler(route)
|
|
1190
|
+
route.compiled_handler = handler
|
|
1191
|
+
|
|
1192
|
+
try:
|
|
1193
|
+
await handler(connection, **params)
|
|
1194
|
+
if connection.is_connected:
|
|
1195
|
+
await connection.close(code=1000)
|
|
1196
|
+
except WebSocketDisconnect as exc:
|
|
1197
|
+
logger.debug("WebSocket disconnected: %s", exc)
|
|
1198
|
+
except Exception:
|
|
1199
|
+
if connection.client_state == WebSocketState.CONNECTING:
|
|
1200
|
+
# Handler raised before accept() -> policy violation / forbidden close code 1008
|
|
1201
|
+
await connection.close(code=1008, reason="Policy Violation")
|
|
1202
|
+
else:
|
|
1203
|
+
logger.exception("Unhandled exception in WebSocket handler")
|
|
1204
|
+
if connection.is_connected:
|
|
1205
|
+
await connection.close(code=1011, reason="Internal Server Error")
|
|
1206
|
+
finally:
|
|
1207
|
+
try:
|
|
1208
|
+
await self.websocket_manager.disconnect(connection)
|
|
1209
|
+
except Exception:
|
|
1210
|
+
logger.exception("Error disconnecting WebSocket from manager in finally")
|
|
1211
|
+
if connection.is_connected:
|
|
1212
|
+
try:
|
|
1213
|
+
await connection.close(code=1000)
|
|
1214
|
+
except Exception: # noqa: BLE001, S110
|
|
1215
|
+
pass
|
|
1216
|
+
await self.container.aclose_scoped()
|
|
1217
|
+
Context.clear()
|
|
1218
|
+
return
|
|
1219
|
+
|
|
1220
|
+
if scope["type"] != "http":
|
|
1221
|
+
return
|
|
1222
|
+
|
|
1223
|
+
if not self._booted:
|
|
1224
|
+
self.boot()
|
|
1225
|
+
|
|
1226
|
+
with bind_container(self.container):
|
|
1227
|
+
request: Request | None = None
|
|
1228
|
+
response_started = False
|
|
1229
|
+
|
|
1230
|
+
async def tracked_send(message: dict[str, Any]) -> None:
|
|
1231
|
+
nonlocal response_started
|
|
1232
|
+
if message.get("type") == "http.response.start":
|
|
1233
|
+
response_started = True
|
|
1234
|
+
await send(message)
|
|
1235
|
+
|
|
1236
|
+
try:
|
|
1237
|
+
request = Request(
|
|
1238
|
+
scope,
|
|
1239
|
+
receive,
|
|
1240
|
+
max_body_size=self.max_body_size,
|
|
1241
|
+
max_content_length=self.max_content_length,
|
|
1242
|
+
max_json_depth=self.max_json_depth,
|
|
1243
|
+
)
|
|
1244
|
+
Context.set("request", request)
|
|
1245
|
+
send_body = request.method.upper() != "HEAD"
|
|
1246
|
+
|
|
1247
|
+
if self._middleware:
|
|
1248
|
+
pipeline = MiddlewarePipeline(self.container, self._middleware)
|
|
1249
|
+
entry = pipeline.wrap(
|
|
1250
|
+
self._dispatch_http,
|
|
1251
|
+
exception_handler=self._handle_exception_safely,
|
|
1252
|
+
)
|
|
1253
|
+
response = await entry(request)
|
|
1254
|
+
else:
|
|
1255
|
+
response = await self._dispatch_http(request)
|
|
1256
|
+
|
|
1257
|
+
try:
|
|
1258
|
+
await response.send(tracked_send, send_body=send_body)
|
|
1259
|
+
except ClientDisconnect:
|
|
1260
|
+
raise
|
|
1261
|
+
except Exception as exc:
|
|
1262
|
+
logger.exception("Error while sending HTTP response")
|
|
1263
|
+
if not response_started:
|
|
1264
|
+
fallback = await self._handle_exception_safely(
|
|
1265
|
+
exc, request=request
|
|
1266
|
+
)
|
|
1267
|
+
for hdr_name, hdr_val in response.headers.raw_items():
|
|
1268
|
+
lower_hdr = hdr_name.lower()
|
|
1269
|
+
if (
|
|
1270
|
+
lower_hdr == "vary"
|
|
1271
|
+
or lower_hdr.startswith("access-control-")
|
|
1272
|
+
) and hdr_name not in fallback.headers:
|
|
1273
|
+
fallback.headers[hdr_name] = hdr_val
|
|
1274
|
+
await fallback.send(tracked_send, send_body=send_body)
|
|
1275
|
+
|
|
1276
|
+
except ClientDisconnect:
|
|
1277
|
+
logger.debug("Client disconnected before request completed")
|
|
1278
|
+
return
|
|
1279
|
+
except Exception as exc: # noqa: BLE001
|
|
1280
|
+
if not response_started:
|
|
1281
|
+
fallback = await self._handle_exception_safely(
|
|
1282
|
+
exc, request=request
|
|
1283
|
+
)
|
|
1284
|
+
try:
|
|
1285
|
+
fallback_send_body = (
|
|
1286
|
+
request.method.upper() != "HEAD"
|
|
1287
|
+
if request is not None
|
|
1288
|
+
else True
|
|
1289
|
+
)
|
|
1290
|
+
await fallback.send(
|
|
1291
|
+
tracked_send, send_body=fallback_send_body
|
|
1292
|
+
)
|
|
1293
|
+
except ClientDisconnect:
|
|
1294
|
+
logger.debug(
|
|
1295
|
+
"Client disconnected before fallback response completed"
|
|
1296
|
+
)
|
|
1297
|
+
|
|
1298
|
+
finally:
|
|
1299
|
+
if request is not None:
|
|
1300
|
+
await request.close()
|
|
1301
|
+
if scope.get("type") == "http":
|
|
1302
|
+
await self.container.aclose_scoped()
|
|
1303
|
+
Context.clear()
|
|
1304
|
+
|
|
1305
|
+
except Exception:
|
|
1306
|
+
logger.exception("Fatal error in ASGI dispatch")
|