python-corekit 0.4.0__py3-none-any.whl → 0.4.1__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.
@@ -0,0 +1,68 @@
1
+ """
2
+ Process-wide exception capture: catch, run one action, rethrow.
3
+
4
+ Product concerns (Postgres, ntfy, prompts) stay in the installing application.
5
+ This package owns the wrapper, built-in actions, fingerprinting, ASGI middleware,
6
+ and the ``run_task`` hook point.
7
+ """
8
+
9
+ from corekit.exceptionator.actions import (
10
+ ExceptionatorAction,
11
+ LogTracebackAction,
12
+ NoOpAction,
13
+ )
14
+ from corekit.exceptionator.asgi import (
15
+ ExceptionatorMiddleware,
16
+ get_process_exceptionator,
17
+ record_http_exception,
18
+ set_process_exceptionator,
19
+ should_record_http_exception,
20
+ )
21
+ from corekit.exceptionator.exceptionator import Exceptionator
22
+ from corekit.exceptionator.fingerprint import ExceptionFingerprint, ExceptionText
23
+ from corekit.exceptionator.guard import (
24
+ begin_handling,
25
+ end_handling,
26
+ handling_active,
27
+ is_captured,
28
+ mark_captured,
29
+ )
30
+ from corekit.exceptionator.jobs import (
31
+ clear_run_task_hook,
32
+ get_run_task_hook,
33
+ install_run_task_hook,
34
+ )
35
+ from corekit.exceptionator.models import (
36
+ CapturedException,
37
+ ExceptionatorActionName,
38
+ ExceptionContext,
39
+ ExceptionSource,
40
+ build_captured,
41
+ )
42
+
43
+ __all__ = [
44
+ "CapturedException",
45
+ "ExceptionContext",
46
+ "ExceptionFingerprint",
47
+ "ExceptionSource",
48
+ "ExceptionText",
49
+ "Exceptionator",
50
+ "ExceptionatorAction",
51
+ "ExceptionatorActionName",
52
+ "ExceptionatorMiddleware",
53
+ "LogTracebackAction",
54
+ "NoOpAction",
55
+ "begin_handling",
56
+ "build_captured",
57
+ "clear_run_task_hook",
58
+ "end_handling",
59
+ "get_process_exceptionator",
60
+ "get_run_task_hook",
61
+ "handling_active",
62
+ "install_run_task_hook",
63
+ "is_captured",
64
+ "mark_captured",
65
+ "record_http_exception",
66
+ "set_process_exceptionator",
67
+ "should_record_http_exception",
68
+ ]
@@ -0,0 +1,46 @@
1
+ """
2
+ Built-in Exceptionator actions.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from corekit.exceptionator.models import CapturedException
8
+ from corekit.observability.loggable import Loggable
9
+
10
+ __all__ = ["ExceptionatorAction", "LogTracebackAction", "NoOpAction"]
11
+
12
+
13
+ class ExceptionatorAction(Loggable):
14
+ """
15
+ Work performed after an exception is captured and before it continues.
16
+ """
17
+
18
+ def run(self, captured: CapturedException) -> None:
19
+ """
20
+ Perform the action. Must not raise.
21
+ """
22
+ raise NotImplementedError
23
+
24
+
25
+ class NoOpAction(ExceptionatorAction):
26
+ """
27
+ Catch and continue. Records nothing and publishes nothing.
28
+ """
29
+
30
+ def run(self, captured: CapturedException) -> None:
31
+ """
32
+ Do nothing with the captured exception.
33
+ """
34
+ return None
35
+
36
+
37
+ class LogTracebackAction(ExceptionatorAction):
38
+ """
39
+ Write the message and traceback. Does not store or notify.
40
+ """
41
+
42
+ def run(self, captured: CapturedException) -> None:
43
+ """
44
+ Log the incident text.
45
+ """
46
+ self.error(f"{captured.service} {captured.exception_type}: {captured.message}\n{captured.traceback_text}")
@@ -0,0 +1,115 @@
1
+ """
2
+ ASGI middleware and HTTP helpers for Exceptionator.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Awaitable, Callable
8
+ from typing import Any
9
+
10
+ from fastapi import Request
11
+ from fastapi.exceptions import RequestValidationError
12
+ from fastapi.responses import JSONResponse
13
+ from starlette.exceptions import HTTPException
14
+ from starlette.websockets import WebSocketDisconnect
15
+
16
+ from corekit.exceptionator.exceptionator import Exceptionator
17
+ from corekit.exceptionator.models import ExceptionContext, ExceptionSource
18
+
19
+ __all__ = [
20
+ "ExceptionatorMiddleware",
21
+ "get_process_exceptionator",
22
+ "record_http_exception",
23
+ "set_process_exceptionator",
24
+ "should_record_http_exception",
25
+ ]
26
+
27
+ ASGIApp = Callable[..., Awaitable[None]]
28
+
29
+ _process_exceptionator: Exceptionator | None = None
30
+
31
+
32
+ def set_process_exceptionator(exceptionator: Exceptionator) -> None:
33
+ """
34
+ Remember the process Exceptionator for middleware and HTTP handlers.
35
+ """
36
+ global _process_exceptionator
37
+ _process_exceptionator = exceptionator
38
+
39
+
40
+ def get_process_exceptionator() -> Exceptionator:
41
+ """
42
+ The Exceptionator installed for this process.
43
+ """
44
+ if _process_exceptionator is None:
45
+ raise RuntimeError("No Exceptionator installed; call set_process_exceptionator first")
46
+ return _process_exceptionator
47
+
48
+
49
+ def should_record_http_exception(exc: BaseException) -> bool:
50
+ """
51
+ Client errors and validation failures are not incidents. HTTP 500s are.
52
+ """
53
+ if isinstance(exc, RequestValidationError):
54
+ return False
55
+ if isinstance(exc, WebSocketDisconnect):
56
+ return False
57
+ status = getattr(exc, "status_code", None)
58
+ if isinstance(exc, HTTPException) and isinstance(status, int) and status < 500:
59
+ return False
60
+ return True
61
+
62
+
63
+ class ExceptionatorMiddleware:
64
+ """
65
+ ASGI middleware that records unhandled HTTP failures and rethrows them.
66
+
67
+ Not ``BaseHTTPMiddleware``: that wrapper breaks streaming and exception groups.
68
+ """
69
+
70
+ def __init__(self, app: ASGIApp, exceptionator: Exceptionator | None = None) -> None:
71
+ self.app = app
72
+ self._exceptionator = exceptionator
73
+
74
+ async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None:
75
+ if scope.get("type") != "http":
76
+ await self.app(scope, receive, send)
77
+ return
78
+ try:
79
+ await self.app(scope, receive, send)
80
+ except Exception as exc:
81
+ if should_record_http_exception(exc):
82
+ self._resolve().capture(
83
+ exc,
84
+ context=ExceptionContext(
85
+ source=ExceptionSource.HTTP,
86
+ http_method=scope.get("method"),
87
+ http_path=scope.get("path"),
88
+ ),
89
+ )
90
+ raise
91
+
92
+ def _resolve(self) -> Exceptionator:
93
+ if self._exceptionator is not None:
94
+ return self._exceptionator
95
+ return get_process_exceptionator()
96
+
97
+
98
+ def record_http_exception(request: Request, exc: HTTPException) -> JSONResponse:
99
+ """
100
+ Store HTTP 500s, then return the same JSON body FastAPI would have sent.
101
+
102
+ Starlette answers ``HTTPException`` inside the router, so the ASGI middleware
103
+ never sees it. 4xx responses are returned unchanged and are not incidents.
104
+ """
105
+ if should_record_http_exception(exc):
106
+ get_process_exceptionator().capture(
107
+ exc,
108
+ context=ExceptionContext(
109
+ source=ExceptionSource.HTTP,
110
+ http_method=request.method,
111
+ http_path=request.url.path,
112
+ ),
113
+ )
114
+ headers = getattr(exc, "headers", None)
115
+ return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail}, headers=headers)
@@ -0,0 +1,7 @@
1
+ """
2
+ Limits shared by every Exceptionator install.
3
+ """
4
+
5
+ MESSAGE_MAX_CHARS = 2_000
6
+ TRACEBACK_MAX_CHARS = 32_000
7
+ FINGERPRINT_FRAMES = 8
@@ -0,0 +1,62 @@
1
+ """
2
+ Catch an exception, run one action, and let the caller rethrow.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Iterator
8
+ from contextlib import contextmanager
9
+
10
+ from corekit.exceptionator.actions import ExceptionatorAction
11
+ from corekit.exceptionator.guard import (
12
+ begin_handling,
13
+ end_handling,
14
+ handling_active,
15
+ is_captured,
16
+ mark_captured,
17
+ )
18
+ from corekit.exceptionator.models import CapturedException, ExceptionContext, build_captured
19
+ from corekit.observability.loggable import Loggable
20
+
21
+ __all__ = ["Exceptionator"]
22
+
23
+
24
+ class Exceptionator(Loggable):
25
+ """
26
+ Catch an exception, run the configured action, and let the caller rethrow.
27
+
28
+ ``guard`` rethrows. ``capture`` runs the same action and returns, for a
29
+ caller that has already decided to swallow the error.
30
+ """
31
+
32
+ def __init__(self, action: ExceptionatorAction, *, service: str) -> None:
33
+ super().__init__()
34
+ self._action = action
35
+ self.service = service
36
+
37
+ @contextmanager
38
+ def guard(self, context: ExceptionContext | None = None) -> Iterator[None]:
39
+ """
40
+ Run the action when the block raises, then rethrow the original exception.
41
+ """
42
+ try:
43
+ yield
44
+ except Exception as exc:
45
+ self.capture(exc, context=context)
46
+ raise
47
+
48
+ def capture(self, exc: BaseException, *, context: ExceptionContext | None = None) -> None:
49
+ """
50
+ Run the action once for this exception. Later calls on the same object no-op.
51
+ """
52
+ if handling_active() or is_captured(exc):
53
+ return
54
+ token = begin_handling()
55
+ try:
56
+ captured: CapturedException = build_captured(exc, service=self.service, context=context)
57
+ mark_captured(exc)
58
+ self._action.run(captured)
59
+ except Exception:
60
+ self.exception("Exceptionator failed while recording an exception")
61
+ finally:
62
+ end_handling(token)
@@ -0,0 +1,86 @@
1
+ """
2
+ Identity for an exception based on its type and innermost frames.
3
+
4
+ The message is left out so ids embedded in the text do not split one bug into
5
+ many fingerprints.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import traceback
12
+ from types import TracebackType
13
+ from typing import ClassVar
14
+
15
+ from corekit.exceptionator.constants import FINGERPRINT_FRAMES
16
+ from corekit.utils.text import truncate
17
+
18
+ __all__ = ["ExceptionFingerprint", "ExceptionText"]
19
+
20
+
21
+ class ExceptionText:
22
+ """
23
+ Backend text extracted from an exception.
24
+ """
25
+
26
+ @staticmethod
27
+ def message(exc: BaseException) -> str:
28
+ """
29
+ Backend message. Public exceptions stringify to user copy, so prefer ``for_log``.
30
+ """
31
+ for_log = getattr(exc, "for_log", None)
32
+ if callable(for_log):
33
+ try:
34
+ return str(for_log())
35
+ except Exception:
36
+ return str(exc)
37
+ return str(exc)
38
+
39
+ @staticmethod
40
+ def first_line(text: str, limit: int) -> str:
41
+ """
42
+ The first line of ``text``, truncated to ``limit`` characters.
43
+ """
44
+ line = text.splitlines()[0] if text else ""
45
+ return truncate(line, limit)
46
+
47
+
48
+ class ExceptionFingerprint:
49
+ """
50
+ Stable identity for an exception based on its type and innermost frames.
51
+ """
52
+
53
+ path_markers: ClassVar[tuple[str, ...]] = ()
54
+
55
+ def of(self, exc: BaseException) -> str:
56
+ """
57
+ Hash the exception type plus the innermost stack frames.
58
+ """
59
+ frames = traceback.extract_tb(exc.__traceback__)[-FINGERPRINT_FRAMES:]
60
+ parts = [type(exc).__qualname__]
61
+ for frame in frames:
62
+ parts.append(f"{self.normalize_path(frame.filename)}|{frame.name}|{frame.lineno}")
63
+ return hashlib.sha256("\n".join(parts).encode()).hexdigest()
64
+
65
+ @classmethod
66
+ def normalize_path(cls, filename: str) -> str:
67
+ """
68
+ Drop machine-specific prefixes so a container path and a checkout match.
69
+ """
70
+ normalized = filename.replace("\\", "/")
71
+ for marker in cls.path_markers:
72
+ index = normalized.find(marker)
73
+ if index >= 0:
74
+ return normalized[index:]
75
+ parts = [part for part in normalized.split("/") if part]
76
+ if not parts:
77
+ return normalized
78
+ return "/".join(parts[-2:])
79
+
80
+ @staticmethod
81
+ def format_traceback(exc: BaseException) -> str:
82
+ """
83
+ Render the traceback text for storage.
84
+ """
85
+ tb: TracebackType | None = exc.__traceback__
86
+ return "".join(traceback.format_exception(type(exc), exc, tb))
@@ -0,0 +1,53 @@
1
+ """
2
+ ContextVar and per-exception marker so one failure is recorded once.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from contextvars import ContextVar, Token
8
+
9
+ __all__ = [
10
+ "begin_handling",
11
+ "end_handling",
12
+ "handling_active",
13
+ "is_captured",
14
+ "mark_captured",
15
+ ]
16
+
17
+ CAPTURED_MARKER = "_exceptionator_captured"
18
+ _handling: ContextVar[bool] = ContextVar("exceptionator_handling", default=False)
19
+
20
+
21
+ def is_captured(exc: BaseException) -> bool:
22
+ """
23
+ Whether this exception object was already handed to an Exceptionator.
24
+ """
25
+ return bool(getattr(exc, CAPTURED_MARKER, False))
26
+
27
+
28
+ def mark_captured(exc: BaseException) -> None:
29
+ """
30
+ Remember that this exception object has been handled.
31
+ """
32
+ setattr(exc, CAPTURED_MARKER, True)
33
+
34
+
35
+ def handling_active() -> bool:
36
+ """
37
+ Whether this task is already inside the Exceptionator.
38
+ """
39
+ return _handling.get()
40
+
41
+
42
+ def begin_handling() -> Token[bool]:
43
+ """
44
+ Mark this task as inside the Exceptionator. Pair with ``end_handling``.
45
+ """
46
+ return _handling.set(True)
47
+
48
+
49
+ def end_handling(token: Token[bool]) -> None:
50
+ """
51
+ Leave the Exceptionator guard.
52
+ """
53
+ _handling.reset(token)
@@ -0,0 +1,52 @@
1
+ """
2
+ Hook ``run_task`` calls after a task fails and before ``failure()``.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Callable
8
+ from typing import TYPE_CHECKING
9
+
10
+ from corekit.exceptionator.models import ExceptionContext, ExceptionSource
11
+
12
+ if TYPE_CHECKING:
13
+ from corekit.exceptionator.exceptionator import Exceptionator
14
+
15
+ __all__ = ["clear_run_task_hook", "get_run_task_hook", "install_run_task_hook"]
16
+
17
+ RunTaskHook = Callable[[str, BaseException], None]
18
+
19
+ _hook: RunTaskHook | None = None
20
+
21
+
22
+ def install_run_task_hook(exceptionator: Exceptionator) -> None:
23
+ """
24
+ Register ``exceptionator`` so ``run_task`` captures failures with the task name.
25
+
26
+ Passing the same instance again is a no-op. Call ``clear_run_task_hook`` to
27
+ remove it. With no hook registered, ``run_task`` behaves as it did before.
28
+ """
29
+ global _hook
30
+
31
+ def hook(task_name: str, exc: BaseException) -> None:
32
+ exceptionator.capture(
33
+ exc,
34
+ context=ExceptionContext(source=ExceptionSource.RQ, job_name=task_name),
35
+ )
36
+
37
+ _hook = hook
38
+
39
+
40
+ def clear_run_task_hook() -> None:
41
+ """
42
+ Remove any ``run_task`` capture hook.
43
+ """
44
+ global _hook
45
+ _hook = None
46
+
47
+
48
+ def get_run_task_hook() -> RunTaskHook | None:
49
+ """
50
+ The hook ``run_task`` should call, or ``None``.
51
+ """
52
+ return _hook
@@ -0,0 +1,98 @@
1
+ """
2
+ Values every Exceptionator action receives.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass, field
8
+ from typing import Any
9
+
10
+ from pydantic import BaseModel, Field
11
+
12
+ from corekit.exceptionator.constants import MESSAGE_MAX_CHARS, TRACEBACK_MAX_CHARS
13
+ from corekit.exceptionator.fingerprint import ExceptionFingerprint, ExceptionText
14
+ from corekit.schemas import StringEnum
15
+ from corekit.utils.text import truncate
16
+
17
+ __all__ = [
18
+ "CapturedException",
19
+ "ExceptionContext",
20
+ "ExceptionSource",
21
+ "ExceptionatorActionName",
22
+ "build_captured",
23
+ ]
24
+
25
+ _fingerprint = ExceptionFingerprint()
26
+
27
+
28
+ class ExceptionatorActionName(StringEnum):
29
+ """
30
+ Built-in action names. Apps may define additional string names for custom actions.
31
+ """
32
+
33
+ NOOP = "noop"
34
+ LOG = "log"
35
+ PERSIST_AND_NOTIFY = "persist_and_notify"
36
+
37
+
38
+ class ExceptionSource(StringEnum):
39
+ """
40
+ Which process boundary captured the exception.
41
+ """
42
+
43
+ HTTP = "http"
44
+ RQ = "rq"
45
+ DISCORD = "discord"
46
+ TASK = "task"
47
+
48
+
49
+ class ExceptionContext(BaseModel):
50
+ """
51
+ Where an exception was caught, plus whatever the boundary already knows.
52
+ """
53
+
54
+ source: ExceptionSource = ExceptionSource.TASK
55
+ http_method: str | None = None
56
+ http_path: str | None = None
57
+ job_name: str | None = None
58
+ extra: dict[str, Any] = Field(default_factory=dict)
59
+
60
+
61
+ @dataclass
62
+ class CapturedException:
63
+ """
64
+ One incident, ready for an action. Not a database row.
65
+ """
66
+
67
+ service: str
68
+ exception_type: str
69
+ message: str
70
+ traceback_text: str
71
+ fingerprint: str
72
+ context: ExceptionContext
73
+ exc: BaseException = field(repr=False)
74
+
75
+
76
+ def build_captured(
77
+ exc: BaseException,
78
+ *,
79
+ service: str,
80
+ context: ExceptionContext | None = None,
81
+ ) -> CapturedException:
82
+ """
83
+ Truncate an exception into the object actions receive.
84
+
85
+ Product code that stores the text should redact secrets before writing.
86
+ """
87
+ resolved = context or ExceptionContext()
88
+ message = ExceptionText.message(exc)
89
+ traceback_text = ExceptionFingerprint.format_traceback(exc)
90
+ return CapturedException(
91
+ service=service,
92
+ exception_type=type(exc).__qualname__,
93
+ message=truncate(message, MESSAGE_MAX_CHARS),
94
+ traceback_text=truncate(traceback_text, TRACEBACK_MAX_CHARS, suffix="\n… truncated"),
95
+ fingerprint=_fingerprint.of(exc),
96
+ context=resolved,
97
+ exc=exc,
98
+ )
corekit/jobs/runner.py CHANGED
@@ -18,6 +18,7 @@ import inspect
18
18
  import logging
19
19
  from typing import Any
20
20
 
21
+ from corekit.exceptionator.jobs import get_run_task_hook
21
22
  from corekit.jobs.registry import task_registry
22
23
  from corekit.utils.payload import decode_payload
23
24
 
@@ -34,8 +35,10 @@ def run_task(task_name: str, payload: str | bytes | None = None) -> Any:
34
35
  raises, and the original exception is re-raised so the queue records the
35
36
  job as failed. A hook that raises does not mask the original error.
36
37
  ``last_result`` and ``last_error`` are set on the task before the hook
37
- runs. A coroutine ``task_function`` is awaited. ``timeout`` is not applied
38
- here; the scheduling adapter owns that.
38
+ runs. When an Exceptionator ``run_task`` hook is installed it runs after
39
+ ``last_error`` is set and before ``failure()``. A coroutine
40
+ ``task_function`` is awaited. ``timeout`` is not applied here; the
41
+ scheduling adapter owns that.
39
42
 
40
43
  Args:
41
44
  task_name: The registered name of the task to run.
@@ -58,6 +61,7 @@ def run_task(task_name: str, payload: str | bytes | None = None) -> Any:
58
61
  except Exception as exc:
59
62
  task.last_result = None
60
63
  task.last_error = exc
64
+ _run_exceptionator_hook(task_name, exc)
61
65
  _run_hook(task, "failure", args, kwargs)
62
66
  raise
63
67
 
@@ -67,6 +71,22 @@ def run_task(task_name: str, payload: str | bytes | None = None) -> Any:
67
71
  return result
68
72
 
69
73
 
74
+ def _run_exceptionator_hook(task_name: str, exc: BaseException) -> None:
75
+ """
76
+ Run the optional Exceptionator hook without replacing the original error.
77
+ """
78
+ hook = get_run_task_hook()
79
+ if hook is None:
80
+ return
81
+ try:
82
+ hook(task_name, exc)
83
+ except Exception:
84
+ logger.exception(
85
+ "Exceptionator run_task hook raised for %s; the task's own outcome stands",
86
+ task_name,
87
+ )
88
+
89
+
70
90
  def _run_hook(task: Any, hook_name: str, args: list[Any], kwargs: dict[str, Any]) -> None:
71
91
  """
72
92
  Run a success or failure hook without letting it replace the real outcome.
corekit/utils/__init__.py CHANGED
@@ -19,7 +19,7 @@ from corekit.utils.ids import (
19
19
  )
20
20
  from corekit.utils.payload import Payload, decode_payload, encode_payload
21
21
  from corekit.utils.raise_exc import raise_exc
22
- from corekit.utils.text import join_lines, list_to_english, sanitize_filename
22
+ from corekit.utils.text import join_lines, list_to_english, sanitize_filename, truncate
23
23
  from corekit.utils.time import isoformat_now, parse_docker_timestamp, time_now, timedelta_now, timestamp_now
24
24
  from corekit.utils.validators import false_validator, true_validator
25
25
  from corekit.utils.void import void
@@ -56,5 +56,6 @@ __all__ = [
56
56
  "timedelta_now",
57
57
  "timestamp_now",
58
58
  "true_validator",
59
+ "truncate",
59
60
  "void",
60
61
  ]
corekit/utils/text.py CHANGED
@@ -2,13 +2,14 @@
2
2
  String assembly helpers.
3
3
 
4
4
  Small formatters for turning collections into text a human will read -- log
5
- lines, notification bodies, error messages -- plus filename sanitization.
5
+ lines, notification bodies, error messages -- plus filename sanitization and
6
+ length limits.
6
7
  """
7
8
 
8
9
  import re
9
10
  from typing import Any, Literal
10
11
 
11
- __all__ = ["join_lines", "list_to_english", "sanitize_filename"]
12
+ __all__ = ["join_lines", "list_to_english", "sanitize_filename", "truncate"]
12
13
 
13
14
  FALLBACK_FILENAME = "unnamed"
14
15
  _UNSAFE_CHARS = re.compile(r"[^a-z0-9\-]")
@@ -43,6 +44,24 @@ def list_to_english(items: list[str], ending: Literal["and", "or"] | None = None
43
44
  return f"{buffer}, {ending} {last}"
44
45
 
45
46
 
47
+ def truncate(text: str, limit: int, *, suffix: str = "") -> str:
48
+ """
49
+ Cut ``text`` to at most ``limit`` characters, appending ``suffix`` when cut.
50
+
51
+ ``suffix`` counts toward ``limit``, so the returned string is never longer
52
+ than ``limit`` (unless ``suffix`` itself is longer than ``limit``, in which
53
+ case ``suffix`` is returned truncated to ``limit``).
54
+ """
55
+ if limit <= 0:
56
+ return ""
57
+ if len(text) <= limit:
58
+ return text
59
+ if len(suffix) >= limit:
60
+ return suffix[:limit]
61
+ keep = limit - len(suffix)
62
+ return text[:keep] + suffix
63
+
64
+
46
65
  def sanitize_filename(raw: str, fallback: str = FALLBACK_FILENAME) -> str:
47
66
  """
48
67
  Reduce a string to lowercase kebab-case safe for use as a filename stem.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-corekit
3
- Version: 0.4.0
3
+ Version: 0.4.1
4
4
  Summary: Shared foundations for Python projects: logging, benchmarking, registries, FastAPI application and routers, SQL statements and migrations, background tasks, ETL, and LLM chat/tool primitives
5
5
  Author: Steven Jacobsen
6
6
  License-Expression: MIT
@@ -90,6 +90,29 @@ class Report(Benchmarkable):
90
90
  self.timing("queried") # logs the time since the previous split
91
91
  ```
92
92
 
93
+ ## Exceptionator
94
+
95
+ Catch an exception, run one action, then rethrow so the existing failure path
96
+ still happens. Built-in actions are no-op and log-traceback; apps supply their
97
+ own (persist, notify, …).
98
+
99
+ ```python
100
+ from corekit.exceptionator import (
101
+ Exceptionator,
102
+ ExceptionatorMiddleware,
103
+ LogTracebackAction,
104
+ install_run_task_hook,
105
+ set_process_exceptionator,
106
+ )
107
+
108
+ exceptionator = Exceptionator(LogTracebackAction(), service="api")
109
+ set_process_exceptionator(exceptionator)
110
+ install_run_task_hook(exceptionator) # optional; run_task captures with task name
111
+ ```
112
+
113
+ `ExceptionatorMiddleware` is raw ASGI (not `BaseHTTPMiddleware`). With no
114
+ `run_task` hook installed, jobs behave as in 0.4.0.
115
+
93
116
  ## Assembling an application
94
117
 
95
118
  `Application` is a plain `FastAPI` subclass — every constructor argument,
@@ -74,6 +74,15 @@ corekit/events/publisher.py,sha256=70lHyEIEg0eXUWJ9k9eUNVBBmckm4rYBgvTZgRfbcl8,2
74
74
  corekit/events/reader.py,sha256=HoJs6zb9N3VDD-nJV2fpks7ny2OI8UaAKQMBaXcK7_k,4994
75
75
  corekit/events/sse.py,sha256=lhF4KUQ_XrdExGLWbKYJghti2t6ExNzXYoA6dOZi9mA,4090
76
76
  corekit/events/websocket.py,sha256=S6CUh9duI5xHVrKqbHpss8FrnKKqnFHBFJpSkmgInN4,3858
77
+ corekit/exceptionator/__init__.py,sha256=-JjKXBPgevTZsd0MeJdyknae3SfJ2Etsqk6WIzrpSS8,1764
78
+ corekit/exceptionator/actions.py,sha256=ji2qEabM-xQRv6Wiu5mkyCQJvDKJmSbfOwcnEvmx5fo,1172
79
+ corekit/exceptionator/asgi.py,sha256=P7LPf_rsHas-2Rywe6lYhzG-C-yzI-cuCub2mn7hguQ,3780
80
+ corekit/exceptionator/constants.py,sha256=pCNrGF_pH-__qMjWzTB1PK2lhTCIzCTRsgI0xkHYBCE,133
81
+ corekit/exceptionator/exceptionator.py,sha256=z5dbvvpEgxRAYrsXQR8tDuo3wNjKsygonQy_4C3FWvs,1974
82
+ corekit/exceptionator/fingerprint.py,sha256=Fjf02FFOq3pm4o88F0I7QDy7Nq9EwgA01jjpb8oWuMM,2609
83
+ corekit/exceptionator/guard.py,sha256=SU95rYpadfqgAUogmXSQyHvHCP7xATADlQyOTwLO_Qk,1180
84
+ corekit/exceptionator/jobs.py,sha256=ufQZNc5bbEsl3IYyCuTtaShXh0-lSbCReTouZHqpv9k,1340
85
+ corekit/exceptionator/models.py,sha256=CQxKKzBBerkEqdUnuPVyXflzx2r9cjFzUpG8K8VizhE,2437
77
86
  corekit/exceptions/__init__.py,sha256=8q9EX-0bzOiJI1FOzCbViQFwx53Ugs8NH482Cvpci6k,995
78
87
  corekit/exceptions/base.py,sha256=k0AfTfPrLWR6x-l2qvvjqD_sup0fiWhqu1OoNaNM-Lk,5596
79
88
  corekit/exceptions/enum.py,sha256=D-YL-cZXs-F2jS1GgRBhPWmuqBfX33B1QP61vAXdAes,324
@@ -95,7 +104,7 @@ corekit/http/status.py,sha256=rZ-cdliG9EAvWMTzvxjqjipRkZRc6RgSzcBY4Kewdg0,2377
95
104
  corekit/http/stream.py,sha256=lkERyCXz5amOWzoE-b12iftf3l_G-ghwSvN1lL5lUio,3257
96
105
  corekit/jobs/__init__.py,sha256=vsv8o23ApT6MlOwOq-AFYeQW2NT1kjyvu89A5CL2PsY,880
97
106
  corekit/jobs/registry.py,sha256=cco6884eVuIYHEtSv6P62MICFjX-QhuSZIFkEJcQi_M,2557
98
- corekit/jobs/runner.py,sha256=KRzUIaeXVqLFekoIi2C5cnZ8F-5V5Oy_91xOPHjhjmY,2650
107
+ corekit/jobs/runner.py,sha256=VyiTrQJT-E8-XuNBh8s1QgLJkKhkpBq_398Fs_03Kow,3321
99
108
  corekit/jobs/task.py,sha256=tqr-QaQSHyfPjbyZscM5i-YgT-fl58cpd2FVxevtG_E,6112
100
109
  corekit/llm/__init__.py,sha256=Qa-5V2cG4aH98b0nLY2tMx0G7uhoWhcaaZ7JY1dJjcA,3217
101
110
  corekit/llm/client.py,sha256=bO2o21ntKdGNjcWOoEv4ew2QQD7-HQ6Hsn01Zf_5a1I,6441
@@ -148,18 +157,18 @@ corekit/serialization/enum.py,sha256=pzHuAIXeonEF7-jyN1uYddJk-xvmQGuymDf1U6RWR5w
148
157
  corekit/serialization/pickle_file.py,sha256=dudKIxR8ueT3wx_IBxHJeoqnFeP1rT7dlTb_PXlSkd8,2251
149
158
  corekit/serialization/serializable.py,sha256=viF3ZCKRJ90hk6m4lbqIfo6ifsY2c4sXr4xZrn1Yz-Q,1999
150
159
  corekit/serialization/serializer.py,sha256=XlGE1Rq8M55Jl2a4F5MkvDcba2VI7lrh0v9kwL0DWG8,6617
151
- corekit/utils/__init__.py,sha256=2_YU0DK_guZntR5yooQ1rblLj5BMJSSA-6HMoFCjapk,1801
160
+ corekit/utils/__init__.py,sha256=xOHqpsAipQbkCLurKOYBSQ8RJyHULfoeEKPXqudNWH4,1827
152
161
  corekit/utils/coercion.py,sha256=Aq63jrxQYg1ooWUFXHff2uepB_LoHm1izao8_3xkzEU,3650
153
162
  corekit/utils/collections.py,sha256=cn7Bzh67utzBi7UO4FfjWrjDun05ye5_rTscwfWcmwo,4475
154
163
  corekit/utils/ids.py,sha256=BVniaYqewM-EosDxcJAT_S_7T9C1c5X8nsaVGs5up34,1731
155
164
  corekit/utils/payload.py,sha256=T7EgdVU0S5h8MAzvQsmkfRPMatWqUbxjHL9hmZdM9ho,3882
156
165
  corekit/utils/raise_exc.py,sha256=cz7ljc6ZW90AGQussKuANN8PLsDLUhl-E8FZ0Ipsw-0,175
157
- corekit/utils/text.py,sha256=54maLM4jsS8cjVXRQCNVFzVszGimuzgaNzudhZzZeio,1694
166
+ corekit/utils/text.py,sha256=0322DdZGuDGEagTyejuda6QT1jbbxNIO6loC-_AGml0,2311
158
167
  corekit/utils/time.py,sha256=-iPaETXcgDu7J39Kwe938JyZKhPVjl6a572BBqsqcDQ,2215
159
168
  corekit/utils/validators.py,sha256=_HVKo3y264KGNaZ-1RyM1x46VPvu7XKcQkrHWDC9uxs,340
160
169
  corekit/utils/void.py,sha256=eXDb2QynuguiSgHGJLdgE08MuRnxBdYebRdMD7s1m9o,178
161
- python_corekit-0.4.0.dist-info/licenses/LICENSE,sha256=357LYxbxAQZ95q5cV-8JK6j-KNgiE6AteRodjEsm-kE,1072
162
- python_corekit-0.4.0.dist-info/METADATA,sha256=N1r_kyXsO1GSGd92YDkDs3HzV6bYkhal5Rnmnl-8QCY,14378
163
- python_corekit-0.4.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
164
- python_corekit-0.4.0.dist-info/top_level.txt,sha256=SDK4o8BoaI47E9tPbiNCbbWoc2y6N_wCjwnIEfr-GWI,8
165
- python_corekit-0.4.0.dist-info/RECORD,,
170
+ python_corekit-0.4.1.dist-info/licenses/LICENSE,sha256=357LYxbxAQZ95q5cV-8JK6j-KNgiE6AteRodjEsm-kE,1072
171
+ python_corekit-0.4.1.dist-info/METADATA,sha256=M24uRb1as-03LHKgbGhDIFJeQ30Z3mEO84EfCj_GNIE,15084
172
+ python_corekit-0.4.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
173
+ python_corekit-0.4.1.dist-info/top_level.txt,sha256=SDK4o8BoaI47E9tPbiNCbbWoc2y6N_wCjwnIEfr-GWI,8
174
+ python_corekit-0.4.1.dist-info/RECORD,,