bugstack 1.0.0__py3-none-any.whl → 1.2.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 CHANGED
@@ -1,142 +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
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://dashboard.bugstack.ai/api/ingest/sdk",
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 CHANGED
@@ -1,151 +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()
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()