nyssa-ai-result 0.2.2__tar.gz

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.
@@ -0,0 +1,38 @@
1
+ # Ignore dot directories at every level (tracked files remain tracked).
2
+ .*/
3
+ !.github/
4
+ !.github/**
5
+ !.nyssa-ai/
6
+ !.nyssa-ai/dev-standards/
7
+ !.nyssa-ai/dev-standards/**
8
+ !.compound-engineering/
9
+ !.compound-engineering/config.yaml
10
+ !.compound-engineering/config.example.yaml
11
+
12
+ **/bin/
13
+ **/obj/
14
+ **/TestResults/
15
+ *.user
16
+ *.suo
17
+ *.nupkg
18
+ *.snupkg
19
+ .env
20
+ .env.*
21
+ !.env.example
22
+ **/secrets.json
23
+ **/config-manifest.json
24
+ !docs/specs/**/config-manifest.json
25
+
26
+ # Build, dependency, and test runner outputs
27
+ __pycache__/
28
+ *.py[cod]
29
+ .pytest_cache/
30
+ .mypy_cache/
31
+ node_modules/
32
+ dist/
33
+
34
+ # Mandatory repository-local scratch directory (REPO-SCRATCH)
35
+ .temp/
36
+ .worktrees/
37
+ .compound-engineering/*.local.yaml
38
+ .context/compound-engineering/
@@ -0,0 +1,134 @@
1
+ Metadata-Version: 2.5
2
+ Name: nyssa-ai-result
3
+ Version: 0.2.2
4
+ Summary: Railway-oriented programming (ROP) Result pattern for functional error handling in Python.
5
+ Project-URL: Homepage, https://github.com/NyssaAI/NyssaAI.Shared
6
+ Project-URL: Repository, https://github.com/NyssaAI/NyssaAI.Shared.git
7
+ Project-URL: Issues, https://github.com/NyssaAI/NyssaAI.Shared/issues
8
+ Author-email: NyssaAI <oss@nyssa.ai>
9
+ License: Apache-2.0
10
+ Keywords: error-handling,functional,railway-oriented-programming,result
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.12
21
+ Provides-Extra: dev
22
+ Requires-Dist: mypy>=1.9.0; extra == 'dev'
23
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
24
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
25
+ Requires-Dist: ruff>=0.3.0; extra == 'dev'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # NyssaAI.Result (Python)
29
+
30
+ `nyssa-ai-result` gives Python applications a consistent way to report whether an operation succeeded and, when it did not, what went wrong. A function returns `Result[T]` holding either the successful payload or structured errors.
31
+
32
+ The library implements Railway-Oriented Programming (ROP) with pure combinators and explicit exception boundaries, adhering to Jeremy Maynor's `dev-standards` (v0.6.5).
33
+
34
+ ---
35
+
36
+ ## Core Invariant: Pure Combinators vs. Explicit Exception Boundaries
37
+
38
+ > **Fail fast on programmer defects; use `Result` for expected operational outcomes.**
39
+ > Unexpected exceptions (e.g., `AttributeError`, `ZeroDivisionError`, `KeyError`, coding defects) bubble immediately.
40
+ > External fallible I/O (e.g., HTTP drivers, database adapters) must be wrapped exclusively at explicit boundaries via `Result.try_` / `Result.try_async`.
41
+
42
+ ### 1. Pure Monadic Combinators (`then`, `then_async`, `transform`, `transform_async`)
43
+ Monadic chaining methods do **not** swallow or intercept unexpected exceptions in delegates:
44
+ - If the current result is a failure, errors propagate immediately without executing the delegate.
45
+ - If the current result is a success, the delegate is executed directly. Any unexpected exception bubbles up the stack immediately so unit tests and telemetry identify the defect immediately.
46
+
47
+ ### 2. Explicit Exception Boundaries (`Result.try_`, `Result.try_async`)
48
+ Volatile, external fallible boundaries catch exceptions and convert them into structured failures:
49
+ - Standard translation maps exceptions to `Error` values while preserving the causal chain and stack trace.
50
+ - Custom error handlers (`error_handler: Callable[[Exception], Error]`) allow translation to specific categories.
51
+ - Cancellation evidence (`asyncio.CancelledError`, `TimeoutError`, cancellation tokens) classifies outcomes accurately as `ErrorCategory.CANCELED` vs. `ErrorCategory.UNAVAILABLE`.
52
+
53
+ ---
54
+
55
+ ## Quickstart
56
+
57
+ ```python
58
+ from nyssa_ai_result import Error, ErrorCategory, Guard, Result, ok, fail
59
+
60
+ # 1. Success and Failure factories
61
+ res_ok = Result.success(42)
62
+ res_fail = Result.failure(Error.from_message("Entity not found", ErrorCategory.NOT_FOUND))
63
+
64
+ # Shorthand helpers
65
+ s = ok("payload")
66
+ f = fail("something broke")
67
+
68
+ # 2. Inspecting results
69
+ if res_ok:
70
+ print(f"Value: {res_ok.value}")
71
+
72
+ if res_fail.is_failure:
73
+ for err in res_fail.errors:
74
+ print(f"[{err.category}] {err.user_message}: {err.technical_message}")
75
+
76
+ # 3. Monadic Chaining (Railway-Oriented Pipeline)
77
+ pipeline_result = (
78
+ Guard.against.null_or_whitespace(username, parameter_name="username")
79
+ .then(lambda valid_name: find_user(valid_name))
80
+ .transform(lambda user: user.to_dto())
81
+ )
82
+
83
+ # 4. Explicit Exception Boundary for External I/O
84
+ db_result = Result.try_(
85
+ lambda: database_driver.query_user(user_id),
86
+ error_handler=lambda exc: Error.from_messages(
87
+ user_message="Database service currently unavailable.",
88
+ technical_message=f"Driver failure: {exc}",
89
+ category=ErrorCategory.UNAVAILABLE,
90
+ )
91
+ )
92
+ ```
93
+
94
+ ---
95
+
96
+ ## API Overview
97
+
98
+ ### `Result[T]`
99
+ - `value: T`: The success payload (meaningful only when `is_success` is True).
100
+ - `errors: tuple[Error, ...]`: Structured failures (empty on success).
101
+ - `is_success / ok: bool`: True on success, False on failure.
102
+ - `is_failure: bool`: True on failure, False on success.
103
+ - `then(next_op: Callable[[T], Result[U]]) -> Result[U]`: Monadic bind (synchronous).
104
+ - `then_async(next_op: Callable[[T], Awaitable[Result[U]]]) -> Result[U]`: Monadic bind (asynchronous).
105
+ - `transform(fn: Callable[[T], U]) -> Result[U]`: Functor projection map (synchronous).
106
+ - `transform_async(fn: Callable[[T], Awaitable[U]]) -> Result[U]`: Functor projection map (asynchronous).
107
+ - `resolve(on_success, on_failure) -> R`: Fold / match into a unified value.
108
+ - `resolve_async(on_success, on_failure) -> R`: Async fold / match.
109
+ - `throw_if_error() -> T` / `unwrap() -> T`: Returns payload on success, or raises `ResultException`.
110
+ - `try_get_value() -> tuple[bool, T | None]`: Safe extraction tuple.
111
+ - `try_(action, error_handler=None, cancellation_token=None)`: Synchronous explicit boundary.
112
+ - `try_async(action, error_handler=None, cancellation_token=None)`: Asynchronous explicit boundary.
113
+
114
+ ### `Error`
115
+ - `user_message: str`: Message safe for end users.
116
+ - `technical_message: str | None`: Diagnostic details, exception types, and chained causes.
117
+ - `category: ErrorCategory`: Categorization (`UNEXPECTED`, `VALIDATION`, `NOT_FOUND`, `CONFLICT`, `FORBIDDEN`, `UNAVAILABLE`, `CANCELED`, `INDETERMINATE`).
118
+ - `stack_trace: str | None`: Captured traceback if created from an exception.
119
+ - Named factories: `from_message`, `from_messages`, `from_exception`, `from_exceptions`, `canceled`, `from_cancellation`, `from_caught`, `at_least_one`.
120
+
121
+ ### `Guard.against`
122
+ Input validation guards returning `Result[T]` with `ErrorCategory.VALIDATION`:
123
+ - `null` / `none`
124
+ - `null_or_empty`
125
+ - `null_or_whitespace`
126
+ - `out_of_range(value, min_val, max_val)`
127
+ - `less_than`, `less_than_or_equal`
128
+ - `greater_than`, `greater_than_or_equal`
129
+ - `length_out_of_range(string, min_len, max_len)`
130
+ - `pattern_mismatch(string, pattern)`
131
+ - `true(cond / value, predicate)`
132
+ - `false(cond / value, predicate)`
133
+ - `contains(collection, predicate)`
134
+ - `not_contains(collection, predicate)`
@@ -0,0 +1,107 @@
1
+ # NyssaAI.Result (Python)
2
+
3
+ `nyssa-ai-result` gives Python applications a consistent way to report whether an operation succeeded and, when it did not, what went wrong. A function returns `Result[T]` holding either the successful payload or structured errors.
4
+
5
+ The library implements Railway-Oriented Programming (ROP) with pure combinators and explicit exception boundaries, adhering to Jeremy Maynor's `dev-standards` (v0.6.5).
6
+
7
+ ---
8
+
9
+ ## Core Invariant: Pure Combinators vs. Explicit Exception Boundaries
10
+
11
+ > **Fail fast on programmer defects; use `Result` for expected operational outcomes.**
12
+ > Unexpected exceptions (e.g., `AttributeError`, `ZeroDivisionError`, `KeyError`, coding defects) bubble immediately.
13
+ > External fallible I/O (e.g., HTTP drivers, database adapters) must be wrapped exclusively at explicit boundaries via `Result.try_` / `Result.try_async`.
14
+
15
+ ### 1. Pure Monadic Combinators (`then`, `then_async`, `transform`, `transform_async`)
16
+ Monadic chaining methods do **not** swallow or intercept unexpected exceptions in delegates:
17
+ - If the current result is a failure, errors propagate immediately without executing the delegate.
18
+ - If the current result is a success, the delegate is executed directly. Any unexpected exception bubbles up the stack immediately so unit tests and telemetry identify the defect immediately.
19
+
20
+ ### 2. Explicit Exception Boundaries (`Result.try_`, `Result.try_async`)
21
+ Volatile, external fallible boundaries catch exceptions and convert them into structured failures:
22
+ - Standard translation maps exceptions to `Error` values while preserving the causal chain and stack trace.
23
+ - Custom error handlers (`error_handler: Callable[[Exception], Error]`) allow translation to specific categories.
24
+ - Cancellation evidence (`asyncio.CancelledError`, `TimeoutError`, cancellation tokens) classifies outcomes accurately as `ErrorCategory.CANCELED` vs. `ErrorCategory.UNAVAILABLE`.
25
+
26
+ ---
27
+
28
+ ## Quickstart
29
+
30
+ ```python
31
+ from nyssa_ai_result import Error, ErrorCategory, Guard, Result, ok, fail
32
+
33
+ # 1. Success and Failure factories
34
+ res_ok = Result.success(42)
35
+ res_fail = Result.failure(Error.from_message("Entity not found", ErrorCategory.NOT_FOUND))
36
+
37
+ # Shorthand helpers
38
+ s = ok("payload")
39
+ f = fail("something broke")
40
+
41
+ # 2. Inspecting results
42
+ if res_ok:
43
+ print(f"Value: {res_ok.value}")
44
+
45
+ if res_fail.is_failure:
46
+ for err in res_fail.errors:
47
+ print(f"[{err.category}] {err.user_message}: {err.technical_message}")
48
+
49
+ # 3. Monadic Chaining (Railway-Oriented Pipeline)
50
+ pipeline_result = (
51
+ Guard.against.null_or_whitespace(username, parameter_name="username")
52
+ .then(lambda valid_name: find_user(valid_name))
53
+ .transform(lambda user: user.to_dto())
54
+ )
55
+
56
+ # 4. Explicit Exception Boundary for External I/O
57
+ db_result = Result.try_(
58
+ lambda: database_driver.query_user(user_id),
59
+ error_handler=lambda exc: Error.from_messages(
60
+ user_message="Database service currently unavailable.",
61
+ technical_message=f"Driver failure: {exc}",
62
+ category=ErrorCategory.UNAVAILABLE,
63
+ )
64
+ )
65
+ ```
66
+
67
+ ---
68
+
69
+ ## API Overview
70
+
71
+ ### `Result[T]`
72
+ - `value: T`: The success payload (meaningful only when `is_success` is True).
73
+ - `errors: tuple[Error, ...]`: Structured failures (empty on success).
74
+ - `is_success / ok: bool`: True on success, False on failure.
75
+ - `is_failure: bool`: True on failure, False on success.
76
+ - `then(next_op: Callable[[T], Result[U]]) -> Result[U]`: Monadic bind (synchronous).
77
+ - `then_async(next_op: Callable[[T], Awaitable[Result[U]]]) -> Result[U]`: Monadic bind (asynchronous).
78
+ - `transform(fn: Callable[[T], U]) -> Result[U]`: Functor projection map (synchronous).
79
+ - `transform_async(fn: Callable[[T], Awaitable[U]]) -> Result[U]`: Functor projection map (asynchronous).
80
+ - `resolve(on_success, on_failure) -> R`: Fold / match into a unified value.
81
+ - `resolve_async(on_success, on_failure) -> R`: Async fold / match.
82
+ - `throw_if_error() -> T` / `unwrap() -> T`: Returns payload on success, or raises `ResultException`.
83
+ - `try_get_value() -> tuple[bool, T | None]`: Safe extraction tuple.
84
+ - `try_(action, error_handler=None, cancellation_token=None)`: Synchronous explicit boundary.
85
+ - `try_async(action, error_handler=None, cancellation_token=None)`: Asynchronous explicit boundary.
86
+
87
+ ### `Error`
88
+ - `user_message: str`: Message safe for end users.
89
+ - `technical_message: str | None`: Diagnostic details, exception types, and chained causes.
90
+ - `category: ErrorCategory`: Categorization (`UNEXPECTED`, `VALIDATION`, `NOT_FOUND`, `CONFLICT`, `FORBIDDEN`, `UNAVAILABLE`, `CANCELED`, `INDETERMINATE`).
91
+ - `stack_trace: str | None`: Captured traceback if created from an exception.
92
+ - Named factories: `from_message`, `from_messages`, `from_exception`, `from_exceptions`, `canceled`, `from_cancellation`, `from_caught`, `at_least_one`.
93
+
94
+ ### `Guard.against`
95
+ Input validation guards returning `Result[T]` with `ErrorCategory.VALIDATION`:
96
+ - `null` / `none`
97
+ - `null_or_empty`
98
+ - `null_or_whitespace`
99
+ - `out_of_range(value, min_val, max_val)`
100
+ - `less_than`, `less_than_or_equal`
101
+ - `greater_than`, `greater_than_or_equal`
102
+ - `length_out_of_range(string, min_len, max_len)`
103
+ - `pattern_mismatch(string, pattern)`
104
+ - `true(cond / value, predicate)`
105
+ - `false(cond / value, predicate)`
106
+ - `contains(collection, predicate)`
107
+ - `not_contains(collection, predicate)`
@@ -0,0 +1,64 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "nyssa-ai-result"
7
+ version = "0.2.2"
8
+ description = "Railway-oriented programming (ROP) Result pattern for functional error handling in Python."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [
13
+ { name = "NyssaAI", email = "oss@nyssa.ai" }
14
+ ]
15
+ keywords = [
16
+ "result",
17
+ "railway-oriented-programming",
18
+ "functional",
19
+ "error-handling"
20
+ ]
21
+ classifiers = [
22
+ "Development Status :: 4 - Beta",
23
+ "Intended Audience :: Developers",
24
+ "License :: OSI Approved :: Apache Software License",
25
+ "Operating System :: OS Independent",
26
+ "Programming Language :: Python :: 3",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Programming Language :: Python :: 3.13",
29
+ "Topic :: Software Development :: Libraries :: Python Modules",
30
+ "Typing :: Typed",
31
+ ]
32
+ dependencies = []
33
+
34
+ [project.optional-dependencies]
35
+ dev = [
36
+ "pytest>=8.0.0",
37
+ "pytest-cov>=4.0.0",
38
+ "mypy>=1.9.0",
39
+ "ruff>=0.3.0",
40
+ ]
41
+
42
+ [project.urls]
43
+ Homepage = "https://github.com/NyssaAI/NyssaAI.Shared"
44
+ Repository = "https://github.com/NyssaAI/NyssaAI.Shared.git"
45
+ Issues = "https://github.com/NyssaAI/NyssaAI.Shared/issues"
46
+
47
+ [tool.hatch.build.targets.wheel]
48
+ packages = ["src/nyssa_ai_result"]
49
+
50
+ [tool.pytest.ini_options]
51
+ testpaths = ["test/unit", "test/use_case"]
52
+ python_files = ["test_*.py", "*_test.py"]
53
+ pythonpath = ["src"]
54
+
55
+ [tool.mypy]
56
+ strict = true
57
+ python_version = "3.12"
58
+ warn_return_any = true
59
+ warn_unused_configs = true
60
+ mypy_path = "src"
61
+
62
+ [tool.ruff]
63
+ line-length = 120
64
+ target-version = "py312"
@@ -0,0 +1,25 @@
1
+ # Responsibility: Export the public surface of nyssa_ai_result.
2
+ # Public interface:
3
+ # (none)
4
+ """Railway-oriented programming Result pattern for Python."""
5
+
6
+ from nyssa_ai_result.error import Error
7
+ from nyssa_ai_result.error_category import ErrorCategory
8
+ from nyssa_ai_result.guard import Guard
9
+ from nyssa_ai_result.result import Err, Ok, Result, fail, fail_error, ok, try_, try_async
10
+ from nyssa_ai_result.result_exception import ResultException
11
+
12
+ __all__ = [
13
+ "Err",
14
+ "Error",
15
+ "ErrorCategory",
16
+ "Guard",
17
+ "Ok",
18
+ "Result",
19
+ "ResultException",
20
+ "fail",
21
+ "fail_error",
22
+ "ok",
23
+ "try_",
24
+ "try_async",
25
+ ]
@@ -0,0 +1,274 @@
1
+ # Responsibility: Represent failure information as an immutable value.
2
+ # Public interface:
3
+ # +-- CANCELED_USER_MESSAGE
4
+ # +-- DEFAULT_USER_MESSAGE
5
+ # +-- Error
6
+ # | +-- CANCELED_USER_MESSAGE
7
+ # | +-- DEFAULT_USER_MESSAGE
8
+ # | +-- TIMED_OUT_USER_MESSAGE
9
+ # | +-- at_least_one(errors)
10
+ # | +-- canceled(canceled)
11
+ # | +-- category
12
+ # | +-- cause_type
13
+ # | +-- from_cancellation(canceled, caller_token)
14
+ # | +-- from_caught(exception, caller_token)
15
+ # | +-- from_exception(exception, user_message, category)
16
+ # | +-- from_exceptions(exception_or_exceptions, user_message, category)
17
+ # | +-- from_message(message, category)
18
+ # | +-- from_messages(user_message, technical_message, category, cause_type)
19
+ # | +-- has_stack_trace
20
+ # | +-- message
21
+ # | +-- stack_trace
22
+ # | +-- technical_message
23
+ # | `-- user_message
24
+ # `-- TIMED_OUT_USER_MESSAGE
25
+ """Immutable description of a failure for functional error handling."""
26
+
27
+ from __future__ import annotations
28
+
29
+ import asyncio
30
+ import traceback
31
+ from collections.abc import Iterable
32
+ from dataclasses import dataclass
33
+
34
+ from nyssa_ai_result.error_category import ErrorCategory
35
+ from nyssa_ai_result.result_exception import ResultException
36
+
37
+ DEFAULT_USER_MESSAGE: str = "An unexpected error occurred"
38
+ CANCELED_USER_MESSAGE: str = "The operation was cancelled."
39
+ TIMED_OUT_USER_MESSAGE: str = "The operation timed out."
40
+ _MISSING_EXCEPTION_DETAIL: str = "A failure was reported without any exception detail"
41
+ _MISSING_ERROR_DETAIL: str = "A failure was reported without any error"
42
+
43
+
44
+ def _resolve_category(cat: ErrorCategory | str) -> ErrorCategory:
45
+ if isinstance(cat, ErrorCategory):
46
+ return cat
47
+ normalized = str(cat).strip().lower().replace("_", "")
48
+ for member in ErrorCategory:
49
+ if member.value.lower() == normalized or member.name.lower() == normalized:
50
+ return member
51
+ return ErrorCategory.UNEXPECTED
52
+
53
+
54
+ def _describe_exception(exc: BaseException) -> str:
55
+ chain: list[str] = []
56
+ current: BaseException | None = exc
57
+ seen: set[int] = set()
58
+ while current is not None and id(current) not in seen:
59
+ seen.add(id(current))
60
+ chain.append(f"{type(current).__name__}: {current}")
61
+ current = current.__cause__ or current.__context__
62
+ return " ---> ".join(chain)
63
+
64
+
65
+ def _capture_stack_trace(exc: BaseException) -> str | None:
66
+ if exc.__traceback__ is None:
67
+ return None
68
+ lines = traceback.format_exception(type(exc), exc, exc.__traceback__)
69
+ formatted = "".join(lines).strip()
70
+ return formatted if formatted else None
71
+
72
+
73
+ def _is_token_canceled(caller_token: object | None) -> bool:
74
+ if caller_token is None:
75
+ return False
76
+ if isinstance(caller_token, bool):
77
+ return caller_token
78
+ if hasattr(caller_token, "is_cancellation_requested"):
79
+ return bool(getattr(caller_token, "is_cancellation_requested"))
80
+ if hasattr(caller_token, "is_set") and callable(getattr(caller_token, "is_set")):
81
+ return bool(caller_token.is_set())
82
+ return False
83
+
84
+
85
+ @dataclass(frozen=True, slots=True)
86
+ class Error:
87
+ """Immutable failure details safe for boundaries and diagnostics."""
88
+
89
+ user_message: str = DEFAULT_USER_MESSAGE
90
+ technical_message: str | None = None
91
+ category: ErrorCategory = ErrorCategory.UNEXPECTED
92
+ stack_trace: str | None = None
93
+ cause_type: str | None = None
94
+
95
+ DEFAULT_USER_MESSAGE: str = DEFAULT_USER_MESSAGE
96
+ CANCELED_USER_MESSAGE: str = CANCELED_USER_MESSAGE
97
+ TIMED_OUT_USER_MESSAGE: str = TIMED_OUT_USER_MESSAGE
98
+
99
+ @property
100
+ def message(self) -> str:
101
+ """Get diagnostic message if present, otherwise user message."""
102
+ return self.technical_message if self.technical_message else self.user_message
103
+
104
+ @property
105
+ def has_stack_trace(self) -> bool:
106
+ """Return True when a non-empty stack trace was captured."""
107
+ return bool(self.stack_trace and self.stack_trace.strip())
108
+
109
+ @classmethod
110
+ def from_message(
111
+ cls,
112
+ message: str | None = None,
113
+ category: ErrorCategory | str = ErrorCategory.UNEXPECTED,
114
+ ) -> Error:
115
+ """Create an error where message serves user and technical contexts."""
116
+ resolved = message if message is not None else DEFAULT_USER_MESSAGE
117
+ return cls(
118
+ user_message=resolved,
119
+ technical_message=resolved,
120
+ category=_resolve_category(category),
121
+ stack_trace=None,
122
+ cause_type=None,
123
+ )
124
+
125
+ @classmethod
126
+ def from_messages(
127
+ cls,
128
+ user_message: str | None = None,
129
+ technical_message: str | None = None,
130
+ category: ErrorCategory | str = ErrorCategory.UNEXPECTED,
131
+ cause_type: str | None = None,
132
+ ) -> Error:
133
+ """Create an error with distinct user and technical messages."""
134
+ user_res = user_message if user_message is not None else DEFAULT_USER_MESSAGE
135
+ tech_res = technical_message if technical_message is not None else user_res
136
+ return cls(
137
+ user_message=user_res,
138
+ technical_message=tech_res,
139
+ category=_resolve_category(category),
140
+ stack_trace=None,
141
+ cause_type=cause_type,
142
+ )
143
+
144
+ @classmethod
145
+ def from_exception(
146
+ cls,
147
+ exception: BaseException | None,
148
+ user_message: str = DEFAULT_USER_MESSAGE,
149
+ category: ErrorCategory | str = ErrorCategory.UNEXPECTED,
150
+ ) -> Error:
151
+ """Create an error capturing message chain and stack trace from an exception."""
152
+ if exception is None:
153
+ return cls(
154
+ user_message=user_message,
155
+ technical_message=_MISSING_EXCEPTION_DETAIL,
156
+ category=_resolve_category(category),
157
+ stack_trace=None,
158
+ cause_type=None,
159
+ )
160
+ return cls(
161
+ user_message=user_message,
162
+ technical_message=_describe_exception(exception),
163
+ category=_resolve_category(category),
164
+ stack_trace=_capture_stack_trace(exception),
165
+ cause_type=type(exception).__name__,
166
+ )
167
+
168
+ @classmethod
169
+ def from_exceptions(
170
+ cls,
171
+ exception_or_exceptions: BaseException | Iterable[BaseException] | None,
172
+ user_message: str = DEFAULT_USER_MESSAGE,
173
+ category: ErrorCategory | str = ErrorCategory.UNEXPECTED,
174
+ ) -> tuple[Error, ...]:
175
+ """Expand an exception, group, or sequence into flat structured errors."""
176
+ resolved_category = _resolve_category(category)
177
+ if exception_or_exceptions is None:
178
+ return (cls.from_exception(None, user_message, resolved_category),)
179
+
180
+ if isinstance(exception_or_exceptions, ResultException):
181
+ result_errors: tuple[Error, ...] = getattr(exception_or_exceptions, "errors", ())
182
+ if result_errors:
183
+ return result_errors
184
+
185
+ if isinstance(exception_or_exceptions, BaseExceptionGroup):
186
+ accumulated: list[Error] = []
187
+ for nested in exception_or_exceptions.exceptions:
188
+ accumulated.extend(cls.from_exceptions(nested, user_message, resolved_category))
189
+ return tuple(accumulated) if accumulated else (cls.from_exception(exception_or_exceptions, user_message, resolved_category),)
190
+
191
+ if isinstance(exception_or_exceptions, BaseException):
192
+ return (cls.from_exception(exception_or_exceptions, user_message, resolved_category),)
193
+
194
+ collected: list[Error] = []
195
+ for exc in exception_or_exceptions:
196
+ collected.extend(cls.from_exceptions(exc, user_message, resolved_category))
197
+ return tuple(collected) if collected else (cls.from_exception(None, user_message, resolved_category),)
198
+
199
+ @classmethod
200
+ def canceled(cls, canceled: BaseException | None = None) -> Error:
201
+ """Create a cancellation error carrying ErrorCategory.CANCELED."""
202
+ tech = (
203
+ f"The operation was cancelled before it finished: {type(canceled).__name__}"
204
+ if canceled is not None
205
+ else f"The operation was cancelled before it finished: {_MISSING_EXCEPTION_DETAIL}"
206
+ )
207
+ stack = _capture_stack_trace(canceled) if canceled is not None else None
208
+ return cls(
209
+ user_message=CANCELED_USER_MESSAGE,
210
+ technical_message=tech,
211
+ category=ErrorCategory.CANCELED,
212
+ stack_trace=stack,
213
+ cause_type=type(canceled).__name__ if canceled is not None else None,
214
+ )
215
+
216
+ @classmethod
217
+ def from_cancellation(
218
+ cls,
219
+ canceled: BaseException | None = None,
220
+ caller_token: object | None = None,
221
+ ) -> Error:
222
+ """Classify a cancellation by caller evidence versus timeout."""
223
+ if canceled is None:
224
+ return cls.canceled(None)
225
+ if _is_token_canceled(caller_token):
226
+ return cls.canceled(canceled)
227
+ if isinstance(canceled, TimeoutError):
228
+ return cls.from_exception(canceled, TIMED_OUT_USER_MESSAGE, ErrorCategory.UNAVAILABLE)
229
+ if caller_token is not None and not _is_token_canceled(caller_token):
230
+ return cls.from_exception(canceled, TIMED_OUT_USER_MESSAGE, ErrorCategory.UNAVAILABLE)
231
+ return cls.canceled(canceled)
232
+
233
+ @classmethod
234
+ def from_caught(
235
+ cls,
236
+ exception: BaseException | None,
237
+ caller_token: object | None = None,
238
+ ) -> tuple[Error, ...]:
239
+ """Translate any caught exception at an adapter boundary."""
240
+ if exception is None:
241
+ return (cls.from_exception(None),)
242
+ if isinstance(exception, ResultException):
243
+ result_errors: tuple[Error, ...] = getattr(exception, "errors", ())
244
+ if result_errors:
245
+ return result_errors
246
+ if isinstance(exception, (asyncio.CancelledError, GeneratorExit, TimeoutError)):
247
+ return (cls.from_cancellation(exception, caller_token),)
248
+ return cls.from_exceptions(exception)
249
+
250
+ @staticmethod
251
+ def at_least_one(errors: Iterable[Error | None] | None) -> tuple[Error, ...]:
252
+ """Normalize an error sequence, substituting a sentinel if empty."""
253
+ if errors is None:
254
+ return (
255
+ Error(
256
+ user_message=DEFAULT_USER_MESSAGE,
257
+ technical_message=_MISSING_ERROR_DETAIL,
258
+ category=ErrorCategory.UNEXPECTED,
259
+ stack_trace=None,
260
+ cause_type=None,
261
+ ),
262
+ )
263
+ valid = [e for e in errors if e is not None]
264
+ if not valid:
265
+ return (
266
+ Error(
267
+ user_message=DEFAULT_USER_MESSAGE,
268
+ technical_message=_MISSING_ERROR_DETAIL,
269
+ category=ErrorCategory.UNEXPECTED,
270
+ stack_trace=None,
271
+ cause_type=None,
272
+ ),
273
+ )
274
+ return tuple(valid)
@@ -0,0 +1,27 @@
1
+ # Responsibility: Define categories classifying failure outcomes for railway-oriented results.
2
+ # Public interface:
3
+ # `-- ErrorCategory
4
+ # +-- CANCELED
5
+ # +-- CONFLICT
6
+ # +-- FORBIDDEN
7
+ # +-- INDETERMINATE
8
+ # +-- NOT_FOUND
9
+ # +-- UNAVAILABLE
10
+ # +-- UNEXPECTED
11
+ # `-- VALIDATION
12
+ """Failure categories for structured errors."""
13
+
14
+ from enum import StrEnum
15
+
16
+
17
+ class ErrorCategory(StrEnum):
18
+ """Categorizes the reason for a result failure."""
19
+
20
+ UNEXPECTED = "Unexpected"
21
+ VALIDATION = "Validation"
22
+ NOT_FOUND = "NotFound"
23
+ CONFLICT = "Conflict"
24
+ FORBIDDEN = "Forbidden"
25
+ UNAVAILABLE = "Unavailable"
26
+ CANCELED = "Canceled"
27
+ INDETERMINATE = "Indeterminate"