Repository navigation
feat: Add basic lock-free metrics batcher #8326
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
alexander-alderman-webb
wants to merge
23
commits into
webb/lock-free-base
Choose a base branch
from
webb/sliding-window-metrics-batcher
base: webb/lock-free-base
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+138
−0
Open
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
36694ec
feat: Add basic lock-free metrics batcher
alexander-alderman-webb 9434dbb
chore: Reset batchers at fork from client
alexander-alderman-webb e6fdd6c
merge
alexander-alderman-webb 2f854bc
remove register_at_fork remnants
alexander-alderman-webb 868f23f
use single consumer
alexander-alderman-webb bc3dd79
use sentinels
alexander-alderman-webb d8c36a2
simplify tests
alexander-alderman-webb cd895eb
Merge branch 'webb/deduplicate-register-at-fork' into webb/sliding-wi…
alexander-alderman-webb fb7b724
restore uv.lock
alexander-alderman-webb 8d305c0
Merge branch 'webb/deduplicate-register-at-fork' into webb/sliding-wi…
alexander-alderman-webb d0f0830
simplify
alexander-alderman-webb 551c0f0
remove active flag
alexander-alderman-webb 66b78ac
simplify further
alexander-alderman-webb 921e3e7
clean up types
alexander-alderman-webb 35804f1
fix comments
alexander-alderman-webb b9ca918
remove comment
alexander-alderman-webb 99b7be1
remove comments
alexander-alderman-webb c39a589
use superclass
alexander-alderman-webb 41bf46c
drop client-owned register_at_fork changes
alexander-alderman-webb 721094c
remove redundant capture_internal_exceptions()
alexander-alderman-webb c97978e
Merge branch 'webb/lock-free-base' into webb/sliding-window-metrics-b…
alexander-alderman-webb 3fececf
Merge branch 'webb/lock-free-base' into webb/sliding-window-metrics-b…
alexander-alderman-webb d3a620e
check self._active flag
alexander-alderman-webb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| import os | ||
| import threading | ||
| from collections import deque | ||
| from datetime import datetime, timezone | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| from sentry_sdk._batcher import Batcher | ||
| from sentry_sdk.envelope import Envelope | ||
| from sentry_sdk.utils import ( | ||
| format_timestamp, | ||
| serialize_attribute, | ||
| ) | ||
|
|
||
| if TYPE_CHECKING: | ||
| from typing import Any, Callable, Optional | ||
|
|
||
| from sentry_sdk._types import Metric | ||
|
|
||
|
|
||
| class LockFreeMetricsBatcher(Batcher["Metric"]): | ||
| MAX_BEFORE_FLUSH = 1000 | ||
| MAX_BEFORE_DROP = 10_000 | ||
| FLUSH_WAIT_TIME = 5.0 | ||
|
|
||
| TYPE = "trace_metric" | ||
| CLIENT_REPORT_TYPE = "trace_metric" | ||
| CONTENT_TYPE = "application/vnd.sentry.items.trace-metric+json" | ||
|
|
||
| def __init__( | ||
| self, | ||
| capture_func: "Callable[[Envelope], None]", | ||
| record_lost_func: "Callable[..., None]", | ||
| ) -> None: | ||
| super().__init__(capture_func, record_lost_func) | ||
| self._queue: "deque[Metric]" = deque() | ||
| # Holds the claim of the one thread that gets to start the flusher. | ||
| self._flusher_claim: "dict[str, object]" = {} | ||
|
|
||
| def _reset_thread_state(self) -> None: | ||
| super()._reset_thread_state() | ||
| self._queue = deque() | ||
| self._flusher_claim = {} | ||
|
|
||
| def _ensure_thread(self) -> bool: | ||
| """For forking processes we might need to restart this thread. | ||
| This ensures that our process actually has that thread running. | ||
| """ | ||
| if not self._running: | ||
| return False | ||
|
|
||
| pid = os.getpid() | ||
| if self._flusher_pid == pid: | ||
| return True | ||
|
|
||
| # dict.setdefault is atomic, so exactly one thread gets to start the flusher. | ||
| claim = object() | ||
| if self._flusher_claim.setdefault("flusher", claim) is not claim: | ||
| return True | ||
|
alexander-alderman-webb marked this conversation as resolved.
Resolved
|
||
|
|
||
| flusher = threading.Thread(target=self._flush_loop) | ||
| flusher.daemon = True | ||
| try: | ||
| flusher.start() | ||
| except RuntimeError: | ||
| # Unfortunately at this point the interpreter is in a state that no | ||
| # longer allows us to spawn a thread and we have to bail. | ||
| self._running = False | ||
| return False | ||
|
|
||
| self._flusher = flusher | ||
| self._flusher_pid = pid | ||
| return True | ||
|
|
||
| def add(self, item: "Metric") -> None: | ||
| # Bail out if the current thread is already executing batcher code. | ||
| if getattr(self._active, "flag", False): | ||
| return None | ||
|
|
||
| self._active.flag = True | ||
| try: | ||
| if not self._ensure_thread(): | ||
| return None | ||
|
|
||
| queue = self._queue | ||
| if len(queue) >= self.MAX_BEFORE_DROP: | ||
| self._record_lost(item) | ||
| return None | ||
|
|
||
| queue.append(item) | ||
| if len(queue) < self.MAX_BEFORE_FLUSH or self._flush_event.is_set(): | ||
| return | ||
|
|
||
| self._flush_event.set() | ||
| finally: | ||
| self._active.flag = False | ||
|
|
||
| def _flush(self) -> "Optional[Envelope]": | ||
| queue = self._queue | ||
| items: "list[Metric]" = [] | ||
| # Only take what's queued now. Producers can keep enqueuing (no locks). | ||
| for _ in range(len(queue)): | ||
| try: | ||
| items.append(queue.popleft()) | ||
| except IndexError: | ||
| break | ||
|
|
||
| if not items: | ||
| return None | ||
|
|
||
| envelope = Envelope( | ||
| headers={"sent_at": format_timestamp(datetime.now(timezone.utc))} | ||
| ) | ||
| envelope.add_item(self._to_envelope_item(items)) | ||
| self._capture_func(envelope) | ||
| return envelope | ||
|
|
||
| @staticmethod | ||
| def _to_transport_format(item: "Metric") -> "Any": | ||
| res = { | ||
| "timestamp": item["timestamp"], | ||
| "name": item["name"], | ||
| "type": item["type"], | ||
| "value": item["value"], | ||
| "attributes": { | ||
| k: serialize_attribute(v) for (k, v) in item["attributes"].items() | ||
| }, | ||
| } | ||
|
|
||
| if item.get("trace_id") is not None: | ||
| res["trace_id"] = item["trace_id"] | ||
|
|
||
| if item.get("span_id") is not None: | ||
| res["span_id"] = item["span_id"] | ||
|
|
||
| if item.get("unit") is not None: | ||
| res["unit"] = item["unit"] | ||
|
|
||
| return res | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
TIL of this setdefault hack