Skip to content

Commit 75d0275

Browse files
committed
fun with python types
1 parent 3d8419c commit 75d0275

File tree

1 file changed

+56
-67
lines changed

1 file changed

+56
-67
lines changed

sentry_sdk/transport.py

Lines changed: 56 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
from typing import List
3636
from typing import Mapping
3737
from typing import Optional
38+
from typing import Self
3839
from typing import Tuple
3940
from typing import Type
4041
from typing import Union
@@ -67,20 +68,16 @@ class Transport(ABC):
6768

6869
parsed_dsn = None # type: Optional[Dsn]
6970

70-
def __init__(
71-
self, options=None # type: Optional[Dict[str, Any]]
72-
):
73-
# type: (...) -> None
71+
def __init__(self, options=None):
72+
# type: (Self, Optional[Dict[str, Any]]) -> None
7473
self.options = options
7574
if options and options["dsn"] is not None and options["dsn"]:
7675
self.parsed_dsn = Dsn(options["dsn"])
7776
else:
7877
self.parsed_dsn = None
7978

80-
def capture_event(
81-
self, event # type: Event
82-
):
83-
# type: (...) -> None
79+
def capture_event(self, event):
80+
# type: (Self, Event) -> None
8481
"""
8582
DEPRECATED: Please use capture_envelope instead.
8683
@@ -99,25 +96,23 @@ def capture_event(
9996
self.capture_envelope(envelope)
10097

10198
@abstractmethod
102-
def capture_envelope(
103-
self, envelope # type: Envelope
104-
):
105-
# type: (...) -> None
99+
def capture_envelope(self, envelope):
100+
# type: (Self, Envelope) -> None
106101
"""
107102
Send an envelope to Sentry.
108103
109104
Envelopes are a data container format that can hold any type of data
110105
submitted to Sentry. We use it to send all event data (including errors,
111-
transactions, crons checkins, etc.) to Sentry.
106+
transactions, crons check-ins, etc.) to Sentry.
112107
"""
113108
pass
114109

115110
def flush(
116111
self,
117-
timeout, # type: float
118-
callback=None, # type: Optional[Any]
112+
timeout,
113+
callback=None,
119114
):
120-
# type: (...) -> None
115+
# type: (Self, float, Optional[Any]) -> None
121116
"""
122117
Wait `timeout` seconds for the current events to be sent out.
123118
@@ -127,7 +122,7 @@ def flush(
127122
return None
128123

129124
def kill(self):
130-
# type: () -> None
125+
# type: (Self) -> None
131126
"""
132127
Forcefully kills the transport.
133128
@@ -162,19 +157,19 @@ def record_lost_event(
162157
return None
163158

164159
def is_healthy(self):
165-
# type: () -> bool
160+
# type: (Self) -> bool
166161
return True
167162

168163
def __del__(self):
169-
# type: () -> None
164+
# type: (Self) -> None
170165
try:
171166
self.kill()
172167
except Exception:
173168
pass
174169

175170

176171
def _parse_rate_limits(header, now=None):
177-
# type: (Any, Optional[datetime]) -> Iterable[Tuple[Optional[EventDataCategory], datetime]]
172+
# type: (str, Optional[datetime]) -> Iterable[Tuple[Optional[EventDataCategory], datetime]]
178173
if now is None:
179174
now = datetime.now(timezone.utc)
180175

@@ -203,10 +198,8 @@ def _parse_rate_limits(header, now=None):
203198
class BaseHttpTransport(Transport):
204199
"""The base HTTP transport."""
205200

206-
def __init__(
207-
self, options # type: Dict[str, Any]
208-
):
209-
# type: (...) -> None
201+
def __init__(self, options):
202+
# type: (Self, Dict[str, Any]) -> None
210203
from sentry_sdk.consts import VERSION
211204

212205
Transport.__init__(self, options)
@@ -299,11 +292,11 @@ def record_lost_event(
299292
self._discarded_events[data_category, reason] += quantity
300293

301294
def _get_header_value(self, response, header):
302-
# type: (Any, str) -> Optional[str]
295+
# type: (Self, Any, str) -> Optional[str]
303296
return response.headers.get(header)
304297

305298
def _update_rate_limits(self, response):
306-
# type: (Union[urllib3.BaseHTTPResponse, httpcore.Response]) -> None
299+
# type: (Self, Union[urllib3.BaseHTTPResponse, httpcore.Response]) -> None
307300

308301
# new sentries with more rate limit insights. We honor this header
309302
# no matter of the status code to update our internal rate limits.
@@ -329,12 +322,12 @@ def _update_rate_limits(self, response):
329322

330323
def _send_request(
331324
self,
332-
body, # type: bytes
333-
headers, # type: Dict[str, str]
334-
endpoint_type=EndpointType.ENVELOPE, # type: EndpointType
335-
envelope=None, # type: Optional[Envelope]
325+
body,
326+
headers,
327+
endpoint_type=EndpointType.ENVELOPE,
328+
envelope=None,
336329
):
337-
# type: (...) -> None
330+
# type: (Self, bytes, Dict[str, str], EndpointType, Optional[Envelope]) -> None
338331

339332
def record_loss(reason):
340333
# type: (str) -> None
@@ -384,12 +377,12 @@ def record_loss(reason):
384377
finally:
385378
response.close()
386379

387-
def on_dropped_event(self, reason):
388-
# type: (str) -> None
380+
def on_dropped_event(self, _reason):
381+
# type: (Self, str) -> None
389382
return None
390383

391384
def _fetch_pending_client_report(self, force=False, interval=60):
392-
# type: (bool, int) -> Optional[Item]
385+
# type: (Self, bool, int) -> Optional[Item]
393386
if not self.options["send_client_reports"]:
394387
return None
395388

@@ -420,7 +413,7 @@ def _fetch_pending_client_report(self, force=False, interval=60):
420413
)
421414

422415
def _flush_client_reports(self, force=False):
423-
# type: (bool) -> None
416+
# type: (Self, bool) -> None
424417
client_report = self._fetch_pending_client_report(force=force, interval=60)
425418
if client_report is not None:
426419
self.capture_envelope(Envelope(items=[client_report]))
@@ -441,23 +434,21 @@ def _disabled(bucket):
441434
return _disabled(category) or _disabled(None)
442435

443436
def _is_rate_limited(self):
444-
# type: () -> bool
437+
# type: (Self) -> bool
445438
return any(
446439
ts > datetime.now(timezone.utc) for ts in self._disabled_until.values()
447440
)
448441

449442
def _is_worker_full(self):
450-
# type: () -> bool
443+
# type: (Self) -> bool
451444
return self._worker.full()
452445

453446
def is_healthy(self):
454-
# type: () -> bool
447+
# type: (Self) -> bool
455448
return not (self._is_worker_full() or self._is_rate_limited())
456449

457-
def _send_envelope(
458-
self, envelope # type: Envelope
459-
):
460-
# type: (...) -> None
450+
def _send_envelope(self, envelope):
451+
# type: (Self, Envelope) -> None
461452

462453
# remove all items from the envelope which are over quota
463454
new_items = []
@@ -510,7 +501,7 @@ def _send_envelope(
510501
return None
511502

512503
def _serialize_envelope(self, envelope):
513-
# type: (..., Envelope) -> tuple[Optional[str], io.BytesIO]
504+
# type: (Self, Envelope) -> tuple[Optional[str], io.BytesIO]
514505
content_encoding = None
515506
body = io.BytesIO()
516507
if self._compression_level == 0 or self._compression_algo is None:
@@ -532,11 +523,11 @@ def _serialize_envelope(self, envelope):
532523
return content_encoding, body
533524

534525
def _get_pool_options(self, ca_certs, cert_file=None, key_file=None):
535-
# type: (Optional[Any], Optional[Any], Optional[Any]) -> Dict[str, Any]
526+
# type: (Self, Optional[Any], Optional[Any], Optional[Any]) -> Dict[str, Any]
536527
raise NotImplementedError()
537528

538529
def _in_no_proxy(self, parsed_dsn):
539-
# type: (Dsn) -> bool
530+
# type: (Self, Dsn) -> bool
540531
no_proxy = getproxies().get("no")
541532
if not no_proxy:
542533
return False
@@ -566,7 +557,7 @@ def _request(
566557
body,
567558
headers,
568559
):
569-
# type: (str, EndpointType, Any, Mapping[str, str]) -> Union[urllib3.BaseHTTPResponse, httpcore.Response]
560+
# type: (Self, str, EndpointType, Any, Mapping[str, str]) -> Union[urllib3.BaseHTTPResponse, httpcore.Response]
570561
raise NotImplementedError()
571562

572563
def capture_envelope(
@@ -586,18 +577,18 @@ def send_envelope_wrapper():
586577

587578
def flush(
588579
self,
589-
timeout, # type: float
590-
callback=None, # type: Optional[Any]
580+
timeout,
581+
callback=None,
591582
):
592-
# type: (...) -> None
583+
# type: (Self, float, Optional[Callable]) -> None
593584
logger.debug("Flushing HTTP transport")
594585

595586
if timeout > 0:
596587
self._worker.submit(lambda: self._flush_client_reports(force=True))
597588
self._worker.flush(timeout, callback)
598589

599590
def kill(self):
600-
# type: () -> None
591+
# type: (Self) -> None
601592
logger.debug("Killing HTTP transport")
602593
self._worker.kill()
603594

@@ -613,14 +604,14 @@ def _warn_hub_cls():
613604

614605
@property
615606
def hub_cls(self):
616-
# type: () -> type[sentry_sdk.Hub]
607+
# type: (Self) -> type[sentry_sdk.Hub]
617608
"""DEPRECATED: This attribute is deprecated and will be removed in a future release."""
618609
HttpTransport._warn_hub_cls()
619610
return self._hub_cls
620611

621612
@hub_cls.setter
622613
def hub_cls(self, value):
623-
# type: (type[sentry_sdk.Hub]) -> None
614+
# type: (Self, type[sentry_sdk.Hub]) -> None
624615
"""DEPRECATED: This attribute is deprecated and will be removed in a future release."""
625616
HttpTransport._warn_hub_cls()
626617
self._hub_cls = value
@@ -631,7 +622,7 @@ class HttpTransport(BaseHttpTransport):
631622
_pool: Union[PoolManager, ProxyManager]
632623

633624
def _get_pool_options(self, ca_certs, cert_file=None, key_file=None):
634-
# type: (Optional[Any], Optional[Any], Optional[Any]) -> Dict[str, Any]
625+
# type: (Self, Any, Any, Any) -> Dict[str, Any]
635626

636627
num_pools = self.options.get("_experiments", {}).get("transport_num_pools")
637628
options = {
@@ -673,9 +664,9 @@ def _make_pool(
673664
parsed_dsn, # type: Dsn
674665
http_proxy, # type: Optional[str]
675666
https_proxy, # type: Optional[str]
676-
ca_certs, # type: Optional[Any]
677-
cert_file, # type: Optional[Any]
678-
key_file, # type: Optional[Any]
667+
ca_certs, # type: Any
668+
cert_file, # type: Any
669+
key_file, # type: Any
679670
proxy_headers, # type: Optional[Dict[str, str]]
680671
):
681672
# type: (...) -> Union[PoolManager, ProxyManager]
@@ -724,7 +715,7 @@ def _request(
724715
body,
725716
headers,
726717
):
727-
# type: (str, EndpointType, Any, Mapping[str, str]) -> urllib3.BaseHTTPResponse
718+
# type: (Self, str, EndpointType, Any, Mapping[str, str]) -> urllib3.BaseHTTPResponse
728719
return self._pool.request(
729720
method,
730721
self._auth.get_api_url(endpoint_type),
@@ -738,10 +729,8 @@ def _request(
738729
except ImportError:
739730
# Sorry, no Http2Transport for you
740731
class Http2Transport(HttpTransport):
741-
def __init__(
742-
self, options # type: Dict[str, Any]
743-
):
744-
# type: (...) -> None
732+
def __init__(self, options):
733+
# type: (Self, Dict[str, Any]) -> None
745734
super().__init__(options)
746735
logger.warning(
747736
"You tried to use HTTP2Transport but don't have httpcore[http2] installed. Falling back to HTTPTransport."
@@ -758,7 +747,7 @@ class Http2Transport(BaseHttpTransport): # type: ignore
758747
]
759748

760749
def _get_header_value(self, response, header):
761-
# type: (httpcore.Response, str) -> Optional[str]
750+
# type: (Self, httpcore.Response, str) -> Optional[str]
762751
return next(
763752
(
764753
val.decode("ascii")
@@ -775,7 +764,7 @@ def _request(
775764
body,
776765
headers,
777766
):
778-
# type: (str, EndpointType, Any, Mapping[str, str]) -> httpcore.Response
767+
# type: (Self, str, EndpointType, Any, Mapping[str, str]) -> httpcore.Response
779768
response = self._pool.request(
780769
method,
781770
self._auth.get_api_url(endpoint_type),
@@ -785,7 +774,7 @@ def _request(
785774
return response
786775

787776
def _get_pool_options(self, ca_certs, cert_file=None, key_file=None):
788-
# type: (Optional[Any], Optional[Any], Optional[Any]) -> Dict[str, Any]
777+
# type: (Any, Any, Any) -> Dict[str, Any]
789778
options = {
790779
"http2": True,
791780
"retries": 3,
@@ -825,9 +814,9 @@ def _make_pool(
825814
parsed_dsn, # type: Dsn
826815
http_proxy, # type: Optional[str]
827816
https_proxy, # type: Optional[str]
828-
ca_certs, # type: Optional[Any]
829-
cert_file, # type: Optional[Any]
830-
key_file, # type: Optional[Any]
817+
ca_certs, # type: Any
818+
cert_file, # type: Any
819+
key_file, # type: Any
831820
proxy_headers, # type: Optional[Dict[str, str]]
832821
):
833822
# type: (...) -> Union[httpcore.SOCKSProxy, httpcore.HTTPProxy, httpcore.ConnectionPool]

0 commit comments

Comments
 (0)