88from django .conf import settings
99from django .db import IntegrityError , router , transaction
1010from django .db .models import Model
11- from redis .client import StrictRedis
1211from rest_framework import status
1312from rest_framework .exceptions import APIException
13+ from sentry_redis_tools .clients import RedisCluster , StrictRedis
1414
1515from sentry .db .postgres .transactions import enforce_constraints
1616from sentry .types .region import RegionContextError , get_local_region
17+ from sentry .utils import redis
1718
1819if TYPE_CHECKING :
1920 from sentry .db .models .base import Model as BaseModel
@@ -139,14 +140,16 @@ def generate_snowflake_id(redis_key: str) -> int:
139140 return snowflake_id
140141
141142
142- def get_redis_cluster (redis_key : str ) -> StrictRedis [str ]:
143- from sentry . utils import redis
143+ def get_redis_cluster () -> RedisCluster [ str ] | StrictRedis [str ]:
144+ return redis . redis_clusters . get ( settings . SENTRY_SNOWFLAKE_REDIS_CLUSTER )
144145
145- return redis .clusters .get ("default" ).get_local_client_for_key (redis_key )
146+
147+ def get_timestamp_redis_key (redis_key : str , timestamp : int ) -> str :
148+ return f"snowflakeid:{ redis_key } :{ str (timestamp )} "
146149
147150
148151def get_sequence_value_from_redis (redis_key : str , starting_timestamp : int ) -> tuple [int , int ]:
149- cluster = get_redis_cluster (redis_key )
152+ cluster = get_redis_cluster ()
150153
151154 # this is the amount we want to lookback for previous timestamps
152155 # the below is more of a safety net if starting_timestamp is ever
@@ -156,14 +159,16 @@ def get_sequence_value_from_redis(redis_key: str, starting_timestamp: int) -> tu
156159 for i in range (time_range ):
157160 timestamp = starting_timestamp - i
158161
162+ timestamp_redis_key = get_timestamp_redis_key (redis_key , timestamp )
163+
159164 # We are decreasing the value by 1 each time since the incr operation in redis
160165 # initializes the counter at 1. For our region sequences, we want the value to
161166 # be from 0-15 and not 1-16
162- sequence_value = cluster .incr (str ( timestamp ) )
167+ sequence_value = cluster .incr (timestamp_redis_key )
163168 sequence_value -= 1
164169
165170 if sequence_value == 0 :
166- cluster .expire (str ( timestamp ) , int (_TTL .total_seconds ()))
171+ cluster .expire (timestamp_redis_key , int (_TTL .total_seconds ()))
167172
168173 if sequence_value < MAX_AVAILABLE_REGION_SEQUENCES :
169174 return timestamp , sequence_value
0 commit comments