krons 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.
- kronos/__init__.py +0 -0
- kronos/core/__init__.py +145 -0
- kronos/core/broadcaster.py +116 -0
- kronos/core/element.py +225 -0
- kronos/core/event.py +316 -0
- kronos/core/eventbus.py +116 -0
- kronos/core/flow.py +356 -0
- kronos/core/graph.py +442 -0
- kronos/core/node.py +982 -0
- kronos/core/pile.py +575 -0
- kronos/core/processor.py +494 -0
- kronos/core/progression.py +296 -0
- kronos/enforcement/__init__.py +57 -0
- kronos/enforcement/common/__init__.py +34 -0
- kronos/enforcement/common/boolean.py +85 -0
- kronos/enforcement/common/choice.py +97 -0
- kronos/enforcement/common/mapping.py +118 -0
- kronos/enforcement/common/model.py +102 -0
- kronos/enforcement/common/number.py +98 -0
- kronos/enforcement/common/string.py +140 -0
- kronos/enforcement/context.py +129 -0
- kronos/enforcement/policy.py +80 -0
- kronos/enforcement/registry.py +153 -0
- kronos/enforcement/rule.py +312 -0
- kronos/enforcement/service.py +370 -0
- kronos/enforcement/validator.py +198 -0
- kronos/errors.py +146 -0
- kronos/operations/__init__.py +32 -0
- kronos/operations/builder.py +228 -0
- kronos/operations/flow.py +398 -0
- kronos/operations/node.py +101 -0
- kronos/operations/registry.py +92 -0
- kronos/protocols.py +414 -0
- kronos/py.typed +0 -0
- kronos/services/__init__.py +81 -0
- kronos/services/backend.py +286 -0
- kronos/services/endpoint.py +608 -0
- kronos/services/hook.py +471 -0
- kronos/services/imodel.py +465 -0
- kronos/services/registry.py +115 -0
- kronos/services/utilities/__init__.py +36 -0
- kronos/services/utilities/header_factory.py +87 -0
- kronos/services/utilities/rate_limited_executor.py +271 -0
- kronos/services/utilities/rate_limiter.py +180 -0
- kronos/services/utilities/resilience.py +414 -0
- kronos/session/__init__.py +41 -0
- kronos/session/exchange.py +258 -0
- kronos/session/message.py +60 -0
- kronos/session/session.py +411 -0
- kronos/specs/__init__.py +25 -0
- kronos/specs/adapters/__init__.py +0 -0
- kronos/specs/adapters/_utils.py +45 -0
- kronos/specs/adapters/dataclass_field.py +246 -0
- kronos/specs/adapters/factory.py +56 -0
- kronos/specs/adapters/pydantic_adapter.py +309 -0
- kronos/specs/adapters/sql_ddl.py +946 -0
- kronos/specs/catalog/__init__.py +36 -0
- kronos/specs/catalog/_audit.py +39 -0
- kronos/specs/catalog/_common.py +43 -0
- kronos/specs/catalog/_content.py +59 -0
- kronos/specs/catalog/_enforcement.py +70 -0
- kronos/specs/factory.py +120 -0
- kronos/specs/operable.py +314 -0
- kronos/specs/phrase.py +405 -0
- kronos/specs/protocol.py +140 -0
- kronos/specs/spec.py +506 -0
- kronos/types/__init__.py +60 -0
- kronos/types/_sentinel.py +311 -0
- kronos/types/base.py +369 -0
- kronos/types/db_types.py +260 -0
- kronos/types/identity.py +66 -0
- kronos/utils/__init__.py +40 -0
- kronos/utils/_hash.py +234 -0
- kronos/utils/_json_dump.py +392 -0
- kronos/utils/_lazy_init.py +63 -0
- kronos/utils/_to_list.py +165 -0
- kronos/utils/_to_num.py +85 -0
- kronos/utils/_utils.py +375 -0
- kronos/utils/concurrency/__init__.py +205 -0
- kronos/utils/concurrency/_async_call.py +333 -0
- kronos/utils/concurrency/_cancel.py +122 -0
- kronos/utils/concurrency/_errors.py +96 -0
- kronos/utils/concurrency/_patterns.py +363 -0
- kronos/utils/concurrency/_primitives.py +328 -0
- kronos/utils/concurrency/_priority_queue.py +135 -0
- kronos/utils/concurrency/_resource_tracker.py +110 -0
- kronos/utils/concurrency/_run_async.py +67 -0
- kronos/utils/concurrency/_task.py +95 -0
- kronos/utils/concurrency/_utils.py +79 -0
- kronos/utils/fuzzy/__init__.py +14 -0
- kronos/utils/fuzzy/_extract_json.py +90 -0
- kronos/utils/fuzzy/_fuzzy_json.py +288 -0
- kronos/utils/fuzzy/_fuzzy_match.py +149 -0
- kronos/utils/fuzzy/_string_similarity.py +187 -0
- kronos/utils/fuzzy/_to_dict.py +396 -0
- kronos/utils/sql/__init__.py +13 -0
- kronos/utils/sql/_sql_validation.py +142 -0
- krons-0.1.0.dist-info/METADATA +70 -0
- krons-0.1.0.dist-info/RECORD +101 -0
- krons-0.1.0.dist-info/WHEEL +4 -0
- krons-0.1.0.dist-info/licenses/LICENSE +201 -0
kronos/specs/phrase.py
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
"""Phrase - typed operation template with auto-generated Options/Result types.
|
|
2
|
+
|
|
3
|
+
A Phrase wraps an async handler with:
|
|
4
|
+
- Typed inputs (auto-generates FrozenOptions dataclass)
|
|
5
|
+
- Typed outputs (auto-generates FrozenResult dataclass)
|
|
6
|
+
- Validation via Operable
|
|
7
|
+
|
|
8
|
+
Usage with decorator (custom handler):
|
|
9
|
+
from kronos.specs import Operable, phrase
|
|
10
|
+
|
|
11
|
+
consent_operable = Operable([
|
|
12
|
+
Spec("subject_id", UUID),
|
|
13
|
+
Spec("scope", str),
|
|
14
|
+
Spec("has_consent", bool),
|
|
15
|
+
Spec("token_id", UUID | None),
|
|
16
|
+
])
|
|
17
|
+
|
|
18
|
+
@phrase(consent_operable, inputs={"subject_id", "scope"}, outputs={"has_consent", "token_id"})
|
|
19
|
+
async def verify_consent(options, ctx):
|
|
20
|
+
# options is VerifyConsentOptions (frozen dataclass)
|
|
21
|
+
# return dict with output fields
|
|
22
|
+
return {"has_consent": True, "token_id": some_id}
|
|
23
|
+
|
|
24
|
+
# Call it
|
|
25
|
+
result = await verify_consent({"subject_id": id, "scope": "background"}, ctx)
|
|
26
|
+
|
|
27
|
+
Usage with CrudPattern (declarative):
|
|
28
|
+
from kronos.specs import Operable, phrase, CrudPattern
|
|
29
|
+
|
|
30
|
+
def check_has_consent(row):
|
|
31
|
+
return {"has_consent": row["status"] in {"active"} if row else False}
|
|
32
|
+
|
|
33
|
+
verify_consent = phrase(
|
|
34
|
+
consent_operable,
|
|
35
|
+
inputs={"subject_id", "scope"},
|
|
36
|
+
outputs={"has_consent", "token_id"},
|
|
37
|
+
crud=CrudPattern(
|
|
38
|
+
table="consent_tokens",
|
|
39
|
+
operation="read",
|
|
40
|
+
lookup={"subject_id", "scope"},
|
|
41
|
+
),
|
|
42
|
+
result_parser=check_has_consent,
|
|
43
|
+
name="verify_consent",
|
|
44
|
+
)
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
48
|
+
from dataclasses import dataclass
|
|
49
|
+
from enum import Enum
|
|
50
|
+
from types import MappingProxyType
|
|
51
|
+
from typing import Any
|
|
52
|
+
|
|
53
|
+
from kronos.types import Unset, is_unset
|
|
54
|
+
from kronos.utils.sql import validate_identifier
|
|
55
|
+
|
|
56
|
+
from .operable import Operable
|
|
57
|
+
|
|
58
|
+
__all__ = ("CrudPattern", "CrudOperation", "Phrase", "phrase")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class CrudOperation(str, Enum):
|
|
62
|
+
"""CRUD operation types for declarative phrases."""
|
|
63
|
+
|
|
64
|
+
READ = "read"
|
|
65
|
+
INSERT = "insert"
|
|
66
|
+
UPDATE = "update"
|
|
67
|
+
SOFT_DELETE = "soft_delete"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
_EMPTY_MAP: MappingProxyType = MappingProxyType({})
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True, slots=True)
|
|
74
|
+
class CrudPattern:
|
|
75
|
+
"""Declarative CRUD pattern for auto-generating phrase handlers.
|
|
76
|
+
|
|
77
|
+
Attributes:
|
|
78
|
+
table: Validated database table name (alphanumeric + underscores).
|
|
79
|
+
operation: CRUD operation type (read, insert, update, soft_delete).
|
|
80
|
+
lookup: Fields from options used in WHERE clause (for read/update/delete).
|
|
81
|
+
filters: Static key-value pairs added to WHERE clause. Use for
|
|
82
|
+
hardcoded filters like {"status": "active"}.
|
|
83
|
+
set_fields: Explicit field mappings for update. Values can be:
|
|
84
|
+
- Field name (str): copy from options
|
|
85
|
+
- "ctx.{attr}": read from context (e.g., "ctx.now", "ctx.user_id")
|
|
86
|
+
- Literal value: use directly
|
|
87
|
+
defaults: Static default values for insert.
|
|
88
|
+
|
|
89
|
+
The auto-handler resolves output fields in order:
|
|
90
|
+
1. ctx metadata attribute (e.g., tenant_id — only if explicitly set)
|
|
91
|
+
2. options pass-through (if field in inputs)
|
|
92
|
+
3. row column (direct from query result)
|
|
93
|
+
4. result_parser (for computed fields)
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
table: str
|
|
97
|
+
operation: CrudOperation | str = CrudOperation.READ
|
|
98
|
+
lookup: frozenset[str] = frozenset()
|
|
99
|
+
filters: Mapping[str, Any] = None # type: ignore[assignment]
|
|
100
|
+
set_fields: Mapping[str, Any] = None # type: ignore[assignment]
|
|
101
|
+
defaults: Mapping[str, Any] = None # type: ignore[assignment]
|
|
102
|
+
|
|
103
|
+
def __post_init__(self):
|
|
104
|
+
# Validate table name against SQL injection
|
|
105
|
+
validate_identifier(self.table, "table")
|
|
106
|
+
# Normalize operation to enum
|
|
107
|
+
if isinstance(self.operation, str):
|
|
108
|
+
object.__setattr__(self, "operation", CrudOperation(self.operation))
|
|
109
|
+
# Normalize lookup to frozenset
|
|
110
|
+
if not isinstance(self.lookup, frozenset):
|
|
111
|
+
object.__setattr__(self, "lookup", frozenset(self.lookup))
|
|
112
|
+
# Normalize None mappings to immutable empty maps; freeze mutable dicts
|
|
113
|
+
object.__setattr__(
|
|
114
|
+
self, "filters",
|
|
115
|
+
_EMPTY_MAP if self.filters is None else MappingProxyType(dict(self.filters)),
|
|
116
|
+
)
|
|
117
|
+
object.__setattr__(
|
|
118
|
+
self, "set_fields",
|
|
119
|
+
_EMPTY_MAP if self.set_fields is None
|
|
120
|
+
else MappingProxyType(dict(self.set_fields)),
|
|
121
|
+
)
|
|
122
|
+
object.__setattr__(
|
|
123
|
+
self, "defaults",
|
|
124
|
+
_EMPTY_MAP if self.defaults is None
|
|
125
|
+
else MappingProxyType(dict(self.defaults)),
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Phrase:
|
|
130
|
+
"""A typed operation template with auto-generated Options/Result types.
|
|
131
|
+
|
|
132
|
+
Phrases can be created two ways:
|
|
133
|
+
1. With a custom handler (decorator pattern)
|
|
134
|
+
2. With a CrudPattern (declarative pattern, auto-generates handler)
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
def __init__(
|
|
138
|
+
self,
|
|
139
|
+
name: str,
|
|
140
|
+
operable: Operable,
|
|
141
|
+
inputs: set[str],
|
|
142
|
+
outputs: set[str],
|
|
143
|
+
handler: Callable[..., Awaitable] | None = None,
|
|
144
|
+
crud: CrudPattern | None = None,
|
|
145
|
+
result_parser: Callable[[dict | None], dict] | None = None,
|
|
146
|
+
):
|
|
147
|
+
"""
|
|
148
|
+
Args:
|
|
149
|
+
name: Snake_case phrase name.
|
|
150
|
+
operable: Operable defining field specs for inputs/outputs.
|
|
151
|
+
inputs: Set of field names that form the options type.
|
|
152
|
+
outputs: Set of field names that form the result type.
|
|
153
|
+
handler: Async function (options, ctx) -> result dict. Required if no crud.
|
|
154
|
+
crud: CrudPattern for declarative CRUD operations. If provided, handler
|
|
155
|
+
is auto-generated.
|
|
156
|
+
result_parser: Function (row) -> dict for computed output fields.
|
|
157
|
+
Only used with crud pattern. Row may be None if not found.
|
|
158
|
+
"""
|
|
159
|
+
if handler is None and crud is None:
|
|
160
|
+
raise ValueError("Either handler or crud must be provided")
|
|
161
|
+
|
|
162
|
+
self.name = name
|
|
163
|
+
self.operable = Operable(operable.get_specs(), adapter="dataclass")
|
|
164
|
+
self.inputs = tuple(inputs)
|
|
165
|
+
self.outputs = tuple(outputs)
|
|
166
|
+
self.crud = crud
|
|
167
|
+
self.result_parser = result_parser
|
|
168
|
+
self._options_type: Any = Unset
|
|
169
|
+
self._result_type: Any = Unset
|
|
170
|
+
|
|
171
|
+
# Use provided handler or generate from crud
|
|
172
|
+
if handler is not None:
|
|
173
|
+
self.handler = handler
|
|
174
|
+
else:
|
|
175
|
+
self.handler = self._make_crud_handler()
|
|
176
|
+
|
|
177
|
+
def _make_crud_handler(self) -> Callable[..., Awaitable]:
|
|
178
|
+
"""Generate handler from CrudPattern."""
|
|
179
|
+
crud = self.crud
|
|
180
|
+
inputs = set(self.inputs)
|
|
181
|
+
outputs = set(self.outputs)
|
|
182
|
+
result_parser = self.result_parser
|
|
183
|
+
|
|
184
|
+
async def _crud_handler(options: Any, ctx: Any) -> dict:
|
|
185
|
+
# Get the query backend from context
|
|
186
|
+
query_fn = getattr(ctx, "query_fn", None)
|
|
187
|
+
if query_fn is None:
|
|
188
|
+
raise RuntimeError(
|
|
189
|
+
"Context must provide query_fn for crud patterns. "
|
|
190
|
+
"Ensure ctx.query_fn is set."
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
# Helper: check ctx metadata for a key
|
|
194
|
+
_meta = getattr(ctx, "metadata", {})
|
|
195
|
+
|
|
196
|
+
row = None
|
|
197
|
+
|
|
198
|
+
if crud.operation == CrudOperation.READ:
|
|
199
|
+
# Build WHERE from lookup fields + filters + tenant_id
|
|
200
|
+
where = {field: getattr(options, field) for field in crud.lookup}
|
|
201
|
+
where.update(crud.filters)
|
|
202
|
+
if "tenant_id" in _meta:
|
|
203
|
+
where["tenant_id"] = _meta["tenant_id"]
|
|
204
|
+
row = await query_fn(crud.table, "select_one", where, None, ctx)
|
|
205
|
+
|
|
206
|
+
elif crud.operation == CrudOperation.INSERT:
|
|
207
|
+
# Build data from input fields + defaults
|
|
208
|
+
data = {}
|
|
209
|
+
for field in inputs:
|
|
210
|
+
if hasattr(options, field):
|
|
211
|
+
data[field] = getattr(options, field)
|
|
212
|
+
# Add defaults
|
|
213
|
+
for key, value in crud.defaults.items():
|
|
214
|
+
if key not in data:
|
|
215
|
+
data[key] = value
|
|
216
|
+
# Add tenant_id
|
|
217
|
+
if "tenant_id" in _meta:
|
|
218
|
+
data["tenant_id"] = _meta["tenant_id"]
|
|
219
|
+
row = await query_fn(crud.table, "insert", None, data, ctx)
|
|
220
|
+
|
|
221
|
+
elif crud.operation == CrudOperation.UPDATE:
|
|
222
|
+
# Build WHERE from lookup fields
|
|
223
|
+
where = {field: getattr(options, field) for field in crud.lookup}
|
|
224
|
+
if "tenant_id" in _meta:
|
|
225
|
+
where["tenant_id"] = _meta["tenant_id"]
|
|
226
|
+
# Build SET data
|
|
227
|
+
data = {}
|
|
228
|
+
for key, value in crud.set_fields.items():
|
|
229
|
+
if isinstance(value, str) and value.startswith("ctx."):
|
|
230
|
+
attr_name = value[4:]
|
|
231
|
+
if attr_name in _meta:
|
|
232
|
+
data[key] = _meta[attr_name]
|
|
233
|
+
else:
|
|
234
|
+
data[key] = getattr(ctx, attr_name)
|
|
235
|
+
elif isinstance(value, str) and hasattr(options, value):
|
|
236
|
+
data[key] = getattr(options, value)
|
|
237
|
+
else:
|
|
238
|
+
data[key] = value
|
|
239
|
+
row = await query_fn(crud.table, "update", where, data, ctx)
|
|
240
|
+
|
|
241
|
+
elif crud.operation == CrudOperation.SOFT_DELETE:
|
|
242
|
+
# Build WHERE from lookup fields
|
|
243
|
+
where = {field: getattr(options, field) for field in crud.lookup}
|
|
244
|
+
if "tenant_id" in _meta:
|
|
245
|
+
where["tenant_id"] = _meta["tenant_id"]
|
|
246
|
+
# Soft delete sets is_deleted=True, deleted_at=now
|
|
247
|
+
data = {"is_deleted": True}
|
|
248
|
+
if ctx.now is not None:
|
|
249
|
+
data["deleted_at"] = ctx.now
|
|
250
|
+
row = await query_fn(crud.table, "update", where, data, ctx)
|
|
251
|
+
|
|
252
|
+
# Build result from auto-mapping + result_parser
|
|
253
|
+
result = {}
|
|
254
|
+
|
|
255
|
+
for field in outputs:
|
|
256
|
+
# Priority 1: ctx metadata attribute (only if explicitly set)
|
|
257
|
+
if field in _meta:
|
|
258
|
+
result[field] = _meta[field]
|
|
259
|
+
# Priority 2: pass-through from options
|
|
260
|
+
elif field in inputs and hasattr(options, field):
|
|
261
|
+
result[field] = getattr(options, field)
|
|
262
|
+
# Priority 3: direct from row
|
|
263
|
+
elif row and field in row:
|
|
264
|
+
result[field] = row[field]
|
|
265
|
+
|
|
266
|
+
# Priority 4: computed fields from result_parser
|
|
267
|
+
if result_parser is not None:
|
|
268
|
+
computed = result_parser(row)
|
|
269
|
+
if computed:
|
|
270
|
+
result.update(computed)
|
|
271
|
+
|
|
272
|
+
return result
|
|
273
|
+
|
|
274
|
+
return _crud_handler
|
|
275
|
+
|
|
276
|
+
async def __call__(self, options: Any, ctx: Any) -> Any:
|
|
277
|
+
# If options is already the correct type, use it directly
|
|
278
|
+
# Otherwise validate/construct from dict
|
|
279
|
+
if not isinstance(options, self.options_type):
|
|
280
|
+
options = self.operable.validate_instance(self.options_type, options)
|
|
281
|
+
result = await self.handler(options, ctx)
|
|
282
|
+
return self.operable.validate_instance(self.result_type, result)
|
|
283
|
+
|
|
284
|
+
@property
|
|
285
|
+
def options_type(self) -> Any:
|
|
286
|
+
if not is_unset(self._options_type):
|
|
287
|
+
return self._options_type
|
|
288
|
+
|
|
289
|
+
_opt_type_name = _to_pascal(self.name) + "Options"
|
|
290
|
+
self._options_type = self.operable.compose_structure(
|
|
291
|
+
_opt_type_name,
|
|
292
|
+
include=set(self.inputs),
|
|
293
|
+
frozen=True,
|
|
294
|
+
)
|
|
295
|
+
return self._options_type
|
|
296
|
+
|
|
297
|
+
@property
|
|
298
|
+
def result_type(self) -> Any:
|
|
299
|
+
if not is_unset(self._result_type):
|
|
300
|
+
return self._result_type
|
|
301
|
+
|
|
302
|
+
_res_type_name = _to_pascal(self.name) + "Result"
|
|
303
|
+
self._result_type = self.operable.compose_structure(
|
|
304
|
+
_res_type_name,
|
|
305
|
+
include=set(self.outputs),
|
|
306
|
+
frozen=True,
|
|
307
|
+
)
|
|
308
|
+
return self._result_type
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _to_pascal(snake_name: str) -> str:
|
|
312
|
+
"""Convert snake_case name to PascalCase.
|
|
313
|
+
|
|
314
|
+
Examples:
|
|
315
|
+
require_monitoring_active -> RequireMonitoringActive
|
|
316
|
+
verify_consent_token -> VerifyConsentToken
|
|
317
|
+
"""
|
|
318
|
+
return "".join(word.capitalize() for word in snake_name.split("_"))
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def phrase(
|
|
322
|
+
operable: Operable,
|
|
323
|
+
*,
|
|
324
|
+
inputs: set[str],
|
|
325
|
+
outputs: set[str],
|
|
326
|
+
name: str | None = None,
|
|
327
|
+
crud: CrudPattern | None = None,
|
|
328
|
+
result_parser: Callable[[dict | None], dict] | None = None,
|
|
329
|
+
) -> Phrase | Callable[[Callable[..., Awaitable]], Phrase]:
|
|
330
|
+
"""Create a Phrase, either as decorator or directly with CrudPattern.
|
|
331
|
+
|
|
332
|
+
Two usage modes:
|
|
333
|
+
|
|
334
|
+
1. Decorator mode (custom handler):
|
|
335
|
+
@phrase(operable, inputs={...}, outputs={...})
|
|
336
|
+
async def my_phrase(options, ctx):
|
|
337
|
+
return {...}
|
|
338
|
+
|
|
339
|
+
2. Direct mode (declarative crud):
|
|
340
|
+
my_phrase = phrase(
|
|
341
|
+
operable,
|
|
342
|
+
inputs={...},
|
|
343
|
+
outputs={...},
|
|
344
|
+
crud=CrudPattern(table="...", operation="read", lookup={...}),
|
|
345
|
+
result_parser=lambda row: {...},
|
|
346
|
+
name="my_phrase",
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
Args:
|
|
350
|
+
operable: Operable defining the field specs for inputs/outputs.
|
|
351
|
+
inputs: Set of field names that form the options type.
|
|
352
|
+
outputs: Set of field names that form the result type.
|
|
353
|
+
name: Phrase name. Required for direct mode, optional for decorator mode.
|
|
354
|
+
crud: CrudPattern for declarative CRUD. If provided, returns Phrase directly.
|
|
355
|
+
result_parser: Function (row) -> dict for computed fields. Only with crud.
|
|
356
|
+
|
|
357
|
+
Returns:
|
|
358
|
+
- If crud provided: Phrase instance directly
|
|
359
|
+
- If no crud: Decorator that wraps async function into Phrase
|
|
360
|
+
|
|
361
|
+
Examples:
|
|
362
|
+
# Decorator mode
|
|
363
|
+
@phrase(my_operable, inputs={"subject_id", "scope"}, outputs={"valid", "reason"})
|
|
364
|
+
async def verify_consent(options, ctx):
|
|
365
|
+
return {"valid": True, "reason": None}
|
|
366
|
+
|
|
367
|
+
# Direct mode with CrudPattern
|
|
368
|
+
verify_consent = phrase(
|
|
369
|
+
my_operable,
|
|
370
|
+
inputs={"subject_id", "scope"},
|
|
371
|
+
outputs={"has_consent", "token_id"},
|
|
372
|
+
crud=CrudPattern(
|
|
373
|
+
table="consent_tokens",
|
|
374
|
+
operation="read",
|
|
375
|
+
lookup={"subject_id", "scope"},
|
|
376
|
+
),
|
|
377
|
+
result_parser=lambda row: {"has_consent": row["status"] == "active" if row else False},
|
|
378
|
+
name="verify_consent",
|
|
379
|
+
)
|
|
380
|
+
"""
|
|
381
|
+
# Direct mode: crud provided, return Phrase immediately
|
|
382
|
+
if crud is not None:
|
|
383
|
+
if name is None:
|
|
384
|
+
raise ValueError("name is required when using crud pattern")
|
|
385
|
+
return Phrase(
|
|
386
|
+
name=name,
|
|
387
|
+
operable=operable,
|
|
388
|
+
inputs=inputs,
|
|
389
|
+
outputs=outputs,
|
|
390
|
+
crud=crud,
|
|
391
|
+
result_parser=result_parser,
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
# Decorator mode: return decorator function
|
|
395
|
+
def decorator(func: Callable[..., Awaitable]) -> Phrase:
|
|
396
|
+
phrase_name = name or func.__name__
|
|
397
|
+
return Phrase(
|
|
398
|
+
name=phrase_name,
|
|
399
|
+
operable=operable,
|
|
400
|
+
inputs=inputs,
|
|
401
|
+
outputs=outputs,
|
|
402
|
+
handler=func,
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
return decorator
|
kronos/specs/protocol.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# Copyright (c) 2025 - 2026, HaiyangLi <quantocean.li at gmail dot com>
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""SpecAdapter protocol: framework-agnostic field specification adapter.
|
|
5
|
+
|
|
6
|
+
Spec serves as the universal intermediate representation (IR) for typed structures.
|
|
7
|
+
Adapters implement bidirectional transformations:
|
|
8
|
+
|
|
9
|
+
Spec/Operable --[Adapter]--> Framework-specific structures
|
|
10
|
+
Framework structures --[Adapter]--> Spec/Operable
|
|
11
|
+
|
|
12
|
+
Concrete adapters:
|
|
13
|
+
- PydanticSpecAdapter: Spec <-> Pydantic FieldInfo/BaseModel
|
|
14
|
+
- DataClassSpecAdapter: Spec <-> dataclass fields/Params/DataClass
|
|
15
|
+
- SQLSpecAdapter: Spec -> SQL DDL (one-way, no instance support)
|
|
16
|
+
|
|
17
|
+
Type parameters:
|
|
18
|
+
F: Field representation (FieldInfo, dict, str)
|
|
19
|
+
S: Structure type (BaseModel, DataClass, DDL string)
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from abc import ABC, abstractmethod
|
|
25
|
+
from typing import TYPE_CHECKING, Any, Generic, TypeVar
|
|
26
|
+
|
|
27
|
+
from kronos.types._sentinel import Unset, UnsetType
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from .operable import Operable
|
|
31
|
+
from .spec import Spec
|
|
32
|
+
|
|
33
|
+
__all__ = ("SpecAdapter",)
|
|
34
|
+
|
|
35
|
+
F = TypeVar("F")
|
|
36
|
+
S = TypeVar("S")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class SpecAdapter(ABC, Generic[F]):
|
|
40
|
+
"""Abstract adapter protocol for Spec <-> framework transformations.
|
|
41
|
+
|
|
42
|
+
Required methods (abstract):
|
|
43
|
+
create_field: Spec -> F (framework field)
|
|
44
|
+
compose_structure: Operable -> structure (type or DDL string)
|
|
45
|
+
extract_specs: structure -> tuple[Spec, ...] (reverse extraction)
|
|
46
|
+
|
|
47
|
+
Optional methods (override as needed):
|
|
48
|
+
create_field_validator: Spec -> validator (framework-specific)
|
|
49
|
+
validate_instance: (structure, dict) -> instance
|
|
50
|
+
dump_instance: instance -> dict
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
@abstractmethod
|
|
55
|
+
def create_field(cls, spec: Spec) -> F:
|
|
56
|
+
"""Convert Spec to framework-specific field representation.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
spec: Field specification
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
Framework field (FieldInfo for Pydantic, dict for DataClass, str for SQL)
|
|
63
|
+
"""
|
|
64
|
+
...
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
@abstractmethod
|
|
68
|
+
def compose_structure(
|
|
69
|
+
cls,
|
|
70
|
+
op: Operable,
|
|
71
|
+
name: str,
|
|
72
|
+
/,
|
|
73
|
+
*,
|
|
74
|
+
include: set[str] | UnsetType = Unset,
|
|
75
|
+
exclude: set[str] | UnsetType = Unset,
|
|
76
|
+
frozen: bool | UnsetType = Unset,
|
|
77
|
+
base_type: type | UnsetType = Unset,
|
|
78
|
+
doc: str | UnsetType = Unset,
|
|
79
|
+
**kwargs: Any,
|
|
80
|
+
) -> Any:
|
|
81
|
+
"""Compose a structure from Operable.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
op: Operable containing Specs
|
|
85
|
+
name: Structure name (class name, table name, etc.)
|
|
86
|
+
include: Only include these field names
|
|
87
|
+
exclude: Exclude these field names
|
|
88
|
+
frozen: Whether the structure is frozen/immutable
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
Composed structure (type for Pydantic/DataClass, str for SQL DDL)
|
|
92
|
+
"""
|
|
93
|
+
...
|
|
94
|
+
|
|
95
|
+
@classmethod
|
|
96
|
+
@abstractmethod
|
|
97
|
+
def extract_specs(cls, structure: Any) -> tuple[Spec, ...]:
|
|
98
|
+
"""Extract Specs from an existing structure.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
structure: Structure to extract from (BaseModel class, DataClass, etc.)
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
Tuple of Specs representing the structure's fields
|
|
105
|
+
"""
|
|
106
|
+
...
|
|
107
|
+
|
|
108
|
+
# Optional methods
|
|
109
|
+
@classmethod
|
|
110
|
+
def create_field_validator(cls, spec: Spec) -> Any | None:
|
|
111
|
+
"""Create framework-specific validator from Spec metadata.
|
|
112
|
+
|
|
113
|
+
Override in adapters that support field validation.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
Validator object or None if not supported/not present
|
|
117
|
+
"""
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
@classmethod
|
|
121
|
+
def validate_instance(cls, structure: Any, data: dict, /) -> Any:
|
|
122
|
+
"""Validate dict data into a structure instance.
|
|
123
|
+
|
|
124
|
+
Override in adapters that produce instantiable structures.
|
|
125
|
+
|
|
126
|
+
Raises:
|
|
127
|
+
NotImplementedError: If adapter doesn't support instance creation
|
|
128
|
+
"""
|
|
129
|
+
raise NotImplementedError(f"{cls.__name__} does not support instance validation")
|
|
130
|
+
|
|
131
|
+
@classmethod
|
|
132
|
+
def dump_instance(cls, instance: Any, **kwargs) -> dict[str, Any]:
|
|
133
|
+
"""Dump a structure instance to dict.
|
|
134
|
+
|
|
135
|
+
Override in adapters that produce instantiable structures.
|
|
136
|
+
|
|
137
|
+
Raises:
|
|
138
|
+
NotImplementedError: If adapter doesn't support instance dumping
|
|
139
|
+
"""
|
|
140
|
+
raise NotImplementedError(f"{cls.__name__} does not support instance dumping")
|