|
1 | 1 | from __future__ import annotations
|
| 2 | +from abc import ABC, abstractmethod |
2 | 3 | import os
|
3 | 4 | import threading
|
4 | 5 |
|
|
16 | 17 | _TERMINATOR = object()
|
17 | 18 |
|
18 | 19 |
|
19 |
| -class BackgroundWorker: |
| 20 | +class Worker(ABC): |
| 21 | + """ |
| 22 | + Base class for all workers. |
| 23 | +
|
| 24 | + A worker is used to process events in the background and send them to Sentry. |
| 25 | + """ |
| 26 | + |
| 27 | + @property |
| 28 | + @abstractmethod |
| 29 | + def is_alive(self) -> bool: |
| 30 | + """ |
| 31 | + Checks whether the worker is alive and running. |
| 32 | +
|
| 33 | + Returns True if the worker is alive, False otherwise. |
| 34 | + """ |
| 35 | + pass |
| 36 | + |
| 37 | + @abstractmethod |
| 38 | + def kill(self) -> None: |
| 39 | + """ |
| 40 | + Kills the worker. |
| 41 | +
|
| 42 | + This method is used to kill the worker. The queue will be drained up to the point where the worker is killed. |
| 43 | + The worker will not be able to process any more events. |
| 44 | + """ |
| 45 | + pass |
| 46 | + |
| 47 | + def flush( |
| 48 | + self, timeout: float, callback: Optional[Callable[[int, float], Any]] = None |
| 49 | + ) -> None: |
| 50 | + """ |
| 51 | + Flush the worker. |
| 52 | +
|
| 53 | + This method blocks until the worker has flushed all events or the specified timeout is reached. |
| 54 | + Default implementation is a no-op, since this method may only be relevant to some workers. |
| 55 | + Subclasses should override this method if necessary. |
| 56 | + """ |
| 57 | + return None |
| 58 | + |
| 59 | + @abstractmethod |
| 60 | + def full(self) -> bool: |
| 61 | + """ |
| 62 | + Checks whether the worker's queue is full. |
| 63 | +
|
| 64 | + Returns True if the queue is full, False otherwise. |
| 65 | + """ |
| 66 | + pass |
| 67 | + |
| 68 | + @abstractmethod |
| 69 | + def submit(self, callback: Callable[[], Any]) -> bool: |
| 70 | + """ |
| 71 | + Schedule a callback to be executed by the worker. |
| 72 | +
|
| 73 | + Returns True if the callback was scheduled, False if the queue is full. |
| 74 | + """ |
| 75 | + pass |
| 76 | + |
| 77 | + |
| 78 | +class BackgroundWorker(Worker): |
20 | 79 | def __init__(self, queue_size: int = DEFAULT_QUEUE_SIZE) -> None:
|
21 | 80 | self._queue: Queue = Queue(queue_size)
|
22 | 81 | self._lock = threading.Lock()
|
@@ -106,7 +165,7 @@ def _wait_flush(self, timeout: float, callback: Optional[Any]) -> None:
|
106 | 165 | pending = self._queue.qsize() + 1
|
107 | 166 | logger.error("flush timed out, dropped %s events", pending)
|
108 | 167 |
|
109 |
| - def submit(self, callback: Callable[[], None]) -> bool: |
| 168 | + def submit(self, callback: Callable[[], Any]) -> bool: |
110 | 169 | self._ensure_thread()
|
111 | 170 | try:
|
112 | 171 | self._queue.put_nowait(callback)
|
|
0 commit comments