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,612 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import copy
|
|
5
|
+
import inspect
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any
|
|
9
|
+
from weakref import WeakKeyDictionary
|
|
10
|
+
|
|
11
|
+
from swiftpy.database.transaction import get_active_connection
|
|
12
|
+
from swiftpy.validation.rules.builtin import (
|
|
13
|
+
BailRule,
|
|
14
|
+
BetweenRule,
|
|
15
|
+
BoolRule,
|
|
16
|
+
EmailRule,
|
|
17
|
+
FloatRule,
|
|
18
|
+
InRule,
|
|
19
|
+
IntRule,
|
|
20
|
+
MaxRule,
|
|
21
|
+
MinRule,
|
|
22
|
+
NotInRule,
|
|
23
|
+
RegexRule,
|
|
24
|
+
StrRule,
|
|
25
|
+
UrlRule,
|
|
26
|
+
)
|
|
27
|
+
from swiftpy.validation.rules.exists import ExistsRule
|
|
28
|
+
from swiftpy.validation.rules.registry import RuleRegistry, default_registry
|
|
29
|
+
from swiftpy.validation.rules.required import NullableRule, RequiredRule
|
|
30
|
+
from swiftpy.validation.rules.unique import UniqueRule
|
|
31
|
+
|
|
32
|
+
_RULE_INVOKER_CACHE: WeakKeyDictionary[
|
|
33
|
+
type, dict[tuple[str, Any], tuple[int, bool]]
|
|
34
|
+
] = WeakKeyDictionary()
|
|
35
|
+
|
|
36
|
+
_RULE_ALIAS_MAP: dict[type[Any], tuple[str, ...]] = {
|
|
37
|
+
RequiredRule: ("required",),
|
|
38
|
+
NullableRule: ("nullable",),
|
|
39
|
+
BailRule: ("bail",),
|
|
40
|
+
StrRule: ("str", "string"),
|
|
41
|
+
EmailRule: ("email",),
|
|
42
|
+
IntRule: ("int", "integer"),
|
|
43
|
+
FloatRule: ("float",),
|
|
44
|
+
BoolRule: ("bool", "boolean"),
|
|
45
|
+
UrlRule: ("url",),
|
|
46
|
+
MinRule: ("min",),
|
|
47
|
+
MaxRule: ("max",),
|
|
48
|
+
BetweenRule: ("between",),
|
|
49
|
+
InRule: ("in", "in_"),
|
|
50
|
+
NotInRule: ("not_in",),
|
|
51
|
+
RegexRule: ("regex",),
|
|
52
|
+
UniqueRule: ("unique",),
|
|
53
|
+
ExistsRule: ("exists",),
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _get_rule_invoker_info(rule: Any) -> tuple[int, bool]:
|
|
58
|
+
"""Precompute and cache rule method signature metadata keyed safely by class and callable."""
|
|
59
|
+
cls = rule.__class__
|
|
60
|
+
method_name = "validate"
|
|
61
|
+
method = getattr(rule, "validate", None)
|
|
62
|
+
if method is None or not callable(method):
|
|
63
|
+
method_name = "passes"
|
|
64
|
+
method = getattr(rule, "passes", None)
|
|
65
|
+
if method is None or not callable(method):
|
|
66
|
+
raise AttributeError(
|
|
67
|
+
f"Rule {cls.__name__} must implement 'validate' or 'passes'"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
func_key: Any = getattr(method, "__func__", method)
|
|
71
|
+
cls_cache: dict[tuple[str, Any], tuple[int, bool]] | None = None
|
|
72
|
+
try:
|
|
73
|
+
cls_cache = _RULE_INVOKER_CACHE.get(cls)
|
|
74
|
+
if cls_cache is not None:
|
|
75
|
+
cached = cls_cache.get((method_name, func_key))
|
|
76
|
+
if cached is not None:
|
|
77
|
+
return cached
|
|
78
|
+
except TypeError:
|
|
79
|
+
cls_cache = None
|
|
80
|
+
|
|
81
|
+
sig = inspect.signature(method)
|
|
82
|
+
param_count = len(sig.parameters)
|
|
83
|
+
is_async = inspect.iscoroutinefunction(method)
|
|
84
|
+
info = (param_count, is_async)
|
|
85
|
+
try:
|
|
86
|
+
if cls_cache is None:
|
|
87
|
+
cls_cache = {}
|
|
88
|
+
_RULE_INVOKER_CACHE[cls] = cls_cache
|
|
89
|
+
cls_cache[(method_name, func_key)] = info
|
|
90
|
+
except TypeError:
|
|
91
|
+
pass
|
|
92
|
+
return info
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _rule_sort_key(rule: Any) -> tuple[int, int]:
|
|
96
|
+
"""Sort rules canonically so type coercion runs deterministically before constraint evaluation."""
|
|
97
|
+
if isinstance(rule, RequiredRule):
|
|
98
|
+
return (0, 0)
|
|
99
|
+
if isinstance(rule, NullableRule):
|
|
100
|
+
return (0, 1)
|
|
101
|
+
if isinstance(rule, BailRule) or getattr(rule, "is_bail_rule", False):
|
|
102
|
+
return (0, 2)
|
|
103
|
+
if isinstance(rule, StrRule):
|
|
104
|
+
return (1, 0)
|
|
105
|
+
if isinstance(rule, EmailRule):
|
|
106
|
+
return (1, 1)
|
|
107
|
+
if isinstance(rule, IntRule):
|
|
108
|
+
return (1, 2)
|
|
109
|
+
if isinstance(rule, FloatRule):
|
|
110
|
+
return (1, 3)
|
|
111
|
+
if isinstance(rule, BoolRule):
|
|
112
|
+
return (1, 4)
|
|
113
|
+
return (2, 0)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass(slots=True)
|
|
117
|
+
class ValidationResult:
|
|
118
|
+
"""
|
|
119
|
+
Typed result returned by validate(data, schema).
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
is_valid: bool
|
|
123
|
+
errors: dict[str, list[str]] = field(default_factory=dict)
|
|
124
|
+
validated_data: dict[str, Any] = field(default_factory=dict)
|
|
125
|
+
|
|
126
|
+
def passes(self) -> bool:
|
|
127
|
+
"""Return True if all validation rules passed."""
|
|
128
|
+
return self.is_valid
|
|
129
|
+
|
|
130
|
+
def fails(self) -> bool:
|
|
131
|
+
"""Return True if any validation rule failed."""
|
|
132
|
+
return not self.is_valid
|
|
133
|
+
|
|
134
|
+
def __bool__(self) -> bool:
|
|
135
|
+
"""Evaluate result truthiness based on validity."""
|
|
136
|
+
return self.is_valid
|
|
137
|
+
|
|
138
|
+
def first_error(self, field_name: str | None = None) -> str | None:
|
|
139
|
+
"""
|
|
140
|
+
Return the first error message for a specific field or across all fields.
|
|
141
|
+
"""
|
|
142
|
+
if field_name is not None:
|
|
143
|
+
field_errors = self.errors.get(field_name)
|
|
144
|
+
return field_errors[0] if field_errors else None
|
|
145
|
+
|
|
146
|
+
for field_errors in self.errors.values():
|
|
147
|
+
if field_errors:
|
|
148
|
+
return field_errors[0]
|
|
149
|
+
return None
|
|
150
|
+
|
|
151
|
+
def errors_for(self, field_name: str) -> list[str]:
|
|
152
|
+
"""Return all error messages for a specific field."""
|
|
153
|
+
return list(self.errors.get(field_name, []))
|
|
154
|
+
|
|
155
|
+
def all_errors(self) -> list[str]:
|
|
156
|
+
"""Return a flattened list of all error messages."""
|
|
157
|
+
flattened: list[str] = []
|
|
158
|
+
for field_errors in self.errors.values():
|
|
159
|
+
flattened.extend(field_errors)
|
|
160
|
+
return flattened
|
|
161
|
+
|
|
162
|
+
def validated(self) -> dict[str, Any]:
|
|
163
|
+
"""Return a copy of the cleaned/coerced validated data."""
|
|
164
|
+
return dict(self.validated_data)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
_UNSET = object()
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _expand_wildcard_targets(
|
|
171
|
+
data: dict[str, Any],
|
|
172
|
+
pattern: str,
|
|
173
|
+
rules: list[Any],
|
|
174
|
+
) -> tuple[
|
|
175
|
+
list[tuple[str, tuple[str | int, ...], list[Any], bool, Any, str]],
|
|
176
|
+
dict[str, list[str]],
|
|
177
|
+
]:
|
|
178
|
+
"""Expand a dotted wildcard pattern (e.g. 'items.*', 'users.*.email') against payload data."""
|
|
179
|
+
segments = pattern.split(".")
|
|
180
|
+
targets: list[tuple[str, tuple[str | int, ...], list[Any], bool, Any, str]] = []
|
|
181
|
+
structural_errors: dict[str, list[str]] = {}
|
|
182
|
+
|
|
183
|
+
def _walk(
|
|
184
|
+
current: Any,
|
|
185
|
+
seg_idx: int,
|
|
186
|
+
field_parts: list[str],
|
|
187
|
+
path_keys: list[str | int],
|
|
188
|
+
present: bool,
|
|
189
|
+
) -> None:
|
|
190
|
+
if not present:
|
|
191
|
+
return
|
|
192
|
+
if seg_idx >= len(segments):
|
|
193
|
+
concrete_name = ".".join(field_parts)
|
|
194
|
+
targets.append(
|
|
195
|
+
(concrete_name, tuple(path_keys), rules, True, current, pattern)
|
|
196
|
+
)
|
|
197
|
+
return
|
|
198
|
+
|
|
199
|
+
seg = segments[seg_idx]
|
|
200
|
+
if seg == "*":
|
|
201
|
+
if current is None:
|
|
202
|
+
return
|
|
203
|
+
if not isinstance(current, (list, tuple)):
|
|
204
|
+
parent_name = ".".join(field_parts) or pattern
|
|
205
|
+
structural_errors.setdefault(parent_name, []).append(
|
|
206
|
+
f"The {parent_name} field must be a list."
|
|
207
|
+
)
|
|
208
|
+
return
|
|
209
|
+
for idx, item in enumerate(current):
|
|
210
|
+
next_fields = [*field_parts, str(idx)]
|
|
211
|
+
next_keys: list[str | int] = [*path_keys, idx]
|
|
212
|
+
if seg_idx == len(segments) - 1:
|
|
213
|
+
targets.append(
|
|
214
|
+
(
|
|
215
|
+
".".join(next_fields),
|
|
216
|
+
tuple(next_keys),
|
|
217
|
+
rules,
|
|
218
|
+
True,
|
|
219
|
+
item,
|
|
220
|
+
pattern,
|
|
221
|
+
)
|
|
222
|
+
)
|
|
223
|
+
else:
|
|
224
|
+
_walk(item, seg_idx + 1, next_fields, next_keys, True)
|
|
225
|
+
return
|
|
226
|
+
|
|
227
|
+
if isinstance(current, Mapping):
|
|
228
|
+
has_key = seg in current
|
|
229
|
+
val = current.get(seg)
|
|
230
|
+
if not has_key:
|
|
231
|
+
if seg_idx == len(segments) - 1 and any(
|
|
232
|
+
k == "*" for k in segments[:seg_idx]
|
|
233
|
+
):
|
|
234
|
+
concrete_name = ".".join([*field_parts, seg])
|
|
235
|
+
targets.append(
|
|
236
|
+
(
|
|
237
|
+
concrete_name,
|
|
238
|
+
(*path_keys, seg),
|
|
239
|
+
rules,
|
|
240
|
+
False,
|
|
241
|
+
None,
|
|
242
|
+
pattern,
|
|
243
|
+
)
|
|
244
|
+
)
|
|
245
|
+
return
|
|
246
|
+
_walk(val, seg_idx + 1, [*field_parts, seg], [*path_keys, seg], True)
|
|
247
|
+
elif current is not None:
|
|
248
|
+
parent_name = ".".join(field_parts) or pattern
|
|
249
|
+
structural_errors.setdefault(parent_name, []).append(
|
|
250
|
+
f"The {parent_name} field must be an object."
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
_walk(data, 0, [], [], True)
|
|
254
|
+
return targets, structural_errors
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _assign_nested_value(
|
|
258
|
+
validated_data: dict[str, Any],
|
|
259
|
+
source_data: dict[str, Any],
|
|
260
|
+
path_keys: tuple[str | int, ...],
|
|
261
|
+
value: Any,
|
|
262
|
+
) -> None:
|
|
263
|
+
"""Assign a coerced leaf value into validated_data without mutating caller input."""
|
|
264
|
+
if not path_keys:
|
|
265
|
+
return
|
|
266
|
+
root_key = str(path_keys[0])
|
|
267
|
+
if root_key not in validated_data and root_key in source_data:
|
|
268
|
+
validated_data[root_key] = copy.deepcopy(source_data[root_key])
|
|
269
|
+
if len(path_keys) == 1:
|
|
270
|
+
validated_data[root_key] = value
|
|
271
|
+
return
|
|
272
|
+
cur: Any = validated_data.get(root_key)
|
|
273
|
+
for step in path_keys[1:-1]:
|
|
274
|
+
if isinstance(step, int) and isinstance(cur, list) and 0 <= step < len(cur):
|
|
275
|
+
next_cur: Any = cur[step]
|
|
276
|
+
cur = next_cur
|
|
277
|
+
elif isinstance(step, str) and isinstance(cur, dict) and step in cur:
|
|
278
|
+
cur = cur[step]
|
|
279
|
+
else:
|
|
280
|
+
return
|
|
281
|
+
last = path_keys[-1]
|
|
282
|
+
if isinstance(last, int):
|
|
283
|
+
if isinstance(cur, list) and 0 <= last < len(cur):
|
|
284
|
+
cur[last] = value
|
|
285
|
+
elif isinstance(cur, dict):
|
|
286
|
+
cur[last] = value
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
class Validator:
|
|
290
|
+
"""
|
|
291
|
+
Core validation engine. Parses schemas, coordinates rule execution,
|
|
292
|
+
supports sync/async custom rules, and returns a typed ValidationResult.
|
|
293
|
+
"""
|
|
294
|
+
|
|
295
|
+
def __init__(
|
|
296
|
+
self,
|
|
297
|
+
data: dict[str, Any] | Any,
|
|
298
|
+
schema: dict[str, Any],
|
|
299
|
+
registry: RuleRegistry | None = None,
|
|
300
|
+
messages: dict[str, str] | None = None,
|
|
301
|
+
) -> None:
|
|
302
|
+
self.is_payload_dict = isinstance(data, dict)
|
|
303
|
+
self.data: dict[str, Any] = dict(data) if isinstance(data, dict) else {}
|
|
304
|
+
self.schema = schema
|
|
305
|
+
self.registry = registry or default_registry
|
|
306
|
+
self.messages: dict[str, str] = dict(messages) if messages else {}
|
|
307
|
+
self._db_rule_lock = asyncio.Lock()
|
|
308
|
+
|
|
309
|
+
async def validate(self) -> ValidationResult:
|
|
310
|
+
"""
|
|
311
|
+
Execute validation across all schema rules non-blockingly.
|
|
312
|
+
Fields are validated concurrently via asyncio.gather outside transactions,
|
|
313
|
+
or sequentially when an active transaction is present (P3-D4).
|
|
314
|
+
"""
|
|
315
|
+
if not self.is_payload_dict:
|
|
316
|
+
return ValidationResult(
|
|
317
|
+
is_valid=False,
|
|
318
|
+
errors={"body": ["The request body must be a JSON object."]},
|
|
319
|
+
validated_data={},
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
direct_fields: list[tuple[str, list[Any]]] = []
|
|
323
|
+
wildcard_fields: list[tuple[str, list[Any]]] = []
|
|
324
|
+
for field_name, rule_def in self.schema.items():
|
|
325
|
+
if isinstance(rule_def, list) and all(
|
|
326
|
+
not isinstance(r, str)
|
|
327
|
+
and (hasattr(r, "validate") or hasattr(r, "passes"))
|
|
328
|
+
for r in rule_def
|
|
329
|
+
):
|
|
330
|
+
parsed = rule_def
|
|
331
|
+
else:
|
|
332
|
+
parsed = self.registry.parse_rules(rule_def)
|
|
333
|
+
|
|
334
|
+
if "*" in field_name.split("."):
|
|
335
|
+
wildcard_fields.append((field_name, parsed))
|
|
336
|
+
else:
|
|
337
|
+
direct_fields.append((field_name, parsed))
|
|
338
|
+
|
|
339
|
+
errors: dict[str, list[str]] = {}
|
|
340
|
+
validated_data: dict[str, Any] = {}
|
|
341
|
+
|
|
342
|
+
direct_targets: list[
|
|
343
|
+
tuple[str, tuple[str | int, ...], list[Any], bool, Any, str]
|
|
344
|
+
] = [
|
|
345
|
+
(
|
|
346
|
+
field_name,
|
|
347
|
+
(field_name,),
|
|
348
|
+
rules,
|
|
349
|
+
field_name in self.data,
|
|
350
|
+
self.data.get(field_name),
|
|
351
|
+
field_name,
|
|
352
|
+
)
|
|
353
|
+
for field_name, rules in direct_fields
|
|
354
|
+
]
|
|
355
|
+
wildcard_targets: list[
|
|
356
|
+
tuple[str, tuple[str | int, ...], list[Any], bool, Any, str]
|
|
357
|
+
] = []
|
|
358
|
+
for pattern, rules in wildcard_fields:
|
|
359
|
+
expanded, struct_errs = _expand_wildcard_targets(self.data, pattern, rules)
|
|
360
|
+
for k, msgs in struct_errs.items():
|
|
361
|
+
errors.setdefault(k, []).extend(msgs)
|
|
362
|
+
wildcard_targets.extend(expanded)
|
|
363
|
+
|
|
364
|
+
all_targets = [*direct_targets, *wildcard_targets]
|
|
365
|
+
|
|
366
|
+
if get_active_connection() is not None:
|
|
367
|
+
results = [
|
|
368
|
+
(
|
|
369
|
+
path_keys,
|
|
370
|
+
await self._validate_field(
|
|
371
|
+
field_name,
|
|
372
|
+
rules,
|
|
373
|
+
field_present=present,
|
|
374
|
+
raw_value=raw_val,
|
|
375
|
+
template_field=template_field,
|
|
376
|
+
),
|
|
377
|
+
)
|
|
378
|
+
for field_name, path_keys, rules, present, raw_val, template_field in all_targets
|
|
379
|
+
]
|
|
380
|
+
else:
|
|
381
|
+
coros = [
|
|
382
|
+
self._validate_field(
|
|
383
|
+
field_name,
|
|
384
|
+
rules,
|
|
385
|
+
field_present=present,
|
|
386
|
+
raw_value=raw_val,
|
|
387
|
+
template_field=template_field,
|
|
388
|
+
)
|
|
389
|
+
for field_name, _pk, rules, present, raw_val, template_field in all_targets
|
|
390
|
+
]
|
|
391
|
+
raw_results = list(await asyncio.gather(*coros))
|
|
392
|
+
results = [
|
|
393
|
+
(all_targets[idx][1], res) for idx, res in enumerate(raw_results)
|
|
394
|
+
]
|
|
395
|
+
|
|
396
|
+
for path_keys, (field_name, field_errors, coerced_val) in results:
|
|
397
|
+
if field_errors:
|
|
398
|
+
errors.setdefault(field_name, []).extend(field_errors)
|
|
399
|
+
elif coerced_val is not _UNSET:
|
|
400
|
+
if len(path_keys) == 1:
|
|
401
|
+
validated_data[field_name] = copy.deepcopy(coerced_val)
|
|
402
|
+
else:
|
|
403
|
+
_assign_nested_value(validated_data, self.data, path_keys, coerced_val)
|
|
404
|
+
|
|
405
|
+
return ValidationResult(
|
|
406
|
+
is_valid=len(errors) == 0,
|
|
407
|
+
errors=errors,
|
|
408
|
+
validated_data=validated_data,
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
async def _validate_field(
|
|
412
|
+
self,
|
|
413
|
+
field_name: str,
|
|
414
|
+
rules: list[Any],
|
|
415
|
+
*,
|
|
416
|
+
field_present: bool | None = None,
|
|
417
|
+
raw_value: Any = _UNSET,
|
|
418
|
+
template_field: str | None = None,
|
|
419
|
+
) -> tuple[str, list[str], Any]:
|
|
420
|
+
field_errors: list[str] = []
|
|
421
|
+
|
|
422
|
+
is_nullable = any(
|
|
423
|
+
isinstance(r, NullableRule) or getattr(r, "is_nullable_rule", False)
|
|
424
|
+
for r in rules
|
|
425
|
+
)
|
|
426
|
+
is_required = any(isinstance(r, RequiredRule) for r in rules)
|
|
427
|
+
should_bail = any(
|
|
428
|
+
isinstance(r, BailRule) or getattr(r, "is_bail_rule", False)
|
|
429
|
+
for r in rules
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
if field_present is None:
|
|
433
|
+
field_present = field_name in self.data
|
|
434
|
+
if raw_value is _UNSET:
|
|
435
|
+
raw_value = self.data.get(field_name)
|
|
436
|
+
|
|
437
|
+
# 1. Field is absent
|
|
438
|
+
if not field_present:
|
|
439
|
+
if is_required:
|
|
440
|
+
req_rule = next(r for r in rules if isinstance(r, RequiredRule))
|
|
441
|
+
field_errors.append(
|
|
442
|
+
self._get_rule_message(
|
|
443
|
+
req_rule, field_name, template_field=template_field
|
|
444
|
+
)
|
|
445
|
+
)
|
|
446
|
+
return field_name, field_errors, _UNSET
|
|
447
|
+
|
|
448
|
+
# 2. Field is present and null / empty string
|
|
449
|
+
if (raw_value is None or raw_value == "") and is_nullable:
|
|
450
|
+
return field_name, [], raw_value
|
|
451
|
+
|
|
452
|
+
coerced_value = raw_value
|
|
453
|
+
|
|
454
|
+
# Sort rules canonically so type coercion executes consistently before constraint rules
|
|
455
|
+
sorted_rules = sorted(rules, key=_rule_sort_key)
|
|
456
|
+
|
|
457
|
+
# 3. Evaluate rules sequentially for this field
|
|
458
|
+
for rule in sorted_rules:
|
|
459
|
+
if isinstance(rule, (NullableRule, BailRule)) or getattr(
|
|
460
|
+
rule, "is_bail_rule", False
|
|
461
|
+
):
|
|
462
|
+
continue
|
|
463
|
+
|
|
464
|
+
if (
|
|
465
|
+
getattr(rule, "requires_db", False)
|
|
466
|
+
and get_active_connection() is not None
|
|
467
|
+
):
|
|
468
|
+
async with self._db_rule_lock:
|
|
469
|
+
passed = await self._run_rule(
|
|
470
|
+
rule, field_name, coerced_value, field_present=field_present
|
|
471
|
+
)
|
|
472
|
+
else:
|
|
473
|
+
passed = await self._run_rule(
|
|
474
|
+
rule, field_name, coerced_value, field_present=field_present
|
|
475
|
+
)
|
|
476
|
+
if not passed:
|
|
477
|
+
msg = self._get_rule_message(
|
|
478
|
+
rule, field_name, template_field=template_field
|
|
479
|
+
)
|
|
480
|
+
field_errors.append(msg)
|
|
481
|
+
# Stop further rules when required fails or bail is enabled
|
|
482
|
+
if isinstance(rule, RequiredRule) or should_bail:
|
|
483
|
+
break
|
|
484
|
+
else:
|
|
485
|
+
# Apply coercion if rule is type rule
|
|
486
|
+
if isinstance(rule, IntRule) and isinstance(coerced_value, str):
|
|
487
|
+
try:
|
|
488
|
+
coerced_value = int(coerced_value.strip())
|
|
489
|
+
except ValueError:
|
|
490
|
+
pass
|
|
491
|
+
elif isinstance(rule, FloatRule):
|
|
492
|
+
if isinstance(coerced_value, int) and not isinstance(
|
|
493
|
+
coerced_value, bool
|
|
494
|
+
):
|
|
495
|
+
coerced_value = float(coerced_value)
|
|
496
|
+
elif isinstance(coerced_value, str):
|
|
497
|
+
try:
|
|
498
|
+
coerced_value = float(coerced_value.strip())
|
|
499
|
+
except ValueError:
|
|
500
|
+
pass
|
|
501
|
+
elif isinstance(rule, BoolRule) and not isinstance(coerced_value, bool):
|
|
502
|
+
str_val = str(coerced_value).strip().lower()
|
|
503
|
+
if str_val in ("true", "1"):
|
|
504
|
+
coerced_value = True
|
|
505
|
+
elif str_val in ("false", "0"):
|
|
506
|
+
coerced_value = False
|
|
507
|
+
elif isinstance(rule, EmailRule) and isinstance(coerced_value, str):
|
|
508
|
+
coerced_value = rule.normalize(coerced_value)
|
|
509
|
+
|
|
510
|
+
return field_name, field_errors, coerced_value
|
|
511
|
+
|
|
512
|
+
async def _run_rule(
|
|
513
|
+
self,
|
|
514
|
+
rule: Any,
|
|
515
|
+
field_name: str,
|
|
516
|
+
value: Any,
|
|
517
|
+
*,
|
|
518
|
+
field_present: bool = True,
|
|
519
|
+
) -> bool:
|
|
520
|
+
"""Invoke rule's validate or passes method safely handling sync and async."""
|
|
521
|
+
method = getattr(rule, "validate", None)
|
|
522
|
+
if method is None or not callable(method):
|
|
523
|
+
method = getattr(rule, "passes", None)
|
|
524
|
+
|
|
525
|
+
if method is None or not callable(method):
|
|
526
|
+
raise AttributeError(
|
|
527
|
+
f"Rule {rule.__class__.__name__} must implement 'validate' or 'passes'"
|
|
528
|
+
)
|
|
529
|
+
|
|
530
|
+
param_count, is_async = _get_rule_invoker_info(rule)
|
|
531
|
+
|
|
532
|
+
if param_count <= 2:
|
|
533
|
+
res = method(field_name, value)
|
|
534
|
+
else:
|
|
535
|
+
rule_data = (
|
|
536
|
+
{**self.data, field_name: value}
|
|
537
|
+
if field_present and field_name not in self.data
|
|
538
|
+
else self.data
|
|
539
|
+
)
|
|
540
|
+
res = method(field_name, value, rule_data)
|
|
541
|
+
|
|
542
|
+
if is_async or inspect.isawaitable(res):
|
|
543
|
+
return bool(await res)
|
|
544
|
+
return bool(res)
|
|
545
|
+
|
|
546
|
+
def _resolve_rule_aliases(self, rule: Any) -> tuple[str, ...]:
|
|
547
|
+
explicit = getattr(rule, "rule_name", None)
|
|
548
|
+
if isinstance(explicit, str) and explicit:
|
|
549
|
+
return (explicit.lower(),)
|
|
550
|
+
aliases = _RULE_ALIAS_MAP.get(type(rule))
|
|
551
|
+
if aliases is not None:
|
|
552
|
+
return aliases
|
|
553
|
+
cls_name = type(rule).__name__.lower()
|
|
554
|
+
if cls_name.endswith("rule") and len(cls_name) > 4:
|
|
555
|
+
return (cls_name[:-4],)
|
|
556
|
+
return (cls_name,)
|
|
557
|
+
|
|
558
|
+
def _get_rule_message(
|
|
559
|
+
self,
|
|
560
|
+
rule: Any,
|
|
561
|
+
field_name: str,
|
|
562
|
+
*,
|
|
563
|
+
template_field: str | None = None,
|
|
564
|
+
) -> str:
|
|
565
|
+
"""Extract custom override or default error message from the rule."""
|
|
566
|
+
if self.messages:
|
|
567
|
+
aliases = self._resolve_rule_aliases(rule)
|
|
568
|
+
for target_field in (
|
|
569
|
+
(field_name, template_field)
|
|
570
|
+
if template_field and template_field != field_name
|
|
571
|
+
else (field_name,)
|
|
572
|
+
):
|
|
573
|
+
for alias in aliases:
|
|
574
|
+
key = f"{target_field}.{alias}"
|
|
575
|
+
if key in self.messages:
|
|
576
|
+
return str(self.messages[key])
|
|
577
|
+
if target_field in self.messages:
|
|
578
|
+
return str(self.messages[target_field])
|
|
579
|
+
for alias in aliases:
|
|
580
|
+
if alias in self.messages:
|
|
581
|
+
return str(self.messages[alias])
|
|
582
|
+
|
|
583
|
+
if hasattr(rule, "message"):
|
|
584
|
+
attr = rule.message
|
|
585
|
+
if callable(attr):
|
|
586
|
+
try:
|
|
587
|
+
return str(attr(field_name))
|
|
588
|
+
except TypeError:
|
|
589
|
+
return str(attr())
|
|
590
|
+
return str(attr)
|
|
591
|
+
return f"The {field_name} field is invalid."
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
async def validate(
|
|
595
|
+
data: dict[str, Any] | Any,
|
|
596
|
+
schema: dict[str, Any],
|
|
597
|
+
registry: RuleRegistry | None = None,
|
|
598
|
+
messages: dict[str, str] | None = None,
|
|
599
|
+
) -> ValidationResult:
|
|
600
|
+
"""
|
|
601
|
+
Validate data against a schema non-blockingly, returning a typed ValidationResult.
|
|
602
|
+
"""
|
|
603
|
+
validator = Validator(
|
|
604
|
+
data=data,
|
|
605
|
+
schema=schema,
|
|
606
|
+
registry=registry,
|
|
607
|
+
messages=messages,
|
|
608
|
+
)
|
|
609
|
+
return await validator.validate()
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
__all__ = ["ValidationResult", "Validator", "validate"]
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from swiftpy.websockets.connection import (
|
|
4
|
+
WebSocket,
|
|
5
|
+
WebSocketConnection,
|
|
6
|
+
WebSocketDisconnect,
|
|
7
|
+
WebSocketException,
|
|
8
|
+
WebSocketState,
|
|
9
|
+
)
|
|
10
|
+
from swiftpy.websockets.manager import WebSocketManager
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"WebSocket",
|
|
14
|
+
"WebSocketConnection",
|
|
15
|
+
"WebSocketDisconnect",
|
|
16
|
+
"WebSocketException",
|
|
17
|
+
"WebSocketManager",
|
|
18
|
+
"WebSocketState",
|
|
19
|
+
]
|