






















You are given a stream of log events. Each event contains at least:
timestamp: arrival time (assume integer seconds or milliseconds)store_id: storefront identifierevent_type / messageImplement a rate limiter that decides whether each log should be accepted and written downstream.
store_id.window, allow at most limit logs per store_id; extra logs must be rejected.ALLOW/REJECT decision for every input event.(timestamp, store_id) in arrival order, plus window and limit.ALLOW or REJECT per event.window = 10s, limit = 3
1 from collections import deque, defaultdict 2 3 class StorefrontRateLimiter: 4 def __init__(self, window, limit): 5 self.window = window 6 self.limit = limit 7 # Automatically creates a new deque when a store_id is accessed for the first time 8 self.store_history = defaultdict(deque) 9 10 def process_event(self, timestamp, store_id): 11 history = self.store_history[store_id] 12 13 # Cleanup: Remove timestamps outside the sliding window 14 while history and history[0] <= timestamp - self.window: 15 history.popleft() 16 17 # Rate Limit Logic 18 if len(history) < self.limit: 19 history.append(timestamp) 20 return "ALLOW" 21 22 return "REJECT"
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。