bugstack 1.0.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.
bugstack/__init__.py ADDED
@@ -0,0 +1,142 @@
1
+ """BugStack SDK — Production error capture for BugStack.
2
+
3
+ Usage:
4
+ import bugstack
5
+
6
+ bugstack.init(api_key="bs_live_...")
7
+
8
+ # Errors are captured automatically via framework integrations.
9
+ # For manual capture:
10
+ try:
11
+ risky_operation()
12
+ except Exception as e:
13
+ bugstack.capture_exception(e)
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import atexit
19
+ from typing import Any, Optional
20
+
21
+ from .client import BugStackClient
22
+ from .types import BugStackConfig, ErrorEvent, RequestContext, SDK_VERSION
23
+
24
+ __version__ = SDK_VERSION
25
+ __all__ = [
26
+ "init",
27
+ "capture_exception",
28
+ "get_client",
29
+ "BugStackConfig",
30
+ "ErrorEvent",
31
+ "RequestContext",
32
+ ]
33
+
34
+ _client: Optional[BugStackClient] = None
35
+
36
+
37
+ def init(
38
+ api_key: str,
39
+ *,
40
+ endpoint: str = "https://api.bugstack.dev/api/capture",
41
+ project_id: str = "",
42
+ environment: str = "production",
43
+ auto_fix: bool = False,
44
+ enabled: bool = True,
45
+ debug: bool = False,
46
+ dry_run: bool = False,
47
+ deduplication_window: float = 300.0,
48
+ timeout: float = 5.0,
49
+ max_retries: int = 3,
50
+ ignored_errors: Optional[list] = None,
51
+ before_send: Optional[Any] = None,
52
+ redact_fields: Optional[list[str]] = None,
53
+ ) -> BugStackClient:
54
+ """Initialize the BugStack SDK.
55
+
56
+ Call this once at application startup.
57
+
58
+ Args:
59
+ api_key: Your BugStack API key (required).
60
+ endpoint: BugStack API endpoint.
61
+ project_id: Project identifier.
62
+ environment: Environment name (e.g., "production").
63
+ auto_fix: Enable autonomous error fixing.
64
+ enabled: Kill switch — set to False to disable everything.
65
+ debug: Log SDK activity to console.
66
+ dry_run: Log errors but don't send them.
67
+ deduplication_window: Dedup window in seconds (default: 300).
68
+ timeout: HTTP timeout in seconds (default: 5).
69
+ max_retries: Max retry attempts (default: 3).
70
+ ignored_errors: Error types or messages to ignore.
71
+ before_send: Hook to inspect/modify/drop events.
72
+ redact_fields: Additional field names to redact.
73
+
74
+ Returns:
75
+ The initialized BugStackClient.
76
+ """
77
+ global _client
78
+
79
+ if _client is not None:
80
+ _client.shutdown()
81
+
82
+ config = BugStackConfig(
83
+ api_key=api_key,
84
+ endpoint=endpoint,
85
+ project_id=project_id,
86
+ environment=environment,
87
+ auto_fix=auto_fix,
88
+ enabled=enabled,
89
+ debug=debug,
90
+ dry_run=dry_run,
91
+ deduplication_window=deduplication_window,
92
+ timeout=timeout,
93
+ max_retries=max_retries,
94
+ ignored_errors=ignored_errors or [],
95
+ before_send=before_send,
96
+ redact_fields=redact_fields or [],
97
+ )
98
+
99
+ _client = BugStackClient(config)
100
+
101
+ atexit.register(_shutdown)
102
+
103
+ return _client
104
+
105
+
106
+ def capture_exception(
107
+ exc: Optional[BaseException] = None,
108
+ *,
109
+ request: Optional[RequestContext] = None,
110
+ metadata: Optional[dict[str, Any]] = None,
111
+ ) -> bool:
112
+ """Capture an exception and send it to BugStack.
113
+
114
+ If no exception is passed, captures the current exception from sys.exc_info().
115
+
116
+ Returns True if the error was accepted.
117
+ """
118
+ if _client is None:
119
+ import warnings
120
+ warnings.warn("BugStack not initialized. Call bugstack.init() first.", stacklevel=2)
121
+ return False
122
+
123
+ if exc is None:
124
+ import sys
125
+ _, exc_val, _ = sys.exc_info()
126
+ if exc_val is None:
127
+ return False
128
+ exc = exc_val
129
+
130
+ return _client.capture_exception(exc, request=request, metadata=metadata)
131
+
132
+
133
+ def get_client() -> Optional[BugStackClient]:
134
+ """Get the current BugStack client instance."""
135
+ return _client
136
+
137
+
138
+ def _shutdown() -> None:
139
+ global _client
140
+ if _client is not None:
141
+ _client.shutdown()
142
+ _client = None
bugstack/client.py ADDED
@@ -0,0 +1,151 @@
1
+ """Core BugStack client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import sys
7
+ import re
8
+ from datetime import datetime, timezone
9
+ from typing import Any, Optional, Union
10
+
11
+ from .fingerprint import (
12
+ Deduplicator,
13
+ extract_error_location,
14
+ format_traceback,
15
+ generate_fingerprint,
16
+ )
17
+ from .transport import Transport
18
+ from .types import BugStackConfig, ErrorEvent, EnvironmentInfo, RequestContext
19
+
20
+ logger = logging.getLogger("bugstack")
21
+
22
+
23
+ class BugStackClient:
24
+ """Core client for capturing and reporting errors to BugStack.
25
+
26
+ Thread-safe. Handles deduplication, filtering, and transport.
27
+ """
28
+
29
+ def __init__(self, config: BugStackConfig) -> None:
30
+ self._config = config
31
+ self._deduplicator = Deduplicator(window=config.deduplication_window)
32
+ self._transport: Optional[Transport] = None
33
+
34
+ if config.enabled and not config.dry_run:
35
+ self._transport = Transport(
36
+ endpoint=config.endpoint,
37
+ api_key=config.api_key,
38
+ timeout=config.timeout,
39
+ max_retries=config.max_retries,
40
+ debug=config.debug,
41
+ )
42
+
43
+ if config.debug:
44
+ logging.basicConfig(level=logging.DEBUG)
45
+ logger.debug(
46
+ "[BugStack] Client initialized (endpoint=%s, dry_run=%s)",
47
+ config.endpoint,
48
+ config.dry_run,
49
+ )
50
+
51
+ @property
52
+ def config(self) -> BugStackConfig:
53
+ return self._config
54
+
55
+ def capture_exception(
56
+ self,
57
+ exc: BaseException,
58
+ request: Optional[RequestContext] = None,
59
+ metadata: Optional[dict[str, Any]] = None,
60
+ ) -> bool:
61
+ """Capture an exception and send it to BugStack.
62
+
63
+ Returns True if the error was accepted (not filtered/deduplicated).
64
+ Never raises — all errors are caught and logged in debug mode.
65
+ """
66
+ try:
67
+ return self._do_capture(exc, request, metadata)
68
+ except Exception as inner:
69
+ if self._config.debug:
70
+ logger.error("[BugStack] Error during capture: %s", inner)
71
+ return False
72
+
73
+ def _do_capture(
74
+ self,
75
+ exc: BaseException,
76
+ request: Optional[RequestContext],
77
+ metadata: Optional[dict[str, Any]],
78
+ ) -> bool:
79
+ if not self._config.enabled:
80
+ return False
81
+
82
+ # Check ignored_errors
83
+ if self._is_ignored(exc):
84
+ if self._config.debug:
85
+ logger.debug("[BugStack] Error ignored: %s", type(exc).__name__)
86
+ return False
87
+
88
+ # Extract location info
89
+ exc_type, file, function, line = extract_error_location(exc)
90
+ stack_trace = format_traceback(exc)
91
+
92
+ # Build event
93
+ event = ErrorEvent(
94
+ message=str(exc),
95
+ stack_trace=stack_trace,
96
+ file=file,
97
+ function=function,
98
+ exception_type=exc_type,
99
+ fingerprint=generate_fingerprint(exc_type, file, function, line),
100
+ request=request,
101
+ environment=EnvironmentInfo(),
102
+ timestamp=datetime.now(timezone.utc).isoformat(),
103
+ metadata=metadata or {},
104
+ )
105
+
106
+ # before_send hook
107
+ if self._config.before_send:
108
+ result = self._config.before_send(event)
109
+ if result is None:
110
+ if self._config.debug:
111
+ logger.debug("[BugStack] Event dropped by before_send")
112
+ return False
113
+ event = result
114
+
115
+ # Deduplication
116
+ if not self._deduplicator.should_send(event.fingerprint):
117
+ if self._config.debug:
118
+ logger.debug("[BugStack] Event deduplicated: %s", event.fingerprint)
119
+ return False
120
+
121
+ # Build payload
122
+ payload = event.to_payload(self._config)
123
+
124
+ # Dry run mode
125
+ if self._config.dry_run:
126
+ import json
127
+ print(f"[BugStack DryRun] Would send: {json.dumps(payload, indent=2)}")
128
+ return True
129
+
130
+ # Enqueue for sending
131
+ if self._transport:
132
+ self._transport.enqueue(payload)
133
+
134
+ if self._config.debug:
135
+ logger.debug("[BugStack] Event queued: %s", event.fingerprint)
136
+
137
+ return True
138
+
139
+ def _is_ignored(self, exc: BaseException) -> bool:
140
+ """Check if an exception matches any ignored_errors patterns."""
141
+ for pattern in self._config.ignored_errors:
142
+ if isinstance(pattern, type) and isinstance(exc, pattern):
143
+ return True
144
+ if isinstance(pattern, str) and pattern == str(exc):
145
+ return True
146
+ return False
147
+
148
+ def shutdown(self) -> None:
149
+ """Shut down the client and flush pending events."""
150
+ if self._transport:
151
+ self._transport.shutdown()
@@ -0,0 +1,96 @@
1
+ """Error fingerprinting and client-side deduplication."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import time
7
+ import traceback
8
+ import threading
9
+ from typing import Optional
10
+
11
+
12
+ def generate_fingerprint(
13
+ exception_type: str,
14
+ file: str,
15
+ function: str,
16
+ line: Optional[int] = None,
17
+ ) -> str:
18
+ """Generate a stable SHA-256 fingerprint for an error.
19
+
20
+ Based on exception type, file, function, and line number.
21
+ The same error at the same location always produces the same hash.
22
+ """
23
+ parts = [exception_type, file, function]
24
+ if line is not None:
25
+ parts.append(str(line))
26
+ key = ":".join(parts)
27
+ return hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]
28
+
29
+
30
+ def extract_error_location(
31
+ exc: BaseException,
32
+ ) -> tuple[str, str, str, Optional[int]]:
33
+ """Extract file, function, line from an exception's traceback.
34
+
35
+ Returns (exception_type, file, function, line).
36
+ """
37
+ exception_type = type(exc).__name__
38
+
39
+ tb = exc.__traceback__
40
+ if tb is None:
41
+ return exception_type, "", "", None
42
+
43
+ # Walk to the last (innermost) frame
44
+ while tb.tb_next is not None:
45
+ tb = tb.tb_next
46
+
47
+ frame = tb.tb_frame
48
+ file = frame.f_code.co_filename
49
+ function = frame.f_code.co_name
50
+ line = tb.tb_lineno
51
+
52
+ return exception_type, file, function, line
53
+
54
+
55
+ def format_traceback(exc: BaseException) -> str:
56
+ """Format an exception's traceback as a string."""
57
+ lines = traceback.format_exception(type(exc), exc, exc.__traceback__)
58
+ return "".join(lines)
59
+
60
+
61
+ class Deduplicator:
62
+ """Client-side error deduplicator.
63
+
64
+ Prevents the same error (by fingerprint) from being reported
65
+ more than once within a configurable time window.
66
+ """
67
+
68
+ def __init__(self, window: float = 300.0) -> None:
69
+ self._cache: dict[str, float] = {}
70
+ self._window = window
71
+ self._lock = threading.Lock()
72
+
73
+ def should_send(self, fingerprint: str) -> bool:
74
+ """Check if an error should be sent. Thread-safe."""
75
+ now = time.monotonic()
76
+
77
+ with self._lock:
78
+ last_sent = self._cache.get(fingerprint)
79
+ if last_sent is not None and (now - last_sent) < self._window:
80
+ return False
81
+ self._cache[fingerprint] = now
82
+ self._cleanup(now)
83
+ return True
84
+
85
+ def _cleanup(self, now: float) -> None:
86
+ """Remove expired entries."""
87
+ expired = [
88
+ fp for fp, ts in self._cache.items()
89
+ if (now - ts) >= self._window
90
+ ]
91
+ for fp in expired:
92
+ del self._cache[fp]
93
+
94
+ def clear(self) -> None:
95
+ with self._lock:
96
+ self._cache.clear()
@@ -0,0 +1,5 @@
1
+ """BugStack framework integrations.
2
+
3
+ Integrations are imported lazily — you only need the framework
4
+ you're using installed.
5
+ """
@@ -0,0 +1,93 @@
1
+ """BugStack integration for Django."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import Any, Optional
7
+
8
+ logger = logging.getLogger("bugstack")
9
+
10
+
11
+ class BugStackMiddleware:
12
+ """Django middleware that captures unhandled exceptions.
13
+
14
+ Usage in settings.py:
15
+ MIDDLEWARE = [
16
+ 'bugstack.integrations.django.BugStackMiddleware',
17
+ # ... other middleware
18
+ ]
19
+
20
+ BUGSTACK_API_KEY = "bs_live_..."
21
+ BUGSTACK_AUTO_FIX = True
22
+
23
+ The middleware auto-initializes from Django settings if
24
+ bugstack.init() hasn't been called yet.
25
+ """
26
+
27
+ def __init__(self, get_response: Any) -> None:
28
+ self.get_response = get_response
29
+ self._ensure_initialized()
30
+
31
+ @staticmethod
32
+ def _ensure_initialized() -> None:
33
+ """Initialize BugStack from Django settings if not already done."""
34
+ import bugstack
35
+
36
+ if bugstack.get_client() is not None:
37
+ return
38
+
39
+ try:
40
+ from django.conf import settings
41
+
42
+ api_key = getattr(settings, "BUGSTACK_API_KEY", "")
43
+ if not api_key:
44
+ return
45
+
46
+ bugstack.init(
47
+ api_key=api_key,
48
+ auto_fix=getattr(settings, "BUGSTACK_AUTO_FIX", False),
49
+ environment=getattr(settings, "BUGSTACK_ENVIRONMENT", "production"),
50
+ debug=getattr(settings, "BUGSTACK_DEBUG", False),
51
+ dry_run=getattr(settings, "BUGSTACK_DRY_RUN", False),
52
+ )
53
+ except Exception as exc:
54
+ logger.warning("[BugStack] Failed to auto-initialize from Django settings: %s", exc)
55
+
56
+ def __call__(self, request: Any) -> Any:
57
+ return self.get_response(request)
58
+
59
+ def process_exception(self, request: Any, exception: Exception) -> None:
60
+ """Called by Django when a view raises an exception."""
61
+ try:
62
+ import bugstack
63
+ from ..types import RequestContext
64
+
65
+ client = bugstack.get_client()
66
+ if client is None:
67
+ return
68
+
69
+ request_ctx = self._build_request_context(request)
70
+ client.capture_exception(
71
+ exception,
72
+ request=request_ctx,
73
+ metadata={"framework": "django"},
74
+ )
75
+ except Exception as exc:
76
+ logger.warning("[BugStack] Error capturing exception: %s", exc)
77
+
78
+ @staticmethod
79
+ def _build_request_context(request: Any) -> "RequestContext":
80
+ from ..types import RequestContext
81
+
82
+ route = ""
83
+ try:
84
+ if hasattr(request, "resolver_match") and request.resolver_match:
85
+ route = request.resolver_match.route
86
+ else:
87
+ route = request.path
88
+ except Exception:
89
+ route = getattr(request, "path", "")
90
+
91
+ method = getattr(request, "method", "")
92
+
93
+ return RequestContext(route=route, method=method)
@@ -0,0 +1,94 @@
1
+ """BugStack integration for FastAPI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import Any
7
+
8
+ from ..types import RequestContext
9
+
10
+ logger = logging.getLogger("bugstack")
11
+
12
+
13
+ class FastAPIMiddleware:
14
+ """ASGI middleware that captures unhandled exceptions in FastAPI.
15
+
16
+ Usage:
17
+ from fastapi import FastAPI
18
+ from bugstack.integrations.fastapi import FastAPIMiddleware
19
+
20
+ app = FastAPI()
21
+ app.add_middleware(FastAPIMiddleware)
22
+
23
+ The middleware captures the error, builds request context,
24
+ and re-raises so FastAPI's own error handling still works.
25
+ """
26
+
27
+ def __init__(self, app: Any) -> None:
28
+ self.app = app
29
+ self._framework_version = self._get_version()
30
+
31
+ @staticmethod
32
+ def _get_version() -> str:
33
+ try:
34
+ import fastapi
35
+ return fastapi.__version__
36
+ except Exception:
37
+ return ""
38
+
39
+ async def __call__(self, scope: dict, receive: Any, send: Any) -> None:
40
+ if scope["type"] != "http":
41
+ await self.app(scope, receive, send)
42
+ return
43
+
44
+ try:
45
+ await self.app(scope, receive, send)
46
+ except Exception as exc:
47
+ import bugstack
48
+
49
+ client = bugstack.get_client()
50
+ if client:
51
+ request_ctx = self._build_request_context(scope)
52
+
53
+ # Set framework info
54
+ from ..types import EnvironmentInfo
55
+ env = EnvironmentInfo(
56
+ framework="fastapi",
57
+ framework_version=self._framework_version,
58
+ )
59
+
60
+ client.capture_exception(
61
+ exc,
62
+ request=request_ctx,
63
+ metadata={"framework": "fastapi"},
64
+ )
65
+
66
+ raise
67
+
68
+ @staticmethod
69
+ def _build_request_context(scope: dict) -> RequestContext:
70
+ """Extract request context from ASGI scope."""
71
+ path = scope.get("path", "")
72
+ method = scope.get("method", "")
73
+
74
+ # Extract query params
75
+ query_string = scope.get("query_string", b"")
76
+ query_params = None
77
+ if query_string:
78
+ from urllib.parse import parse_qs
79
+ parsed = parse_qs(query_string.decode("utf-8", errors="replace"))
80
+ query_params = {k: v[0] if len(v) == 1 else ",".join(v) for k, v in parsed.items()}
81
+
82
+ # Extract route from path params if available
83
+ route = path
84
+ path_params = scope.get("path_params", {})
85
+ if path_params:
86
+ # Reconstruct route pattern from path and params
87
+ for key, value in path_params.items():
88
+ route = route.replace(str(value), f"{{{key}}}")
89
+
90
+ return RequestContext(
91
+ route=route,
92
+ method=method,
93
+ query_params=query_params,
94
+ )
@@ -0,0 +1,57 @@
1
+ """BugStack integration for Flask."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import Any
7
+
8
+ logger = logging.getLogger("bugstack")
9
+
10
+
11
+ def init_app(app: Any) -> None:
12
+ """Register BugStack error handler on a Flask app.
13
+
14
+ Usage:
15
+ from flask import Flask
16
+ import bugstack
17
+ from bugstack.integrations.flask import init_app
18
+
19
+ bugstack.init(api_key="bs_live_...")
20
+ app = Flask(__name__)
21
+ init_app(app)
22
+
23
+ Captures unhandled exceptions and re-raises them so
24
+ Flask's own error handling still works.
25
+ """
26
+
27
+ @app.errorhandler(Exception)
28
+ def _bugstack_error_handler(exc: Exception) -> Any:
29
+ try:
30
+ import bugstack
31
+ from flask import request as flask_request
32
+ from ..types import RequestContext
33
+
34
+ client = bugstack.get_client()
35
+ if client:
36
+ request_ctx = RequestContext(
37
+ route=flask_request.url_rule.rule if flask_request.url_rule else flask_request.path,
38
+ method=flask_request.method,
39
+ )
40
+ client.capture_exception(
41
+ exc,
42
+ request=request_ctx,
43
+ metadata={"framework": "flask"},
44
+ )
45
+ except Exception as inner:
46
+ logger.warning("[BugStack] Error capturing exception: %s", inner)
47
+
48
+ # Re-raise so Flask handles it normally
49
+ raise exc
50
+
51
+ # Also try to detect Flask version for environment info
52
+ try:
53
+ from importlib.metadata import version
54
+ flask_version = version("flask")
55
+ logger.debug("[BugStack] Flask integration initialized (Flask %s)", flask_version)
56
+ except Exception:
57
+ logger.debug("[BugStack] Flask integration initialized")
@@ -0,0 +1,71 @@
1
+ """BugStack generic Python integration.
2
+
3
+ Hooks sys.excepthook and threading.excepthook to capture
4
+ all unhandled exceptions.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import sys
11
+ import threading
12
+ from typing import Any, Optional
13
+
14
+ logger = logging.getLogger("bugstack")
15
+
16
+ _original_excepthook = sys.excepthook
17
+ _original_threading_excepthook = getattr(threading, "excepthook", None)
18
+
19
+
20
+ def install_hooks() -> None:
21
+ """Install global exception hooks.
22
+
23
+ Usage:
24
+ import bugstack
25
+ from bugstack.integrations.generic import install_hooks
26
+
27
+ bugstack.init(api_key="bs_live_...")
28
+ install_hooks()
29
+ """
30
+ sys.excepthook = _bugstack_excepthook
31
+
32
+ if hasattr(threading, "excepthook"):
33
+ threading.excepthook = _bugstack_threading_excepthook
34
+
35
+ logger.debug("[BugStack] Global exception hooks installed")
36
+
37
+
38
+ def uninstall_hooks() -> None:
39
+ """Restore original exception hooks."""
40
+ sys.excepthook = _original_excepthook
41
+
42
+ if _original_threading_excepthook is not None:
43
+ threading.excepthook = _original_threading_excepthook
44
+
45
+
46
+ def _bugstack_excepthook(exc_type: type, exc_value: BaseException, exc_tb: Any) -> None:
47
+ """Custom sys.excepthook that captures exceptions before passing through."""
48
+ try:
49
+ import bugstack
50
+ bugstack.capture_exception(exc_value)
51
+ except Exception:
52
+ pass
53
+
54
+ # Call the original hook so normal behavior (printing traceback) still happens
55
+ _original_excepthook(exc_type, exc_value, exc_tb)
56
+
57
+
58
+ def _bugstack_threading_excepthook(args: Any) -> None:
59
+ """Custom threading.excepthook for unhandled thread exceptions."""
60
+ try:
61
+ import bugstack
62
+ if args.exc_value is not None:
63
+ bugstack.capture_exception(
64
+ args.exc_value,
65
+ metadata={"thread": args.thread.name if args.thread else "unknown"},
66
+ )
67
+ except Exception:
68
+ pass
69
+
70
+ if _original_threading_excepthook is not None:
71
+ _original_threading_excepthook(args)
bugstack/py.typed ADDED
File without changes
bugstack/transport.py ADDED
@@ -0,0 +1,171 @@
1
+ """HTTP transport with async support and retry logic."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import logging
8
+ import threading
9
+ import time
10
+ from typing import Any, Optional
11
+
12
+ from .types import SDK_VERSION
13
+
14
+ logger = logging.getLogger("bugstack")
15
+
16
+ # Lazy import httpx to give a clear error if not installed
17
+ _httpx = None
18
+
19
+
20
+ def _get_httpx():
21
+ global _httpx
22
+ if _httpx is None:
23
+ try:
24
+ import httpx
25
+ _httpx = httpx
26
+ except ImportError:
27
+ raise ImportError(
28
+ "bugstack requires httpx. Install it with: pip install httpx"
29
+ )
30
+ return _httpx
31
+
32
+
33
+ class Transport:
34
+ """HTTP transport that sends error events to the BugStack API.
35
+
36
+ Handles retry with exponential backoff and background sending.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ endpoint: str,
42
+ api_key: str,
43
+ timeout: float = 5.0,
44
+ max_retries: int = 3,
45
+ debug: bool = False,
46
+ ) -> None:
47
+ self._endpoint = endpoint
48
+ self._api_key = api_key
49
+ self._timeout = timeout
50
+ self._max_retries = max_retries
51
+ self._debug = debug
52
+ self._worker_thread: Optional[threading.Thread] = None
53
+ self._queue: list[dict[str, Any]] = []
54
+ self._queue_lock = threading.Lock()
55
+ self._stop_event = threading.Event()
56
+ self._start_worker()
57
+
58
+ def _start_worker(self) -> None:
59
+ """Start background worker thread for sending events."""
60
+ self._worker_thread = threading.Thread(
61
+ target=self._worker_loop,
62
+ daemon=True,
63
+ name="bugstack-transport",
64
+ )
65
+ self._worker_thread.start()
66
+
67
+ def _worker_loop(self) -> None:
68
+ """Process queued events in the background."""
69
+ while not self._stop_event.is_set():
70
+ payloads: list[dict[str, Any]] = []
71
+ with self._queue_lock:
72
+ if self._queue:
73
+ payloads = self._queue[:]
74
+ self._queue.clear()
75
+
76
+ for payload in payloads:
77
+ self._send_with_retry(payload)
78
+
79
+ self._stop_event.wait(timeout=0.5)
80
+
81
+ def enqueue(self, payload: dict[str, Any]) -> None:
82
+ """Add a payload to the send queue (non-blocking)."""
83
+ with self._queue_lock:
84
+ # Bound the queue to prevent unbounded memory growth
85
+ if len(self._queue) < 100:
86
+ self._queue.append(payload)
87
+ elif self._debug:
88
+ logger.warning("[BugStack] Queue full, dropping event")
89
+
90
+ def _send_with_retry(self, payload: dict[str, Any]) -> bool:
91
+ """Send a payload with exponential backoff retry."""
92
+ httpx = _get_httpx()
93
+
94
+ headers = {
95
+ "Content-Type": "application/json",
96
+ "X-BugStack-API-Key": self._api_key,
97
+ "X-BugStack-SDK-Version": SDK_VERSION,
98
+ }
99
+
100
+ for attempt in range(self._max_retries):
101
+ try:
102
+ with httpx.Client(timeout=self._timeout) as client:
103
+ response = client.post(
104
+ self._endpoint,
105
+ content=json.dumps(payload),
106
+ headers=headers,
107
+ )
108
+
109
+ if response.status_code < 400:
110
+ if self._debug:
111
+ logger.debug("[BugStack] Event sent successfully")
112
+ return True
113
+
114
+ if self._debug:
115
+ logger.warning(
116
+ "[BugStack] HTTP %d: %s",
117
+ response.status_code,
118
+ response.text[:200],
119
+ )
120
+
121
+ except Exception as exc:
122
+ if self._debug:
123
+ logger.warning("[BugStack] Send failed (attempt %d): %s", attempt + 1, exc)
124
+
125
+ # Exponential backoff: 1s, 2s, 4s
126
+ if attempt < self._max_retries - 1:
127
+ delay = 2 ** attempt
128
+ time.sleep(delay)
129
+
130
+ if self._debug:
131
+ logger.error("[BugStack] Max retries exceeded, dropping event")
132
+ return False
133
+
134
+ async def send_async(self, payload: dict[str, Any]) -> bool:
135
+ """Send a payload asynchronously (for async frameworks)."""
136
+ httpx = _get_httpx()
137
+
138
+ headers = {
139
+ "Content-Type": "application/json",
140
+ "X-BugStack-API-Key": self._api_key,
141
+ "X-BugStack-SDK-Version": SDK_VERSION,
142
+ }
143
+
144
+ for attempt in range(self._max_retries):
145
+ try:
146
+ async with httpx.AsyncClient(timeout=self._timeout) as client:
147
+ response = await client.post(
148
+ self._endpoint,
149
+ content=json.dumps(payload),
150
+ headers=headers,
151
+ )
152
+
153
+ if response.status_code < 400:
154
+ if self._debug:
155
+ logger.debug("[BugStack] Event sent successfully (async)")
156
+ return True
157
+
158
+ except Exception as exc:
159
+ if self._debug:
160
+ logger.warning("[BugStack] Async send failed (attempt %d): %s", attempt + 1, exc)
161
+
162
+ if attempt < self._max_retries - 1:
163
+ await asyncio.sleep(2 ** attempt)
164
+
165
+ return False
166
+
167
+ def shutdown(self) -> None:
168
+ """Stop the worker thread."""
169
+ self._stop_event.set()
170
+ if self._worker_thread and self._worker_thread.is_alive():
171
+ self._worker_thread.join(timeout=2.0)
bugstack/types.py ADDED
@@ -0,0 +1,108 @@
1
+ """Type definitions for the BugStack SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import platform
6
+ import sys
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Callable, Optional, Union
9
+
10
+ SDK_VERSION = "1.0.0"
11
+
12
+
13
+ @dataclass
14
+ class BugStackConfig:
15
+ """Configuration for the BugStack SDK."""
16
+
17
+ api_key: str
18
+ endpoint: str = "https://api.bugstack.dev/api/capture"
19
+ project_id: str = ""
20
+ environment: str = "production"
21
+ auto_fix: bool = False
22
+ enabled: bool = True
23
+ debug: bool = False
24
+ dry_run: bool = False
25
+ deduplication_window: float = 300.0 # 5 minutes
26
+ timeout: float = 5.0 # seconds
27
+ max_retries: int = 3
28
+ ignored_errors: list[Union[str, type]] = field(default_factory=list)
29
+ before_send: Optional[Callable[["ErrorEvent"], Optional["ErrorEvent"]]] = None
30
+ redact_fields: list[str] = field(default_factory=list)
31
+
32
+
33
+ @dataclass
34
+ class RequestContext:
35
+ """HTTP request context attached to an error event."""
36
+
37
+ route: str = ""
38
+ method: str = ""
39
+ query_params: Optional[dict[str, str]] = None
40
+ headers: Optional[dict[str, str]] = None
41
+ body: Optional[Any] = None
42
+
43
+
44
+ @dataclass
45
+ class EnvironmentInfo:
46
+ """Runtime environment information."""
47
+
48
+ language: str = "python"
49
+ language_version: str = field(default_factory=lambda: platform.python_version())
50
+ framework: str = ""
51
+ framework_version: str = ""
52
+ os: str = field(default_factory=lambda: sys.platform)
53
+ sdk_version: str = SDK_VERSION
54
+
55
+
56
+ @dataclass
57
+ class ErrorEvent:
58
+ """An error event to be sent to BugStack."""
59
+
60
+ message: str
61
+ stack_trace: str = ""
62
+ file: str = ""
63
+ function: str = ""
64
+ fingerprint: str = ""
65
+ exception_type: str = ""
66
+ request: Optional[RequestContext] = None
67
+ environment: EnvironmentInfo = field(default_factory=EnvironmentInfo)
68
+ timestamp: str = ""
69
+ metadata: dict[str, Any] = field(default_factory=dict)
70
+
71
+ def to_payload(self, config: BugStackConfig) -> dict[str, Any]:
72
+ """Serialize to the standard BugStack API payload."""
73
+ payload: dict[str, Any] = {
74
+ "apiKey": config.api_key,
75
+ "error": {
76
+ "message": self.message,
77
+ "stackTrace": self.stack_trace,
78
+ "file": self.file,
79
+ "function": self.function,
80
+ "fingerprint": self.fingerprint,
81
+ },
82
+ "environment": {
83
+ "language": self.environment.language,
84
+ "languageVersion": self.environment.language_version,
85
+ "framework": self.environment.framework,
86
+ "frameworkVersion": self.environment.framework_version,
87
+ "os": self.environment.os,
88
+ "sdkVersion": self.environment.sdk_version,
89
+ },
90
+ "timestamp": self.timestamp,
91
+ }
92
+
93
+ if self.request:
94
+ payload["request"] = {
95
+ "route": self.request.route,
96
+ "method": self.request.method,
97
+ }
98
+
99
+ if config.project_id:
100
+ payload["projectId"] = config.project_id
101
+
102
+ if self.metadata:
103
+ payload["metadata"] = self.metadata
104
+
105
+ if config.auto_fix:
106
+ payload.setdefault("metadata", {})["autoFix"] = True
107
+
108
+ return payload
@@ -0,0 +1,216 @@
1
+ Metadata-Version: 2.4
2
+ Name: bugstack
3
+ Version: 1.0.0
4
+ Summary: Official BugStack SDK for Python — capture, report, and auto-fix production errors.
5
+ Project-URL: Homepage, https://bugstack.dev
6
+ Project-URL: Documentation, https://docs.bugstack.dev/sdks/python
7
+ Project-URL: Repository, https://github.com/MasonBachmann7/bugstack-python
8
+ Project-URL: Issues, https://github.com/MasonBachmann7/bugstack-python/issues
9
+ Project-URL: Changelog, https://github.com/MasonBachmann7/bugstack-python/blob/main/CHANGELOG.md
10
+ Author-email: BugStack <team@bugstack.dev>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: auto-fix,bugstack,debugging,error-tracking,monitoring
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Software Development :: Bug Tracking
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.9
27
+ Requires-Dist: httpx>=0.24.0
28
+ Provides-Extra: dev
29
+ Requires-Dist: django>=3.2; extra == 'dev'
30
+ Requires-Dist: fastapi>=0.95; extra == 'dev'
31
+ Requires-Dist: flask>=2.0; extra == 'dev'
32
+ Requires-Dist: httpx>=0.24; extra == 'dev'
33
+ Requires-Dist: mypy>=1.0; extra == 'dev'
34
+ Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
35
+ Requires-Dist: pytest>=7.0; extra == 'dev'
36
+ Requires-Dist: respx>=0.20; extra == 'dev'
37
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
38
+ Provides-Extra: django
39
+ Requires-Dist: django>=3.2; extra == 'django'
40
+ Provides-Extra: fastapi
41
+ Requires-Dist: fastapi>=0.95.0; extra == 'fastapi'
42
+ Provides-Extra: flask
43
+ Requires-Dist: flask>=2.0.0; extra == 'flask'
44
+ Description-Content-Type: text/markdown
45
+
46
+ # bugstack-python
47
+
48
+ Official Python SDK for [BugStack](https://bugstack.dev) — capture, report, and auto-fix production errors.
49
+
50
+ [![PyPI](https://img.shields.io/pypi/v/bugstack)](https://pypi.org/project/bugstack/)
51
+ [![Python](https://img.shields.io/pypi/pyversions/bugstack)](https://pypi.org/project/bugstack/)
52
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
53
+
54
+ ## Installation
55
+
56
+ ```bash
57
+ pip install bugstack
58
+ ```
59
+
60
+ ## Quick Start
61
+
62
+ ```python
63
+ import bugstack
64
+
65
+ bugstack.init(api_key="bs_live_...")
66
+
67
+ try:
68
+ risky_operation()
69
+ except Exception as e:
70
+ bugstack.capture_exception(e)
71
+ ```
72
+
73
+ ## Framework Integrations
74
+
75
+ ### FastAPI
76
+
77
+ ```python
78
+ from fastapi import FastAPI
79
+ from bugstack.integrations.fastapi import FastAPIMiddleware
80
+
81
+ app = FastAPI()
82
+ app.add_middleware(FastAPIMiddleware)
83
+
84
+ bugstack.init(api_key="bs_live_...")
85
+ ```
86
+
87
+ ### Django
88
+
89
+ ```python
90
+ # settings.py
91
+ MIDDLEWARE = [
92
+ 'bugstack.integrations.django.BugStackMiddleware',
93
+ # ... other middleware
94
+ ]
95
+
96
+ BUGSTACK_API_KEY = "bs_live_..."
97
+ BUGSTACK_AUTO_FIX = True # optional
98
+ ```
99
+
100
+ ### Flask
101
+
102
+ ```python
103
+ from flask import Flask
104
+ from bugstack.integrations.flask import init_app
105
+
106
+ app = Flask(__name__)
107
+ bugstack.init(api_key="bs_live_...")
108
+ init_app(app)
109
+ ```
110
+
111
+ ### Generic (sys.excepthook)
112
+
113
+ ```python
114
+ from bugstack.integrations.generic import install_hooks
115
+
116
+ bugstack.init(api_key="bs_live_...")
117
+ install_hooks()
118
+ ```
119
+
120
+ ## Configuration
121
+
122
+ ```python
123
+ bugstack.init(
124
+ api_key="bs_live_...", # Required
125
+ environment="production", # Default: "production"
126
+ auto_fix=True, # Enable AI-powered auto-fix
127
+ debug=False, # Log SDK activity
128
+ dry_run=False, # Log without sending
129
+ enabled=True, # Kill switch
130
+ deduplication_window=300, # Seconds (default: 5 min)
131
+ timeout=5.0, # HTTP timeout in seconds
132
+ max_retries=3, # Retry attempts
133
+ ignored_errors=[ # Errors to skip
134
+ KeyboardInterrupt,
135
+ "expected error message",
136
+ ],
137
+ before_send=my_hook, # Inspect/modify/drop events
138
+ redact_fields=["password"], # Fields to redact
139
+ )
140
+ ```
141
+
142
+ ## Data Transparency
143
+
144
+ ### `before_send` Hook
145
+
146
+ Inspect, modify, or drop any event before it leaves your application:
147
+
148
+ ```python
149
+ def before_send(event):
150
+ # Drop health check errors
151
+ if "health" in event.request.route:
152
+ return None
153
+
154
+ # Redact sensitive data
155
+ event.metadata.pop("secret", None)
156
+
157
+ return event
158
+
159
+ bugstack.init(api_key="bs_live_...", before_send=before_send)
160
+ ```
161
+
162
+ ### `ignored_errors`
163
+
164
+ Skip specific error types or messages:
165
+
166
+ ```python
167
+ bugstack.init(
168
+ api_key="bs_live_...",
169
+ ignored_errors=[
170
+ KeyboardInterrupt, # By type
171
+ SystemExit, # By type
172
+ "Connection reset", # By exact message
173
+ ],
174
+ )
175
+ ```
176
+
177
+ ### `dry_run` Mode
178
+
179
+ See exactly what would be sent without making any network requests:
180
+
181
+ ```python
182
+ bugstack.init(api_key="bs_live_...", dry_run=True)
183
+ # Prints: [BugStack DryRun] Would send: { ... }
184
+ ```
185
+
186
+ ## What Gets Sent
187
+
188
+ Every error event contains exactly this — nothing more:
189
+
190
+ ```json
191
+ {
192
+ "apiKey": "bs_live_...",
193
+ "error": {
194
+ "message": "division by zero",
195
+ "stackTrace": "Traceback (most recent call last)...",
196
+ "file": "app/api/handler.py",
197
+ "function": "process_request",
198
+ "fingerprint": "a1b2c3d4e5f6g7h8"
199
+ },
200
+ "environment": {
201
+ "language": "python",
202
+ "languageVersion": "3.12.1",
203
+ "framework": "fastapi",
204
+ "frameworkVersion": "0.109.0",
205
+ "os": "linux",
206
+ "sdkVersion": "1.0.0"
207
+ },
208
+ "timestamp": "2026-01-15T08:30:00+00:00"
209
+ }
210
+ ```
211
+
212
+ No cookies. No IP addresses. No user data. No request bodies (unless you explicitly include them).
213
+
214
+ ## License
215
+
216
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,15 @@
1
+ bugstack/__init__.py,sha256=hxWsmKjDZkplU17PbET2fsMATyoa-UuRtel-C2mAyn4,3933
2
+ bugstack/client.py,sha256=77kJ5CfMswYE7t1kKVa9kJ-eDlaSA4mbGI0je2wj49g,4948
3
+ bugstack/fingerprint.py,sha256=K43CxWzIcrm55vgIDXfsXDRDblp_Yd8pRwFd16aW7w4,2766
4
+ bugstack/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ bugstack/transport.py,sha256=_v3KQwYNUcLpbjPkeMjsEvMAmv-y3CEveR-TBA1_VYc,5670
6
+ bugstack/types.py,sha256=n8OJIkmwvXpYjY2dUzAO-T0TuL9Pg1ij-LHIttSsJjM,3364
7
+ bugstack/integrations/__init__.py,sha256=CkfxfB9X9W3r4VOpm0PKBbLz-IiB8J4RIT96gLjKvZk,135
8
+ bugstack/integrations/django.py,sha256=JfFN0HsLF2Bs2E041mXpN97aiFjatCU_YhtWLJrqYnc,3002
9
+ bugstack/integrations/fastapi.py,sha256=VB2xMhYXhXD43xB8_1lEjfpM4dsr0hWYNMBHadOC7Fk,2924
10
+ bugstack/integrations/flask.py,sha256=uAQHUIqpooKnwnmQxwGNhjkRiLFq6yfIfm3UJtEAkLE,1844
11
+ bugstack/integrations/generic.py,sha256=UBT_F0da21C1Iv-JdrLATn6AD43gdKFawONIzeDynHQ,2082
12
+ bugstack-1.0.0.dist-info/METADATA,sha256=bs1rFndOqxfpLggkXFkBnQv2KJ4vG07xm_FMX0hW21g,5797
13
+ bugstack-1.0.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
14
+ bugstack-1.0.0.dist-info/licenses/LICENSE,sha256=DDs477apGb0jQvBH36dkPnq5blv5bCqPy7TA3PWV440,1086
15
+ bugstack-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BugStack
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.