reach_commons 0.18.35__py3-none-any.whl → 0.18.37__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,17 @@
1
- import logging
2
- import os
3
-
4
-
5
- def init_logger(name: str):
6
- logging.basicConfig(
7
- level=getattr(logging, os.getenv("LOG_LEVEL", "INFO").upper(), logging.INFO),
8
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
9
- force=True,
10
- )
11
- for noisy in ("botocore", "boto3", "urllib3"):
12
- logging.getLogger(noisy).setLevel(logging.WARNING)
13
- return logging.getLogger(name)
14
-
15
-
16
- def log_with_event(level_fn, msg, event):
17
- level_fn(f"{msg} | event={event}")
1
+ import logging
2
+ import os
3
+
4
+
5
+ def init_logger(name: str):
6
+ logging.basicConfig(
7
+ level=getattr(logging, os.getenv("LOG_LEVEL", "INFO").upper(), logging.INFO),
8
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
9
+ force=True,
10
+ )
11
+ for noisy in ("botocore", "boto3", "urllib3"):
12
+ logging.getLogger(noisy).setLevel(logging.WARNING)
13
+ return logging.getLogger(name)
14
+
15
+
16
+ def log_with_event(level_fn, msg, event):
17
+ level_fn(f"{msg} | event={event}")
@@ -0,0 +1,228 @@
1
+ import random
2
+ import time
3
+ from dataclasses import dataclass
4
+ from typing import Optional, Tuple
5
+
6
+ from reach_commons.redis_manager import RedisManager
7
+
8
+ # Atomic fixed-window limiter (safe under high concurrency).
9
+ _LUA_WINDOW_LIMITER = """
10
+ -- KEYS[1] = window_counter_key
11
+ -- ARGV[1] = tokens_to_consume
12
+ -- ARGV[2] = ttl_seconds
13
+ -- ARGV[3] = limit_per_window
14
+
15
+ local tokens = tonumber(ARGV[1])
16
+ local ttl = tonumber(ARGV[2])
17
+ local limit = tonumber(ARGV[3])
18
+
19
+ local current = redis.call('INCRBY', KEYS[1], tokens)
20
+
21
+ -- If this is the first increment for this window, set TTL
22
+ if current == tokens then
23
+ redis.call('EXPIRE', KEYS[1], ttl)
24
+ end
25
+
26
+ if current <= limit then
27
+ return 1
28
+ else
29
+ return 0
30
+ end
31
+ """
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class AcquireResult:
36
+ allowed: bool
37
+ retry_after_seconds: int
38
+
39
+
40
+ class ReachRateLimiter:
41
+ """
42
+ ReachRateLimiter (fixed-window limiter) backed by Redis.
43
+
44
+ Configurable live via Redis (no redeploy needed).
45
+ Atomic under heavy concurrency (Lua runs inside Redis).
46
+ Returns retry_after_seconds (use it to ChangeMessageVisibility / Delay).
47
+
48
+ Redis keys used:
49
+ - Config hash:
50
+ {key_prefix}:cfg:{bucket_key}
51
+ Fields (all optional):
52
+ - limit_per_window (int)
53
+ - interval_seconds (int)
54
+ - jitter_seconds (int)
55
+
56
+ - Per-window counter:
57
+ {key_prefix}:{bucket_key}:{window_start}
58
+
59
+ Suggested defaults:
60
+ interval_seconds=2
61
+ limit_per_window=2000 (=> ~1000/s)
62
+ jitter_seconds=2 or 3
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ redis_manager: RedisManager,
68
+ bucket_key: str,
69
+ key_prefix: str = "rate_limiter",
70
+ default_limit_per_window: int = 2000,
71
+ default_interval_seconds: int = 2,
72
+ default_jitter_seconds: Optional[int] = None,
73
+ # Cache config in-memory per Lambda container (to reduce Redis reads):
74
+ config_cache_seconds: int = 2,
75
+ # if Redis is down, deny by default to avoid stampede downstream
76
+ deny_on_redis_error: bool = True,
77
+ ):
78
+ self.redis = redis_manager
79
+ self.bucket_key = bucket_key
80
+ self.key_prefix = key_prefix
81
+
82
+ self.default_limit = int(default_limit_per_window)
83
+ self.default_interval = int(default_interval_seconds)
84
+ self.default_jitter = (
85
+ int(default_jitter_seconds)
86
+ if default_jitter_seconds is not None
87
+ else int(default_interval_seconds)
88
+ )
89
+
90
+ self.config_cache_seconds = max(0, int(config_cache_seconds))
91
+ self.deny_on_redis_error = bool(deny_on_redis_error)
92
+
93
+ self._lua = _LUA_WINDOW_LIMITER
94
+
95
+ # Per-container cache (each Lambda container caches for a short time)
96
+ self._cached_cfg: Optional[Tuple[int, int, int]] = None
97
+ self._cached_cfg_ts: float = 0.0
98
+
99
+ # -------------------------
100
+ # Redis key helpers
101
+ # -------------------------
102
+ def _cfg_key(self) -> str:
103
+ return f"{self.key_prefix}:cfg:{self.bucket_key}"
104
+
105
+ def _counter_key(self, window_start: int) -> str:
106
+ return f"{self.key_prefix}:{self.bucket_key}:{window_start}"
107
+
108
+ # -------------------------
109
+ # Time helpers
110
+ # -------------------------
111
+ def _now(self) -> float:
112
+ return time.time()
113
+
114
+ def _window_start(self, now: float, interval_seconds: int) -> int:
115
+ return int(now // interval_seconds) * interval_seconds
116
+
117
+ # -------------------------
118
+ # Config loading (from Redis hash)
119
+ # -------------------------
120
+ @staticmethod
121
+ def _parse_int(value, fallback: int) -> int:
122
+ try:
123
+ if value is None:
124
+ return fallback
125
+ if isinstance(value, (bytes, bytearray)):
126
+ value = value.decode("utf-8", errors="ignore")
127
+ return int(value)
128
+ except Exception:
129
+ return fallback
130
+
131
+ def _load_config(self) -> Tuple[int, int, int]:
132
+ """
133
+ Loads config from Redis hash:
134
+ limit_per_window, interval_seconds, jitter_seconds
135
+
136
+ Uses short in-memory cache to avoid hammering Redis under high throughput.
137
+ """
138
+ now = self._now()
139
+
140
+ if (
141
+ self._cached_cfg is not None
142
+ and self.config_cache_seconds > 0
143
+ and (now - self._cached_cfg_ts) < self.config_cache_seconds
144
+ ):
145
+ return self._cached_cfg
146
+
147
+ limit = self.default_limit
148
+ interval = self.default_interval
149
+ jitter = self.default_jitter
150
+
151
+ try:
152
+ raw = self.redis.hgetall(self._cfg_key()) or {}
153
+
154
+ # raw typically has bytes keys/values
155
+ limit = self._parse_int(
156
+ raw.get(b"limit_per_window") or raw.get("limit_per_window"), limit
157
+ )
158
+ interval = self._parse_int(
159
+ raw.get(b"interval_seconds") or raw.get("interval_seconds"), interval
160
+ )
161
+ jitter = self._parse_int(
162
+ raw.get(b"jitter_seconds") or raw.get("jitter_seconds"), jitter
163
+ )
164
+
165
+ # Guard rails
166
+ if limit <= 0:
167
+ limit = self.default_limit
168
+ if interval <= 0:
169
+ interval = self.default_interval
170
+ if jitter < 0:
171
+ jitter = 0
172
+
173
+ except Exception:
174
+ # Redis issue: keep defaults
175
+ limit = self.default_limit
176
+ interval = self.default_interval
177
+ jitter = self.default_jitter
178
+
179
+ cfg = (int(limit), int(interval), int(jitter))
180
+ self._cached_cfg = cfg
181
+ self._cached_cfg_ts = now
182
+ return cfg
183
+
184
+ # -------------------------
185
+ # Public API
186
+ # -------------------------
187
+ def acquire(self, tokens: int = 1) -> AcquireResult:
188
+ """
189
+ Attempt to acquire tokens (default 1).
190
+ If denied, returns retry_after_seconds.
191
+ """
192
+ tokens = int(tokens)
193
+ if tokens <= 0:
194
+ return AcquireResult(allowed=True, retry_after_seconds=0)
195
+
196
+ now = self._now()
197
+ limit, interval, jitter_max = self._load_config()
198
+
199
+ window_start = self._window_start(now, interval)
200
+ window_end = window_start + interval
201
+ counter_key = self._counter_key(window_start)
202
+
203
+ # TTL slightly larger than interval so old window keys expire
204
+ ttl_seconds = max(interval * 2, 5)
205
+
206
+ try:
207
+ allowed = self.redis.eval(
208
+ self._lua,
209
+ numkeys=1,
210
+ keys=[counter_key],
211
+ args=[str(tokens), str(ttl_seconds), str(limit)],
212
+ )
213
+ except Exception:
214
+ if self.deny_on_redis_error:
215
+ # safest for protecting downstream (Mongo/API)
216
+ retry_after = int(max(1.0, float(interval)))
217
+ return AcquireResult(allowed=False, retry_after_seconds=retry_after)
218
+ return AcquireResult(allowed=True, retry_after_seconds=0)
219
+
220
+ if allowed == 1:
221
+ return AcquireResult(allowed=True, retry_after_seconds=0)
222
+
223
+ # Denied: retry after next window + jitter to avoid waves
224
+ base = max(0.0, window_end - now)
225
+ jitter = random.uniform(0.0, float(jitter_max))
226
+ retry_after = int(max(1.0, base + jitter))
227
+
228
+ return AcquireResult(allowed=False, retry_after_seconds=retry_after)
@@ -80,3 +80,23 @@ class RedisManager:
80
80
  name=key, value="1", ex=expire_seconds, nx=True
81
81
  )
82
82
  return result is True
83
+
84
+ def incrby(self, key: str, amount: int = 1) -> int:
85
+ return int(self.redis_connection.incrby(key, amount))
86
+
87
+ def expire(self, key: str, seconds: int) -> bool:
88
+ return bool(self.redis_connection.expire(key, seconds))
89
+
90
+ def eval(self, script: str, numkeys: int, keys=None, args=None):
91
+ keys = keys or []
92
+ args = args or []
93
+ return self.redis_connection.eval(script, numkeys, *(keys + args))
94
+
95
+ def hgetall(self, key):
96
+ return self.redis_connection.hgetall(key)
97
+
98
+ def hget(self, key, field):
99
+ return self.redis_connection.hget(key, field)
100
+
101
+ def hset(self, key, field, value):
102
+ return self.redis_connection.hset(key, field, value)
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.1
2
2
  Name: reach_commons
3
- Version: 0.18.35
3
+ Version: 0.18.37
4
4
  Summary: Reach Commons is a versatile utility library designed to streamline and enhance development workflows within the Reach ecosystem.
5
5
  License: MIT
6
6
  Author: Engineering
@@ -14,8 +14,6 @@ Classifier: Programming Language :: Python :: 3.9
14
14
  Classifier: Programming Language :: Python :: 3.10
15
15
  Classifier: Programming Language :: Python :: 3.11
16
16
  Classifier: Programming Language :: Python :: 3.12
17
- Classifier: Programming Language :: Python :: 3.13
18
- Classifier: Programming Language :: Python :: 3.14
19
17
  Requires-Dist: curlify (==3.0.0)
20
18
  Requires-Dist: fastapi (>=0.115.5)
21
19
  Requires-Dist: pydantic (>=2.9.2)
@@ -1,12 +1,10 @@
1
- reach_commons/.DS_Store,sha256=M7WbC5LcTvuTEuj3k7z3tqzMSVGgu87auq6UOLoSv2M,6148
2
1
  reach_commons/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
2
  reach_commons/app_logging/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
3
  reach_commons/app_logging/http_logger.py,sha256=mljQCdmsmtD2HsC_gsFwZAxPlAiLPYVirVrCjXFxitY,2541
5
4
  reach_commons/app_logging/log_deprecated_endpoints.py,sha256=yXs9Jh7V0_0cMnzwXV9WRgCdFXe_tybcFE1eQl2KNC4,2020
6
5
  reach_commons/app_logging/logger.py,sha256=Iq2XTl1zLgHDmVsTMdlFadcYJOqQNhBcFSscacKs_Xs,2295
7
6
  reach_commons/app_logging/logging_config.py,sha256=Y1JaZOoQBWgQjkOqYmeDRIm0p2eCOl3yTzgsgqyqm8I,1539
8
- reach_commons/app_logging/logging_utils.py,sha256=zeDRm3DugbuqMIDstTsVyH5xU_ZV-WAcCINxb6qYdJY,491
9
- reach_commons/clients/.DS_Store,sha256=1lFlJ5EFymdzGAUAaI30vcaaLHt3F1LwpG7xILf9jsM,6148
7
+ reach_commons/app_logging/logging_utils.py,sha256=-QQ4l9CTYs-lCL-VNxGdWvPquRQtrnXWqzNfxOLO9ys,508
10
8
  reach_commons/clients/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
9
  reach_commons/clients/event_processor.py,sha256=KmYF0kuZxLmHQjJASXMr5jz2D_D3WNHB0c4QOlZo1_E,2024
12
10
  reach_commons/clients/hubspot.py,sha256=ntAzvwoaq78MkKaVoZ7geND-AafAzccNnJogfJDahVA,5497
@@ -23,13 +21,14 @@ reach_commons/reach_aws/dynamo_db.py,sha256=BL3QcKzx4uZic-Ui12tln_GMSKe297FdfyIz
23
21
  reach_commons/reach_aws/exceptions.py,sha256=x0RL5ktNtzxg0KykhEVWReBq_dEtciK6B2vMs_s4C9k,915
24
22
  reach_commons/reach_aws/firehose.py,sha256=1xFKLWMv3bNo3PPW5gtaL6NqzUDyVil6B768slj2wbY,5674
25
23
  reach_commons/reach_aws/kms.py,sha256=ZOfyJMQUgxJEojRoB7-aCxtATpNx1Ig522IUYH11NZ4,4678
24
+ reach_commons/reach_aws/reach_rate_limiter.py,sha256=Z3gldy_EkkgVVl9rmc3t5xciccNPcRAiBY1stvr7YLw,7448
26
25
  reach_commons/reach_aws/s3.py,sha256=2MLlDNFx0SROJBpE_KjJefyrB7lMqTlrYuRhSZx4iKs,3945
27
26
  reach_commons/reach_aws/sqs.py,sha256=IKKWrd-qbhMMVYUvGbaq1ouVRdx-0u-SqwYaTcp0tWY,21645
28
27
  reach_commons/reach_base_model.py,sha256=vgdGDcZr3iXMmyRhmBhOf_LKWB_6QzT3r_Yiyo6OmEk,3009
29
- reach_commons/redis_manager.py,sha256=SgUtdtt0eV4bUwsWDankIa9Bjfgcm2DKcmVMQT6ptF0,2946
28
+ reach_commons/redis_manager.py,sha256=yRed53ZKlbIb6rZnL53D1F_aB-xWT3nbeUP2cqYzhoc,3668
30
29
  reach_commons/sms_smart_encoding.py,sha256=92y0RmZ0l4ONHpC9qeO5KfViSNq64yE2rc7lhNDSZqE,1241
31
30
  reach_commons/utils.py,sha256=dMgKIGqTgoSItuBI8oz81gKtW3qi21Jkljv9leS_V88,8475
32
31
  reach_commons/validations.py,sha256=x_lkrtlrCAJC_f7mZb19JjfKFbYlPFv-P84K_lbZyYs,1056
33
- reach_commons-0.18.35.dist-info/METADATA,sha256=gD0kZHrRs6H0VzzuUYrxs4EFOju-ubt9hdnB4AdLMLM,1965
34
- reach_commons-0.18.35.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
35
- reach_commons-0.18.35.dist-info/RECORD,,
32
+ reach_commons-0.18.37.dist-info/METADATA,sha256=k2xckMxe857fXHo3p-lUKT0eWFwHmXTumKIqcI5M2GM,1863
33
+ reach_commons-0.18.37.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
34
+ reach_commons-0.18.37.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: poetry-core 2.2.1
2
+ Generator: poetry-core 1.8.1
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
reach_commons/.DS_Store DELETED
Binary file
Binary file