|
| 1 | +import os |
| 2 | +import random |
| 3 | +import threading |
| 4 | +from datetime import datetime, timezone |
| 5 | +from typing import TYPE_CHECKING, TypeVar, Generic |
| 6 | + |
| 7 | +from sentry_sdk.utils import format_timestamp, safe_repr, serialize_attribute |
| 8 | +from sentry_sdk.envelope import Envelope, Item, PayloadRef |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + from typing import Optional, Callable, Any |
| 12 | + |
| 13 | +T = TypeVar("T") |
| 14 | + |
| 15 | + |
| 16 | +class Batcher(Generic[T]): |
| 17 | + MAX_BEFORE_FLUSH = 100 |
| 18 | + MAX_BEFORE_DROP = 1_000 |
| 19 | + FLUSH_WAIT_TIME = 5.0 |
| 20 | + |
| 21 | + TYPE = "" |
| 22 | + CONTENT_TYPE = "" |
| 23 | + |
| 24 | + def __init__( |
| 25 | + self, |
| 26 | + capture_func: "Callable[[Envelope], None]", |
| 27 | + record_lost_func: "Callable[..., None]", |
| 28 | + ) -> None: |
| 29 | + self._buffer: "list[T]" = [] |
| 30 | + self._capture_func = capture_func |
| 31 | + self._record_lost_func = record_lost_func |
| 32 | + self._running = True |
| 33 | + self._lock = threading.Lock() |
| 34 | + |
| 35 | + self._flush_event: "threading.Event" = threading.Event() |
| 36 | + |
| 37 | + self._flusher: "Optional[threading.Thread]" = None |
| 38 | + self._flusher_pid: "Optional[int]" = None |
| 39 | + |
| 40 | + def _ensure_thread(self) -> bool: |
| 41 | + """For forking processes we might need to restart this thread. |
| 42 | + This ensures that our process actually has that thread running. |
| 43 | + """ |
| 44 | + if not self._running: |
| 45 | + return False |
| 46 | + |
| 47 | + pid = os.getpid() |
| 48 | + if self._flusher_pid == pid: |
| 49 | + return True |
| 50 | + |
| 51 | + with self._lock: |
| 52 | + # Recheck to make sure another thread didn't get here and start the |
| 53 | + # the flusher in the meantime |
| 54 | + if self._flusher_pid == pid: |
| 55 | + return True |
| 56 | + |
| 57 | + self._flusher_pid = pid |
| 58 | + |
| 59 | + self._flusher = threading.Thread(target=self._flush_loop) |
| 60 | + self._flusher.daemon = True |
| 61 | + |
| 62 | + try: |
| 63 | + self._flusher.start() |
| 64 | + except RuntimeError: |
| 65 | + # Unfortunately at this point the interpreter is in a state that no |
| 66 | + # longer allows us to spawn a thread and we have to bail. |
| 67 | + self._running = False |
| 68 | + return False |
| 69 | + |
| 70 | + return True |
| 71 | + |
| 72 | + def _flush_loop(self) -> None: |
| 73 | + while self._running: |
| 74 | + self._flush_event.wait(self.FLUSH_WAIT_TIME + random.random()) |
| 75 | + self._flush_event.clear() |
| 76 | + self._flush() |
| 77 | + |
| 78 | + def add(self, item: "T") -> None: |
| 79 | + if not self._ensure_thread() or self._flusher is None: |
| 80 | + return None |
| 81 | + |
| 82 | + with self._lock: |
| 83 | + if len(self._buffer) >= self.MAX_BEFORE_DROP: |
| 84 | + self._record_lost(item) |
| 85 | + return None |
| 86 | + |
| 87 | + self._buffer.append(item) |
| 88 | + if len(self._buffer) >= self.MAX_BEFORE_FLUSH: |
| 89 | + self._flush_event.set() |
| 90 | + |
| 91 | + def kill(self) -> None: |
| 92 | + if self._flusher is None: |
| 93 | + return |
| 94 | + |
| 95 | + self._running = False |
| 96 | + self._flush_event.set() |
| 97 | + self._flusher = None |
| 98 | + |
| 99 | + def flush(self) -> None: |
| 100 | + self._flush() |
| 101 | + |
| 102 | + def _add_to_envelope(self, envelope: "Envelope") -> None: |
| 103 | + envelope.add_item( |
| 104 | + Item( |
| 105 | + type=self.TYPE, |
| 106 | + content_type=self.CONTENT_TYPE, |
| 107 | + headers={ |
| 108 | + "item_count": len(self._buffer), |
| 109 | + }, |
| 110 | + payload=PayloadRef( |
| 111 | + json={ |
| 112 | + "items": [ |
| 113 | + self._to_transport_format(item) for item in self._buffer |
| 114 | + ] |
| 115 | + } |
| 116 | + ), |
| 117 | + ) |
| 118 | + ) |
| 119 | + |
| 120 | + def _flush(self) -> "Optional[Envelope]": |
| 121 | + envelope = Envelope( |
| 122 | + headers={"sent_at": format_timestamp(datetime.now(timezone.utc))} |
| 123 | + ) |
| 124 | + with self._lock: |
| 125 | + if len(self._buffer) == 0: |
| 126 | + return None |
| 127 | + |
| 128 | + self._add_to_envelope(envelope) |
| 129 | + self._buffer.clear() |
| 130 | + |
| 131 | + self._capture_func(envelope) |
| 132 | + return envelope |
| 133 | + |
| 134 | + def _record_lost(self, item: "T") -> None: |
| 135 | + pass |
| 136 | + |
| 137 | + @staticmethod |
| 138 | + def _to_transport_format(item: "T") -> "Any": |
| 139 | + pass |
0 commit comments