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,186 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
from swiftpy.filesystem.exceptions import (
|
|
8
|
+
FileTooLargeError,
|
|
9
|
+
FileValidationError,
|
|
10
|
+
InvalidFileExtensionError,
|
|
11
|
+
InvalidMimeTypeError,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from swiftpy.filesystem.uploads.uploaded_file import UploadedFile
|
|
16
|
+
|
|
17
|
+
_SIZE_PATTERN = re.compile(r"^(\d+(?:\.\d+)?)\s*([a-zA-Z]+)?$")
|
|
18
|
+
|
|
19
|
+
_SIZE_MULTIPLIERS = {
|
|
20
|
+
"b": 1,
|
|
21
|
+
"bytes": 1,
|
|
22
|
+
"k": 1024,
|
|
23
|
+
"kb": 1024,
|
|
24
|
+
"kib": 1024,
|
|
25
|
+
"m": 1024 * 1024,
|
|
26
|
+
"mb": 1024 * 1024,
|
|
27
|
+
"mib": 1024 * 1024,
|
|
28
|
+
"g": 1024 * 1024 * 1024,
|
|
29
|
+
"gb": 1024 * 1024 * 1024,
|
|
30
|
+
"gib": 1024 * 1024 * 1024,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
MAGIC_BYTE_SIGNATURES: dict[str, list[bytes]] = {
|
|
34
|
+
"image/jpeg": [b"\xff\xd8\xff"],
|
|
35
|
+
"image/jpg": [b"\xff\xd8\xff"],
|
|
36
|
+
"image/png": [b"\x89PNG\r\n\x1a\n"],
|
|
37
|
+
"image/gif": [b"GIF87a", b"GIF89a"],
|
|
38
|
+
"application/pdf": [b"%PDF-"],
|
|
39
|
+
"application/zip": [b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08"],
|
|
40
|
+
"application/x-zip-compressed": [b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08"],
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
_EXTENSION_MIME_MAP: dict[str, tuple[str, ...]] = {
|
|
44
|
+
"jpg": ("image/jpeg", "image/jpg"),
|
|
45
|
+
"jpeg": ("image/jpeg", "image/jpg"),
|
|
46
|
+
"png": ("image/png",),
|
|
47
|
+
"gif": ("image/gif",),
|
|
48
|
+
"webp": ("image/webp",),
|
|
49
|
+
"pdf": ("application/pdf",),
|
|
50
|
+
"zip": ("application/zip", "application/x-zip-compressed"),
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def parse_size_to_bytes(size: int | str) -> int:
|
|
55
|
+
"""Parse integer or string size (e.g. '5MB', '500KB') into integer bytes."""
|
|
56
|
+
if isinstance(size, int):
|
|
57
|
+
return size
|
|
58
|
+
match = _SIZE_PATTERN.match(size.strip())
|
|
59
|
+
if not match:
|
|
60
|
+
raise ValueError(f"Invalid size string: '{size}'")
|
|
61
|
+
value = float(match.group(1))
|
|
62
|
+
unit = (match.group(2) or "b").lower()
|
|
63
|
+
mult = _SIZE_MULTIPLIERS.get(unit)
|
|
64
|
+
if mult is None:
|
|
65
|
+
raise ValueError(f"Unsupported size unit: '{unit}' in '{size}'")
|
|
66
|
+
return int(value * mult)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def verify_magic_bytes(header: bytes, expected_mime: str) -> bool:
|
|
70
|
+
"""
|
|
71
|
+
Verify if header bytes match known magic signatures for expected_mime.
|
|
72
|
+
Fails closed (returns False) when expected_mime has no known signature.
|
|
73
|
+
"""
|
|
74
|
+
mime = expected_mime.split(";", 1)[0].strip().lower()
|
|
75
|
+
if not header:
|
|
76
|
+
return False
|
|
77
|
+
|
|
78
|
+
if mime == "image/webp":
|
|
79
|
+
return len(header) >= 12 and header.startswith(b"RIFF") and header[8:12] == b"WEBP"
|
|
80
|
+
|
|
81
|
+
signatures = MAGIC_BYTE_SIGNATURES.get(mime)
|
|
82
|
+
if not signatures:
|
|
83
|
+
return False
|
|
84
|
+
|
|
85
|
+
return any(header.startswith(sig) for sig in signatures)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class FileValidator:
|
|
89
|
+
"""Upload validation engine enforcing size, extension, MIME, and magic byte constraints."""
|
|
90
|
+
|
|
91
|
+
def __init__(self, rules: Mapping[str, Any]) -> None:
|
|
92
|
+
if not isinstance(rules, Mapping):
|
|
93
|
+
raise TypeError(
|
|
94
|
+
f"FileValidator rules must be a mapping, got {type(rules).__name__}."
|
|
95
|
+
)
|
|
96
|
+
self.rules: dict[str, Any] = dict(rules)
|
|
97
|
+
|
|
98
|
+
def _resolve_magic_byte_candidates(
|
|
99
|
+
self,
|
|
100
|
+
file: UploadedFile,
|
|
101
|
+
allowed_extensions: list[str] | None,
|
|
102
|
+
allowed_mimes: list[str] | None,
|
|
103
|
+
) -> list[str]:
|
|
104
|
+
"""Resolve authoritative MIME signature candidates derived from server policy."""
|
|
105
|
+
file_ext = file.extension.lower()
|
|
106
|
+
declared_mime = file.content_type.split(";", 1)[0].strip().lower()
|
|
107
|
+
ext_mimes = list(_EXTENSION_MIME_MAP.get(file_ext, ()))
|
|
108
|
+
|
|
109
|
+
if allowed_extensions is not None and allowed_mimes is not None:
|
|
110
|
+
if not ext_mimes:
|
|
111
|
+
return []
|
|
112
|
+
return [m for m in ext_mimes if m in allowed_mimes]
|
|
113
|
+
|
|
114
|
+
if allowed_extensions is not None:
|
|
115
|
+
return ext_mimes
|
|
116
|
+
|
|
117
|
+
if allowed_mimes is not None:
|
|
118
|
+
if ext_mimes:
|
|
119
|
+
return [m for m in ext_mimes if m in allowed_mimes]
|
|
120
|
+
return allowed_mimes
|
|
121
|
+
|
|
122
|
+
if ext_mimes:
|
|
123
|
+
return ext_mimes
|
|
124
|
+
return [declared_mime]
|
|
125
|
+
|
|
126
|
+
async def validate(self, file: UploadedFile, field_name: str = "file") -> None:
|
|
127
|
+
errors: list[str] = []
|
|
128
|
+
|
|
129
|
+
# Derive actual real byte size from underlying file to prevent metadata spoofing
|
|
130
|
+
real_size = await file.get_real_size()
|
|
131
|
+
|
|
132
|
+
max_size_raw = self.rules.get("max_size")
|
|
133
|
+
if max_size_raw is not None:
|
|
134
|
+
max_bytes = parse_size_to_bytes(max_size_raw)
|
|
135
|
+
if file.size > max_bytes or real_size > max_bytes:
|
|
136
|
+
errors.append(f"The {field_name} must not be greater than {max_size_raw}.")
|
|
137
|
+
|
|
138
|
+
min_size_raw = self.rules.get("min_size")
|
|
139
|
+
if min_size_raw is not None:
|
|
140
|
+
min_bytes = parse_size_to_bytes(min_size_raw)
|
|
141
|
+
if file.size < min_bytes or real_size < min_bytes:
|
|
142
|
+
errors.append(f"The {field_name} must not be less than {min_size_raw}.")
|
|
143
|
+
|
|
144
|
+
extensions = self.rules.get("extensions")
|
|
145
|
+
ext_list: list[str] | None = None
|
|
146
|
+
if extensions is not None:
|
|
147
|
+
ext_list = [str(e).lstrip(".").lower() for e in extensions]
|
|
148
|
+
if file.extension.lower() not in ext_list:
|
|
149
|
+
allowed_str = ", ".join(ext_list)
|
|
150
|
+
errors.append(f"The {field_name} must be a file of type: {allowed_str}.")
|
|
151
|
+
|
|
152
|
+
mimes = self.rules.get("mimes")
|
|
153
|
+
mime_list: list[str] | None = None
|
|
154
|
+
if mimes is not None:
|
|
155
|
+
mime_list = [str(m).split(";", 1)[0].strip().lower() for m in mimes]
|
|
156
|
+
declared_mime = file.content_type.split(";", 1)[0].strip().lower()
|
|
157
|
+
if declared_mime not in mime_list:
|
|
158
|
+
allowed_str = ", ".join(mime_list)
|
|
159
|
+
errors.append(f"The {field_name} must have a MIME type of: {allowed_str}.")
|
|
160
|
+
|
|
161
|
+
magic_bytes_check = self.rules.get("magic_bytes", False)
|
|
162
|
+
if magic_bytes_check:
|
|
163
|
+
await file.seek(0)
|
|
164
|
+
header = await file.read(32)
|
|
165
|
+
await file.seek(0)
|
|
166
|
+
candidates = self._resolve_magic_byte_candidates(file, ext_list, mime_list)
|
|
167
|
+
declared_mime = file.content_type.split(";", 1)[0].strip().lower()
|
|
168
|
+
matched_policy = bool(candidates) and any(
|
|
169
|
+
verify_magic_bytes(header, mime) for mime in candidates
|
|
170
|
+
)
|
|
171
|
+
if ext_list is None and mime_list is None:
|
|
172
|
+
matched_policy = matched_policy and verify_magic_bytes(header, declared_mime)
|
|
173
|
+
if not matched_policy:
|
|
174
|
+
errors.append(
|
|
175
|
+
f"The {field_name} content does not match an expected file signature."
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
if errors:
|
|
179
|
+
error_map = {field_name: errors}
|
|
180
|
+
if any("greater than" in e for e in errors):
|
|
181
|
+
raise FileTooLargeError(errors[0])
|
|
182
|
+
if any("file of type" in e for e in errors):
|
|
183
|
+
raise InvalidFileExtensionError(error_map, message=errors[0])
|
|
184
|
+
if any("MIME type" in e for e in errors):
|
|
185
|
+
raise InvalidMimeTypeError(error_map, message=errors[0])
|
|
186
|
+
raise FileValidationError(errors=error_map, message=errors[0])
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from enum import StrEnum
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Visibility(StrEnum):
|
|
7
|
+
"""File access visibility."""
|
|
8
|
+
|
|
9
|
+
PUBLIC = "public"
|
|
10
|
+
PRIVATE = "private"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
DEFAULT_FILE_PERMISSIONS: dict[str, int] = {
|
|
14
|
+
Visibility.PUBLIC: 0o644,
|
|
15
|
+
Visibility.PRIVATE: 0o600,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
DEFAULT_DIR_PERMISSIONS: dict[str, int] = {
|
|
19
|
+
Visibility.PUBLIC: 0o755,
|
|
20
|
+
Visibility.PRIVATE: 0o700,
|
|
21
|
+
}
|
|
22
|
+
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from swiftpy.helpers.helper import (
|
|
4
|
+
app,
|
|
5
|
+
cache,
|
|
6
|
+
config,
|
|
7
|
+
container,
|
|
8
|
+
dispatch,
|
|
9
|
+
dispatcher,
|
|
10
|
+
env,
|
|
11
|
+
env_bool,
|
|
12
|
+
event,
|
|
13
|
+
mail,
|
|
14
|
+
pluralize,
|
|
15
|
+
queue,
|
|
16
|
+
resolve,
|
|
17
|
+
snake_case,
|
|
18
|
+
storage,
|
|
19
|
+
websocket_manager,
|
|
20
|
+
ws_manager,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"app",
|
|
25
|
+
"cache",
|
|
26
|
+
"config",
|
|
27
|
+
"container",
|
|
28
|
+
"dispatch",
|
|
29
|
+
"dispatcher",
|
|
30
|
+
"env",
|
|
31
|
+
"env_bool",
|
|
32
|
+
"event",
|
|
33
|
+
"mail",
|
|
34
|
+
"pluralize",
|
|
35
|
+
"queue",
|
|
36
|
+
"resolve",
|
|
37
|
+
"snake_case",
|
|
38
|
+
"storage",
|
|
39
|
+
"websocket_manager",
|
|
40
|
+
"ws_manager",
|
|
41
|
+
]
|
|
42
|
+
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from swiftpy.cache.cache import Cache
|
|
6
|
+
from swiftpy.core.config import Config, env, env_bool
|
|
7
|
+
from swiftpy.core.container import get_container
|
|
8
|
+
from swiftpy.core.container_exceptions import BindingNotFoundError, ResolutionError
|
|
9
|
+
from swiftpy.events.dispatcher import EventDispatcher
|
|
10
|
+
from swiftpy.filesystem.manager import FilesystemManager
|
|
11
|
+
from swiftpy.mail.manager import MailManager
|
|
12
|
+
from swiftpy.queue.dispatcher import QueueDispatcher
|
|
13
|
+
from swiftpy.queue.job import Job
|
|
14
|
+
from swiftpy.support.strings import pluralize, snake_case
|
|
15
|
+
from swiftpy.websockets.manager import WebSocketManager
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def app() -> Any:
|
|
19
|
+
"""Return the application container."""
|
|
20
|
+
return get_container()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def cache(driver_name: str | None = None) -> Any:
|
|
24
|
+
"""Retrieve the application Cache manager or a specific driver."""
|
|
25
|
+
try:
|
|
26
|
+
c_inst = get_container()
|
|
27
|
+
except RuntimeError as exc:
|
|
28
|
+
raise ResolutionError("Application container not bootstrapped") from exc
|
|
29
|
+
|
|
30
|
+
if not c_inst.has(Cache):
|
|
31
|
+
raise BindingNotFoundError(
|
|
32
|
+
"Cache is not registered in the container. Ensure CacheServiceProvider is registered."
|
|
33
|
+
)
|
|
34
|
+
c = c_inst.resolve(Cache)
|
|
35
|
+
|
|
36
|
+
if driver_name is not None:
|
|
37
|
+
return c.driver(driver_name)
|
|
38
|
+
return c
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def storage(disk_name: str | None = None) -> Any:
|
|
42
|
+
"""Retrieve the application FilesystemManager or a specific StorageDisk."""
|
|
43
|
+
try:
|
|
44
|
+
c_inst = get_container()
|
|
45
|
+
if c_inst.has(FilesystemManager):
|
|
46
|
+
manager = c_inst.resolve(FilesystemManager)
|
|
47
|
+
else:
|
|
48
|
+
manager = FilesystemManager.get_instance()
|
|
49
|
+
except RuntimeError:
|
|
50
|
+
manager = FilesystemManager.get_instance()
|
|
51
|
+
|
|
52
|
+
if disk_name is not None:
|
|
53
|
+
return manager.disk(disk_name)
|
|
54
|
+
return manager
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def mail(mailer_name: str | None = None) -> Any:
|
|
58
|
+
"""Retrieve the application MailManager or a specific MailTransport."""
|
|
59
|
+
try:
|
|
60
|
+
c_inst = get_container()
|
|
61
|
+
if c_inst.has(MailManager):
|
|
62
|
+
manager = c_inst.resolve(MailManager)
|
|
63
|
+
else:
|
|
64
|
+
manager = MailManager.get_instance()
|
|
65
|
+
except RuntimeError:
|
|
66
|
+
manager = MailManager.get_instance()
|
|
67
|
+
|
|
68
|
+
if mailer_name is not None:
|
|
69
|
+
return manager.mailer(mailer_name)
|
|
70
|
+
return manager
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def config(key: str | None = None, default: Any = None) -> Any:
|
|
74
|
+
"""Retrieve configuration values."""
|
|
75
|
+
try:
|
|
76
|
+
c_inst = get_container()
|
|
77
|
+
cfg = c_inst.resolve(Config) if c_inst.has(Config) else Config.get_instance()
|
|
78
|
+
except RuntimeError:
|
|
79
|
+
cfg = Config.get_instance()
|
|
80
|
+
|
|
81
|
+
if key is None:
|
|
82
|
+
return cfg
|
|
83
|
+
|
|
84
|
+
return cfg.get(key, default)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def container() -> Any:
|
|
88
|
+
"""Return the IoC container."""
|
|
89
|
+
return get_container()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def resolve(target: type[Any]) -> Any:
|
|
93
|
+
"""Resolve a dependency from the container."""
|
|
94
|
+
return get_container().resolve(target)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def dispatcher() -> EventDispatcher:
|
|
98
|
+
"""Retrieve the application EventDispatcher."""
|
|
99
|
+
try:
|
|
100
|
+
c_inst = get_container()
|
|
101
|
+
except RuntimeError as exc:
|
|
102
|
+
raise ResolutionError("Application container not bootstrapped") from exc
|
|
103
|
+
|
|
104
|
+
if not c_inst.has(EventDispatcher):
|
|
105
|
+
raise BindingNotFoundError(
|
|
106
|
+
"EventDispatcher is not registered in the container. Ensure EventServiceProvider is registered."
|
|
107
|
+
)
|
|
108
|
+
disp: EventDispatcher = c_inst.resolve(EventDispatcher)
|
|
109
|
+
return disp
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
async def event(event_name: str, payload: Any = None) -> list[Any]:
|
|
113
|
+
"""Dispatch an event through the event dispatcher."""
|
|
114
|
+
d = dispatcher()
|
|
115
|
+
return await d.dispatch(event_name, payload)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def queue() -> QueueDispatcher:
|
|
119
|
+
"""Retrieve the application QueueDispatcher."""
|
|
120
|
+
try:
|
|
121
|
+
c_inst = get_container()
|
|
122
|
+
except RuntimeError as exc:
|
|
123
|
+
raise ResolutionError("Application container not bootstrapped") from exc
|
|
124
|
+
|
|
125
|
+
if not c_inst.has(QueueDispatcher):
|
|
126
|
+
raise BindingNotFoundError(
|
|
127
|
+
"QueueDispatcher is not registered in the container. Ensure QueueServiceProvider is registered."
|
|
128
|
+
)
|
|
129
|
+
q: QueueDispatcher = c_inst.resolve(QueueDispatcher)
|
|
130
|
+
return q
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
async def dispatch(
|
|
134
|
+
job: Job,
|
|
135
|
+
queue_name: str | None = None,
|
|
136
|
+
delay: float = 0,
|
|
137
|
+
) -> str:
|
|
138
|
+
"""Dispatch a job onto the application queue."""
|
|
139
|
+
q = queue()
|
|
140
|
+
return await q.push(job, queue=queue_name, delay=delay)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def websocket_manager() -> WebSocketManager:
|
|
144
|
+
"""Retrieve the application WebSocketManager."""
|
|
145
|
+
try:
|
|
146
|
+
c_inst = get_container()
|
|
147
|
+
except RuntimeError as exc:
|
|
148
|
+
raise ResolutionError("Application container not bootstrapped") from exc
|
|
149
|
+
|
|
150
|
+
if not c_inst.has(WebSocketManager):
|
|
151
|
+
raise BindingNotFoundError(
|
|
152
|
+
"WebSocketManager is not registered in the container."
|
|
153
|
+
)
|
|
154
|
+
wm: WebSocketManager = c_inst.resolve(WebSocketManager)
|
|
155
|
+
return wm
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def ws_manager() -> WebSocketManager:
|
|
159
|
+
"""Alias for websocket_manager()."""
|
|
160
|
+
return websocket_manager()
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
__all__ = [
|
|
164
|
+
"app",
|
|
165
|
+
"cache",
|
|
166
|
+
"config",
|
|
167
|
+
"container",
|
|
168
|
+
"dispatch",
|
|
169
|
+
"dispatcher",
|
|
170
|
+
"env",
|
|
171
|
+
"env_bool",
|
|
172
|
+
"event",
|
|
173
|
+
"mail",
|
|
174
|
+
"pluralize",
|
|
175
|
+
"queue",
|
|
176
|
+
"resolve",
|
|
177
|
+
"snake_case",
|
|
178
|
+
"websocket_manager",
|
|
179
|
+
"ws_manager",
|
|
180
|
+
]
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class HttpException(Exception):
|
|
5
|
+
"""
|
|
6
|
+
Base HTTP exception for request pipeline errors.
|
|
7
|
+
Automatically caught and converted into JSON responses by Application.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
def __init__(
|
|
11
|
+
self,
|
|
12
|
+
message: str,
|
|
13
|
+
status_code: int = 500,
|
|
14
|
+
headers: dict[str, str] | None = None,
|
|
15
|
+
) -> None:
|
|
16
|
+
self.message = message
|
|
17
|
+
self.status_code = status_code
|
|
18
|
+
self.headers = headers
|
|
19
|
+
super().__init__(message)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class PayloadTooLargeError(HttpException):
|
|
23
|
+
"""Exception mapped automatically to HTTP 413 Payload Too Large."""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
message: str = "Payload Too Large",
|
|
28
|
+
headers: dict[str, str] | None = None,
|
|
29
|
+
) -> None:
|
|
30
|
+
super().__init__(message=message, status_code=413, headers=headers)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ClientDisconnect(Exception):
|
|
34
|
+
"""Raised when the ASGI client disconnects before the request body is fully read."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"ClientDisconnect",
|
|
39
|
+
"HttpException",
|
|
40
|
+
"PayloadTooLargeError",
|
|
41
|
+
]
|