Просмотр исходного кода

ref: remove calls to to_timestamp (#66711)

`.timestamp()` has existed on `datetime.datetime` since python 3.3 \o/

<!-- Describe your PR here. -->
anthony sottile 1 год назад
Родитель
Сommit
7f64a46060

+ 2 - 2
src/sentry/analytics/__init__.py

@@ -20,8 +20,8 @@ __all__ = (
 
 
 backend = LazyServiceWrapper(
 backend = LazyServiceWrapper(
     backend_base=Analytics,
     backend_base=Analytics,
-    backend_path=get_backend_path(options.get("analytics.backend")),
-    options=options.get("analytics.options"),
+    backend_path=get_backend_path(options.get("analytics.backend")),  # type: ignore[has-type]  # mypy is confused by a circular import
+    options=options.get("analytics.options"),  # type: ignore[has-type]  # mypy is confused by a circular import
 )
 )
 
 
 record = backend.record
 record = backend.record

+ 1 - 2
src/sentry/analytics/event.py

@@ -10,7 +10,6 @@ from django.utils import timezone
 
 
 from sentry.analytics.attribute import Attribute
 from sentry.analytics.attribute import Attribute
 from sentry.analytics.utils import get_data
 from sentry.analytics.utils import get_data
-from sentry.utils.dates import to_timestamp
 
 
 
 
 class Event:
 class Event:
@@ -46,7 +45,7 @@ class Event:
     def serialize(self) -> Mapping[str, Any]:
     def serialize(self) -> Mapping[str, Any]:
         return {
         return {
             "uuid": b64encode(self.uuid.bytes),
             "uuid": b64encode(self.uuid.bytes),
-            "timestamp": to_timestamp(self.datetime),
+            "timestamp": self.datetime.timestamp(),
             "type": self.type,
             "type": self.type,
             "data": self.data,
             "data": self.data,
         }
         }

+ 2 - 3
src/sentry/api/endpoints/project_create_sample_transaction.py

@@ -13,7 +13,6 @@ from sentry.api.bases.project import ProjectEndpoint, ProjectEventPermission
 from sentry.api.serializers import serialize
 from sentry.api.serializers import serialize
 from sentry.constants import DATA_ROOT
 from sentry.constants import DATA_ROOT
 from sentry.utils import json
 from sentry.utils import json
-from sentry.utils.dates import to_timestamp
 from sentry.utils.samples import create_sample_event_basic
 from sentry.utils.samples import create_sample_event_basic
 
 
 base_platforms_with_transactions = ["javascript", "python", "apple-ios"]
 base_platforms_with_transactions = ["javascript", "python", "apple-ios"]
@@ -38,10 +37,10 @@ def fix_event_data(data):
     """
     """
     timestamp = datetime.now(timezone.utc) - timedelta(minutes=1)
     timestamp = datetime.now(timezone.utc) - timedelta(minutes=1)
     timestamp = timestamp - timedelta(microseconds=timestamp.microsecond % 1000)
     timestamp = timestamp - timedelta(microseconds=timestamp.microsecond % 1000)
-    data["timestamp"] = to_timestamp(timestamp)
+    data["timestamp"] = timestamp.timestamp()
 
 
     start_timestamp = timestamp - timedelta(seconds=3)
     start_timestamp = timestamp - timedelta(seconds=3)
-    data["start_timestamp"] = to_timestamp(start_timestamp)
+    data["start_timestamp"] = start_timestamp.timestamp()
 
 
     trace = uuid4().hex
     trace = uuid4().hex
     span_id = uuid4().hex[:16]
     span_id = uuid4().hex[:16]

+ 4 - 6
src/sentry/api/serializers/snuba.py

@@ -1,7 +1,5 @@
 import itertools
 import itertools
 
 
-from sentry.utils.dates import to_timestamp
-
 
 
 def value_from_row(row, tagkey):
 def value_from_row(row, tagkey):
     return tuple(row[k] for k in tagkey)
     return tuple(row[k] for k in tagkey)
@@ -11,8 +9,8 @@ def zerofill(data, start, end, rollup, allow_partial_buckets=False, fill_default
     if fill_default is None:
     if fill_default is None:
         fill_default = []
         fill_default = []
     rv = []
     rv = []
-    end = int(to_timestamp(end))
-    rollup_start = (int(to_timestamp(start)) // rollup) * rollup
+    end = int(end.timestamp())
+    rollup_start = (int(start.timestamp()) // rollup) * rollup
     rollup_end = (end // rollup) * rollup
     rollup_end = (end // rollup) * rollup
 
 
     # Fudge the end value when we're only getting a single window.
     # Fudge the end value when we're only getting a single window.
@@ -45,8 +43,8 @@ def zerofill(data, start, end, rollup, allow_partial_buckets=False, fill_default
 
 
 
 
 def calculate_time_frame(start, end, rollup):
 def calculate_time_frame(start, end, rollup):
-    rollup_start = (int(to_timestamp(start)) // rollup) * rollup
-    rollup_end = (int(to_timestamp(end)) // rollup) * rollup
+    rollup_start = (int(start.timestamp()) // rollup) * rollup
+    rollup_end = (int(end.timestamp()) // rollup) * rollup
     if rollup_end - rollup_start == rollup:
     if rollup_end - rollup_start == rollup:
         rollup_end += 1
         rollup_end += 1
     return {"start": rollup_start, "end": rollup_end}
     return {"start": rollup_start, "end": rollup_end}

+ 1 - 2
src/sentry/digests/notifications.py

@@ -15,7 +15,6 @@ from sentry.models.project import Project
 from sentry.models.rule import Rule
 from sentry.models.rule import Rule
 from sentry.notifications.types import ActionTargetType, FallthroughChoiceType
 from sentry.notifications.types import ActionTargetType, FallthroughChoiceType
 from sentry.tsdb.base import TSDBModel
 from sentry.tsdb.base import TSDBModel
-from sentry.utils.dates import to_timestamp
 from sentry.utils.pipeline import Pipeline
 from sentry.utils.pipeline import Pipeline
 
 
 logger = logging.getLogger("sentry.digests")
 logger = logging.getLogger("sentry.digests")
@@ -71,7 +70,7 @@ def event_to_record(
     return Record(
     return Record(
         event.event_id,
         event.event_id,
         Notification(event, [rule.id for rule in rules], notification_uuid),
         Notification(event, [rule.id for rule in rules], notification_uuid),
-        to_timestamp(event.datetime),
+        event.datetime.timestamp(),
     )
     )
 
 
 
 

+ 2 - 2
src/sentry/event_manager.py

@@ -118,7 +118,7 @@ from sentry.usage_accountant import record
 from sentry.utils import json, metrics
 from sentry.utils import json, metrics
 from sentry.utils.cache import cache_key_for_event
 from sentry.utils.cache import cache_key_for_event
 from sentry.utils.canonical import CanonicalKeyDict
 from sentry.utils.canonical import CanonicalKeyDict
-from sentry.utils.dates import to_datetime, to_timestamp
+from sentry.utils.dates import to_datetime
 from sentry.utils.event import has_event_minified_stack_trace, has_stacktrace, is_handled
 from sentry.utils.event import has_event_minified_stack_trace, has_stacktrace, is_handled
 from sentry.utils.eventuser import EventUser
 from sentry.utils.eventuser import EventUser
 from sentry.utils.metrics import MutableTags
 from sentry.utils.metrics import MutableTags
@@ -292,7 +292,7 @@ class ScoreClause(Func):
         if has_values:
         if has_values:
             sql = "log(times_seen + %d) * 600 + %d" % (
             sql = "log(times_seen + %d) * 600 + %d" % (
                 self.times_seen,
                 self.times_seen,
-                to_timestamp(self.last_seen),
+                self.last_seen.timestamp(),
             )
             )
         else:
         else:
             sql = "log(times_seen) * 600 + last_seen::abstime::int"
             sql = "log(times_seen) * 600 + last_seen::abstime::int"

+ 3 - 6
src/sentry/eventstore/reprocessing/redis.py

@@ -7,7 +7,7 @@ import redis
 from django.conf import settings
 from django.conf import settings
 
 
 from sentry.utils import json
 from sentry.utils import json
-from sentry.utils.dates import to_datetime, to_timestamp
+from sentry.utils.dates import to_datetime
 from sentry.utils.redis import redis_clusters
 from sentry.utils.redis import redis_clusters
 
 
 from .base import ReprocessingStore
 from .base import ReprocessingStore
@@ -99,7 +99,7 @@ class RedisReprocessingStore(ReprocessingStore):
         old_primary_hash: str,
         old_primary_hash: str,
     ) -> None:
     ) -> None:
         event_key = _get_old_primary_hash_subset_key(project_id, group_id, old_primary_hash)
         event_key = _get_old_primary_hash_subset_key(project_id, group_id, old_primary_hash)
-        self.redis.lpush(event_key, f"{to_timestamp(date_val)};{event_id}")
+        self.redis.lpush(event_key, f"{date_val.timestamp()};{event_id}")
         self.redis.expire(event_key, settings.SENTRY_REPROCESSING_TOMBSTONES_TTL)
         self.redis.expire(event_key, settings.SENTRY_REPROCESSING_TOMBSTONES_TTL)
 
 
     def add_hash(self, project_id: int, group_id: int, hash: str) -> None:
     def add_hash(self, project_id: int, group_id: int, hash: str) -> None:
@@ -118,10 +118,7 @@ class RedisReprocessingStore(ReprocessingStore):
         if datetime_to_event:
         if datetime_to_event:
             llen = self.redis.lpush(
             llen = self.redis.lpush(
                 key,
                 key,
-                *(
-                    f"{to_timestamp(datetime)};{event_id}"
-                    for datetime, event_id in datetime_to_event
-                ),
+                *(f"{datetime.timestamp()};{event_id}" for datetime, event_id in datetime_to_event),
             )
             )
             self.redis.expire(key, settings.SENTRY_REPROCESSING_SYNC_TTL)
             self.redis.expire(key, settings.SENTRY_REPROCESSING_SYNC_TTL)
         else:
         else:

+ 2 - 2
src/sentry/incidents/subscription_processor.py

@@ -51,7 +51,7 @@ from sentry.snuba.entity_subscription import (
 from sentry.snuba.models import QuerySubscription
 from sentry.snuba.models import QuerySubscription
 from sentry.snuba.tasks import build_query_builder
 from sentry.snuba.tasks import build_query_builder
 from sentry.utils import metrics, redis
 from sentry.utils import metrics, redis
-from sentry.utils.dates import to_datetime, to_timestamp
+from sentry.utils.dates import to_datetime
 
 
 logger = logging.getLogger(__name__)
 logger = logging.getLogger(__name__)
 REDIS_TTL = int(timedelta(days=7).total_seconds())
 REDIS_TTL = int(timedelta(days=7).total_seconds())
@@ -898,7 +898,7 @@ def update_alert_rule_stats(
             )
             )
 
 
     last_update_key = build_alert_rule_stat_keys(alert_rule, subscription)[0]
     last_update_key = build_alert_rule_stat_keys(alert_rule, subscription)[0]
-    pipeline.set(last_update_key, int(to_timestamp(last_update)), ex=REDIS_TTL)
+    pipeline.set(last_update_key, int(last_update.timestamp()), ex=REDIS_TTL)
     pipeline.execute()
     pipeline.execute()
 
 
 
 

+ 1 - 2
src/sentry/integrations/message_builder.py

@@ -16,7 +16,6 @@ from sentry.notifications.notifications.base import BaseNotification
 from sentry.notifications.notifications.rules import AlertRuleNotification
 from sentry.notifications.notifications.rules import AlertRuleNotification
 from sentry.services.hybrid_cloud.user import RpcUser
 from sentry.services.hybrid_cloud.user import RpcUser
 from sentry.types.integrations import EXTERNAL_PROVIDERS, ExternalProviders
 from sentry.types.integrations import EXTERNAL_PROVIDERS, ExternalProviders
-from sentry.utils.dates import to_timestamp
 from sentry.utils.http import absolute_uri
 from sentry.utils.http import absolute_uri
 
 
 
 
@@ -204,7 +203,7 @@ def build_footer(
 
 
 def get_timestamp(group: Group, event: GroupEvent | None) -> float:
 def get_timestamp(group: Group, event: GroupEvent | None) -> float:
     ts = group.last_seen
     ts = group.last_seen
-    return to_timestamp(max(ts, event.datetime) if event else ts)
+    return (max(ts, event.datetime) if event else ts).timestamp()
 
 
 
 
 def get_color(
 def get_color(

+ 1 - 2
src/sentry/integrations/slack/message_builder/base/block.py

@@ -8,7 +8,6 @@ from typing import Any, TypedDict
 from sentry.integrations.slack.message_builder import SlackBlock
 from sentry.integrations.slack.message_builder import SlackBlock
 from sentry.integrations.slack.message_builder.base.base import SlackMessageBuilder
 from sentry.integrations.slack.message_builder.base.base import SlackMessageBuilder
 from sentry.notifications.utils.actions import MessageAction
 from sentry.notifications.utils.actions import MessageAction
-from sentry.utils.dates import to_timestamp
 
 
 MAX_BLOCK_TEXT_LENGTH = 256
 MAX_BLOCK_TEXT_LENGTH = 256
 
 
@@ -146,7 +145,7 @@ class BlockSlackMessageBuilder(SlackMessageBuilder, ABC):
     def get_context_block(text: str, timestamp: datetime | None = None) -> SlackBlock:
     def get_context_block(text: str, timestamp: datetime | None = None) -> SlackBlock:
         if timestamp:
         if timestamp:
             time = "<!date^{:.0f}^{} at {} | Sentry Issue>".format(
             time = "<!date^{:.0f}^{} at {} | Sentry Issue>".format(
-                to_timestamp(timestamp), "{date_pretty}", "{time}"
+                timestamp.timestamp(), "{date_pretty}", "{time}"
             )
             )
             text += f" | {time}"
             text += f" | {time}"
 
 

Некоторые файлы не были показаны из-за большого количества измененных файлов