debugbundle-python 1.2.0__tar.gz → 1.4.0__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.
Files changed (47) hide show
  1. debugbundle_python-1.4.0/LICENSE +202 -0
  2. {debugbundle_python-1.2.0/src/debugbundle_python.egg-info → debugbundle_python-1.4.0}/PKG-INFO +4 -4
  3. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/README.md +2 -2
  4. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/pyproject.toml +2 -2
  5. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/__init__.py +3 -0
  6. debugbundle_python-1.4.0/src/debugbundle/acknowledgement.py +71 -0
  7. debugbundle_python-1.4.0/src/debugbundle/before_send.py +218 -0
  8. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/core.py +139 -323
  9. debugbundle_python-1.4.0/src/debugbundle/event_support.py +281 -0
  10. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/transport.py +8 -2
  11. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0/src/debugbundle_python.egg-info}/PKG-INFO +4 -4
  12. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle_python.egg-info/SOURCES.txt +4 -0
  13. debugbundle_python-1.4.0/tests/test_before_send.py +134 -0
  14. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/tests/test_contracts.py +2 -1
  15. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/tests/test_http_integration.py +4 -2
  16. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/tests/test_repository_metadata.py +13 -1
  17. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/tests/test_sdk.py +168 -0
  18. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/tests/test_smoke_script.py +2 -2
  19. debugbundle_python-1.2.0/LICENSE +0 -17
  20. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/setup.cfg +0 -0
  21. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/config.py +0 -0
  22. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/integrations/__init__.py +0 -0
  23. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/integrations/common.py +0 -0
  24. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/integrations/django.py +0 -0
  25. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/integrations/fastapi.py +0 -0
  26. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/integrations/flask.py +0 -0
  27. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/integrations/relay_django.py +0 -0
  28. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/integrations/relay_fastapi.py +0 -0
  29. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/integrations/relay_flask.py +0 -0
  30. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/logger_integrations.py +0 -0
  31. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/py.typed +0 -0
  32. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/redaction.py +0 -0
  33. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/relay.py +0 -0
  34. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/relay_delivery.py +0 -0
  35. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/suppression.py +0 -0
  36. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle/trigger_token.py +0 -0
  37. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle_python.egg-info/dependency_links.txt +0 -0
  38. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle_python.egg-info/requires.txt +0 -0
  39. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/src/debugbundle_python.egg-info/top_level.txt +0 -0
  40. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/tests/test_framework_integrations.py +0 -0
  41. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/tests/test_hooks.py +0 -0
  42. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/tests/test_optional_imports.py +0 -0
  43. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/tests/test_relay.py +0 -0
  44. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/tests/test_relay_delivery.py +0 -0
  45. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/tests/test_remote_config.py +0 -0
  46. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/tests/test_schema_validation.py +0 -0
  47. {debugbundle_python-1.2.0 → debugbundle_python-1.4.0}/tests/test_trigger_token.py +0 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: debugbundle-python
3
- Version: 1.2.0
3
+ Version: 1.4.0
4
4
  Summary: DebugBundle SDK for Python
5
5
  Author: DebugBundle
6
- License-Expression: AGPL-3.0-only
6
+ License-Expression: Apache-2.0
7
7
  Project-URL: Homepage, https://debugbundle.com/docs/sdks/python
8
8
  Project-URL: Repository, https://github.com/debugbundle/debugbundle-python
9
9
  Project-URL: Issues, https://github.com/debugbundle/debugbundle-python/issues
@@ -43,7 +43,7 @@ Python SDK for DebugBundle.
43
43
 
44
44
  ![PyPI](https://img.shields.io/pypi/v/debugbundle-python?label=pypi)
45
45
  ![CI](https://img.shields.io/github/actions/workflow/status/debugbundle/debugbundle-python/ci.yml?branch=main&label=ci)
46
- ![License](https://img.shields.io/badge/license-AGPL--3.0--only-blue)
46
+ ![License](https://img.shields.io/badge/license-Apache--2.0-blue)
47
47
 
48
48
  Use this package to capture Python backend exceptions, request metadata, structured logs, runtime context, and probe data. It supports vanilla Python plus Django, Flask, FastAPI, Python logging, structlog, loguru, and browser relay helpers.
49
49
 
@@ -345,4 +345,4 @@ CI validates Ruff, mypy, pytest, package build, event schema fixtures, and cover
345
345
 
346
346
  ## License
347
347
 
348
- AGPL-3.0-only. See `LICENSE`.
348
+ Apache-2.0. See `LICENSE`.
@@ -4,7 +4,7 @@ Python SDK for DebugBundle.
4
4
 
5
5
  ![PyPI](https://img.shields.io/pypi/v/debugbundle-python?label=pypi)
6
6
  ![CI](https://img.shields.io/github/actions/workflow/status/debugbundle/debugbundle-python/ci.yml?branch=main&label=ci)
7
- ![License](https://img.shields.io/badge/license-AGPL--3.0--only-blue)
7
+ ![License](https://img.shields.io/badge/license-Apache--2.0-blue)
8
8
 
9
9
  Use this package to capture Python backend exceptions, request metadata, structured logs, runtime context, and probe data. It supports vanilla Python plus Django, Flask, FastAPI, Python logging, structlog, loguru, and browser relay helpers.
10
10
 
@@ -306,4 +306,4 @@ CI validates Ruff, mypy, pytest, package build, event schema fixtures, and cover
306
306
 
307
307
  ## License
308
308
 
309
- AGPL-3.0-only. See `LICENSE`.
309
+ Apache-2.0. See `LICENSE`.
@@ -4,11 +4,11 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "debugbundle-python"
7
- version = "1.2.0"
7
+ version = "1.4.0"
8
8
  description = "DebugBundle SDK for Python"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
11
- license = "AGPL-3.0-only"
11
+ license = "Apache-2.0"
12
12
  authors = [{ name = "DebugBundle" }]
13
13
  keywords = ["debugbundle", "debugging", "ai-agent", "error-tracking"]
14
14
  classifiers = [
@@ -7,6 +7,7 @@ from collections.abc import Callable, Mapping
7
7
  from contextvars import Token
8
8
  from typing import Any
9
9
 
10
+ from .before_send import BeforeSendHook
10
11
  from .config import RemoteProbeDirective
11
12
  from .core import ConfigFetchResponse, DebugBundleSdk
12
13
  from .relay import BrowserRelayAcceptedBatch, BrowserRelayHandler, BrowserRelayResponse
@@ -30,6 +31,7 @@ def init(
30
31
  probe_flush_on_error: bool = True,
31
32
  fetch_impl: Callable[[str, dict[str, object]], ConfigFetchResponse] | None = None,
32
33
  on_diagnostic: Callable[[dict[str, object]], None] | None = None,
34
+ before_send: BeforeSendHook | None = None,
33
35
  probes_poll_interval: int = 60_000,
34
36
  ) -> None:
35
37
  _sdk.init(
@@ -48,6 +50,7 @@ def init(
48
50
  probe_flush_on_error=probe_flush_on_error,
49
51
  fetch_impl=fetch_impl,
50
52
  on_diagnostic=on_diagnostic,
53
+ before_send=before_send,
51
54
  probes_poll_interval=probes_poll_interval,
52
55
  )
53
56
 
@@ -0,0 +1,71 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Literal, TypeGuard
5
+
6
+ RETRYABLE_REASONS = {
7
+ "rate_limited",
8
+ "monthly_quota_exceeded",
9
+ "analytics_quota_exceeded",
10
+ }
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class AcknowledgementDecision:
15
+ kind: Literal["legacy", "protocol_failure", "acknowledged"]
16
+ accepted: int = 0
17
+ retryable_indices: tuple[int, ...] = ()
18
+ terminal_errors: tuple[tuple[int, str], ...] = ()
19
+ reason: str | None = None
20
+
21
+
22
+ def decide_acknowledgement(body: object | None, batch_length: int) -> AcknowledgementDecision:
23
+ if not isinstance(body, dict) or not any(key in body for key in ("accepted", "rejected", "errors")):
24
+ return AcknowledgementDecision(kind="legacy")
25
+
26
+ accepted = body.get("accepted")
27
+ rejected = body.get("rejected")
28
+ errors = body.get("errors")
29
+ if (
30
+ not _is_count(accepted)
31
+ or not _is_count(rejected)
32
+ or not isinstance(errors, list)
33
+ or accepted + rejected != batch_length
34
+ or len(errors) != rejected
35
+ ):
36
+ return AcknowledgementDecision(kind="protocol_failure", reason="inconsistent_counts")
37
+
38
+ seen: set[int] = set()
39
+ retryable: list[int] = []
40
+ terminal: list[tuple[int, str]] = []
41
+ for error in errors:
42
+ if not isinstance(error, dict):
43
+ return AcknowledgementDecision(kind="protocol_failure", reason="invalid_error_index")
44
+ index = error.get("index")
45
+ reason = error.get("reason")
46
+ if (
47
+ not isinstance(index, int)
48
+ or isinstance(index, bool)
49
+ or index < 0
50
+ or index >= batch_length
51
+ or index in seen
52
+ or not isinstance(reason, str)
53
+ or not reason
54
+ ):
55
+ return AcknowledgementDecision(kind="protocol_failure", reason="invalid_error_index")
56
+ seen.add(index)
57
+ if reason in RETRYABLE_REASONS:
58
+ retryable.append(index)
59
+ else:
60
+ terminal.append((index, reason))
61
+
62
+ return AcknowledgementDecision(
63
+ kind="acknowledged",
64
+ accepted=accepted,
65
+ retryable_indices=tuple(retryable),
66
+ terminal_errors=tuple(terminal),
67
+ )
68
+
69
+
70
+ def _is_count(value: object) -> TypeGuard[int]:
71
+ return isinstance(value, int) and not isinstance(value, bool) and value >= 0
@@ -0,0 +1,218 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import uuid
5
+ from collections.abc import Callable, Mapping
6
+ from datetime import datetime
7
+
8
+ BeforeSendHook = Callable[[dict[str, object]], dict[str, object] | None]
9
+
10
+ _EVENT_PAYLOAD_FIELDS: dict[str, tuple[str, ...]] = {
11
+ "backend_exception": ("name", "message", "stack", "handled", "request", "response", "runtime"),
12
+ "request_event": ("method", "path", "query", "headers", "response_status", "duration_ms"),
13
+ "log_event": ("level", "message", "attributes"),
14
+ "frontend_breadcrumb": ("breadcrumb_type", "data"),
15
+ "frontend_exception": ("name", "message", "stack"),
16
+ "deploy_metadata": ("commit_sha", "version", "branch", "environment", "deployed_at"),
17
+ "error_suppressed": (
18
+ "fingerprint",
19
+ "suppressed_count",
20
+ "window_seconds",
21
+ "first_seen",
22
+ "last_seen",
23
+ ),
24
+ "probe_event": ("label", "data", "activation_id", "probe_label_pattern"),
25
+ }
26
+ _EVENT_PAYLOAD_ALLOWED_FIELDS: dict[str, frozenset[str]] = {
27
+ "backend_exception": frozenset((*_EVENT_PAYLOAD_FIELDS["backend_exception"], "probe_data")),
28
+ "request_event": frozenset(
29
+ (
30
+ *_EVENT_PAYLOAD_FIELDS["request_event"],
31
+ "body",
32
+ "route_template",
33
+ "response_headers",
34
+ "response_body",
35
+ "device",
36
+ )
37
+ ),
38
+ "log_event": frozenset((*_EVENT_PAYLOAD_FIELDS["log_event"], "device")),
39
+ "frontend_breadcrumb": frozenset((*_EVENT_PAYLOAD_FIELDS["frontend_breadcrumb"], "route", "device")),
40
+ "frontend_exception": frozenset(
41
+ (
42
+ *_EVENT_PAYLOAD_FIELDS["frontend_exception"],
43
+ "route",
44
+ "browser",
45
+ "breadcrumbs",
46
+ "device",
47
+ "browser_event",
48
+ "rejection_reason",
49
+ "dom_context",
50
+ "probe_data",
51
+ )
52
+ ),
53
+ "deploy_metadata": frozenset(_EVENT_PAYLOAD_FIELDS["deploy_metadata"]),
54
+ "error_suppressed": frozenset((*_EVENT_PAYLOAD_FIELDS["error_suppressed"], "device")),
55
+ "probe_event": frozenset((*_EVENT_PAYLOAD_FIELDS["probe_event"], "device")),
56
+ }
57
+ _ROOT_FIELDS = frozenset(
58
+ (
59
+ "schema_version",
60
+ "event_id",
61
+ "event_type",
62
+ "project_token",
63
+ "project_id",
64
+ "sdk_name",
65
+ "sdk_version",
66
+ "service",
67
+ "occurred_at",
68
+ "correlation",
69
+ "context",
70
+ "payload",
71
+ )
72
+ )
73
+
74
+
75
+ def apply_before_send(
76
+ event: dict[str, object],
77
+ hook: BeforeSendHook | None,
78
+ emit_diagnostic: Callable[[str, str], None],
79
+ ) -> dict[str, object] | None:
80
+ if hook is None:
81
+ return event
82
+
83
+ try:
84
+ result = hook(copy.deepcopy(event))
85
+ except Exception:
86
+ emit_diagnostic("before_send_failed", "Python before_send hook failed")
87
+ return event
88
+
89
+ if result is None:
90
+ return None
91
+ if not _is_valid_event(result):
92
+ emit_diagnostic("before_send_invalid_event", "Python before_send returned an invalid event")
93
+ return event
94
+ return result
95
+
96
+
97
+ def _is_valid_event(event: object) -> bool:
98
+ if not isinstance(event, dict):
99
+ return False
100
+ if not set(event).issubset(_ROOT_FIELDS):
101
+ return False
102
+ event_type = event.get("event_type")
103
+ if not isinstance(event_type, str) or event_type not in _EVENT_PAYLOAD_FIELDS:
104
+ return False
105
+ if not all(
106
+ isinstance(event.get(field), str) and event[field]
107
+ for field in ("schema_version", "sdk_name", "sdk_version", "occurred_at")
108
+ ):
109
+ return False
110
+ if not _timestamp(event["occurred_at"]):
111
+ return False
112
+ try:
113
+ uuid.UUID(str(event.get("event_id")))
114
+ except (ValueError, TypeError, AttributeError):
115
+ return False
116
+ service = event.get("service")
117
+ if (
118
+ not isinstance(service, dict)
119
+ or not isinstance(service.get("name"), str)
120
+ or not service["name"]
121
+ or not isinstance(service.get("environment"), str)
122
+ or not service["environment"]
123
+ ):
124
+ return False
125
+ payload = event.get("payload")
126
+ if not isinstance(payload, dict):
127
+ return False
128
+ if not set(payload).issubset(_EVENT_PAYLOAD_ALLOWED_FIELDS[event_type]):
129
+ return False
130
+ if not all(field in payload for field in _EVENT_PAYLOAD_FIELDS[event_type]):
131
+ return False
132
+ return _has_valid_payload_shape(event_type, payload)
133
+
134
+
135
+ def _has_valid_payload_shape(event_type: str, payload: Mapping[object, object]) -> bool:
136
+ if event_type == "backend_exception":
137
+ return (
138
+ _has_nonempty_strings(payload, "name", "message", "stack")
139
+ and isinstance(payload["handled"], bool)
140
+ and all(isinstance(payload[field], dict) for field in ("request", "response", "runtime"))
141
+ and _optional_dict(payload, "probe_data")
142
+ )
143
+ if event_type == "request_event":
144
+ return (
145
+ _has_nonempty_strings(payload, "method", "path")
146
+ and all(isinstance(payload[field], dict) for field in ("query", "headers"))
147
+ and _nonnegative_number(payload["response_status"])
148
+ and _nonnegative_number(payload["duration_ms"])
149
+ and _optional_dict(payload, "response_headers")
150
+ )
151
+ if event_type == "log_event":
152
+ return _has_nonempty_strings(payload, "level", "message") and isinstance(payload["attributes"], dict)
153
+ if event_type == "frontend_breadcrumb":
154
+ return _has_nonempty_strings(payload, "breadcrumb_type") and isinstance(payload["data"], dict)
155
+ if event_type == "frontend_exception":
156
+ return (
157
+ _has_nonempty_strings(payload, "name", "message", "stack")
158
+ and (payload.get("breadcrumbs") is None or isinstance(payload["breadcrumbs"], list))
159
+ and _optional_dict(payload, "probe_data")
160
+ )
161
+ if event_type == "deploy_metadata":
162
+ return _has_nonempty_strings(payload, "commit_sha", "version", "branch", "environment") and _timestamp(
163
+ payload["deployed_at"]
164
+ )
165
+ if event_type == "error_suppressed":
166
+ return (
167
+ _has_nonempty_strings(payload, "fingerprint")
168
+ and _nonnegative_integer(payload["suppressed_count"])
169
+ and _positive_integer(payload["window_seconds"])
170
+ and _timestamp(payload["first_seen"])
171
+ and _timestamp(payload["last_seen"])
172
+ )
173
+ if event_type == "probe_event":
174
+ activation_id = payload["activation_id"]
175
+ return (
176
+ _has_nonempty_strings(payload, "label", "probe_label_pattern")
177
+ and isinstance(payload["data"], dict)
178
+ and (activation_id is None or _uuid(activation_id))
179
+ )
180
+ return False
181
+
182
+
183
+ def _has_nonempty_strings(payload: Mapping[object, object], *fields: str) -> bool:
184
+ return all(isinstance(payload.get(field), str) and bool(str(payload[field]).strip()) for field in fields)
185
+
186
+
187
+ def _optional_dict(payload: Mapping[object, object], field: str) -> bool:
188
+ return field not in payload or isinstance(payload[field], dict)
189
+
190
+
191
+ def _nonnegative_number(value: object) -> bool:
192
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and value >= 0
193
+
194
+
195
+ def _nonnegative_integer(value: object) -> bool:
196
+ return isinstance(value, int) and not isinstance(value, bool) and value >= 0
197
+
198
+
199
+ def _positive_integer(value: object) -> bool:
200
+ return isinstance(value, int) and not isinstance(value, bool) and value > 0
201
+
202
+
203
+ def _uuid(value: object) -> bool:
204
+ try:
205
+ uuid.UUID(str(value))
206
+ except (ValueError, TypeError, AttributeError):
207
+ return False
208
+ return isinstance(value, str)
209
+
210
+
211
+ def _timestamp(value: object) -> bool:
212
+ if not isinstance(value, str):
213
+ return False
214
+ try:
215
+ datetime.fromisoformat(value.replace("Z", "+00:00"))
216
+ except ValueError:
217
+ return False
218
+ return True