-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfrastructure.py
More file actions
282 lines (218 loc) · 7.57 KB
/
infrastructure.py
File metadata and controls
282 lines (218 loc) · 7.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""
Infrastructure Abstractions
=============================
Interfaces and in-memory implementations for:
- Pagination (cursor / offset-based)
- Distributed Lock (in-process default, Redis-ready interface)
- Response Cache (in-memory LRU with TTL, Redis-ready interface)
- Enhanced Event Dispatcher (async-capable, multi-server-ready interface)
"""
import asyncio
import hashlib
import threading
import time
from abc import ABC, abstractmethod
from collections import OrderedDict
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
from matchmaker.domain.events import DomainEvent
@dataclass
class Page:
"""A page of results."""
items: list[Any]
total: int
page: int
page_size: int
has_next: bool
has_prev: bool
@property
def total_pages(self) -> int:
return max(1, (self.total + self.page_size - 1) // self.page_size)
class Paginator:
"""Utility to paginate any list."""
@staticmethod
def paginate(
items: list[Any],
page: int = 1,
page_size: int = 20,
) -> Page:
"""Return a Page slice from a list.
Args:
items: Full list of items
page: 1-indexed page number
page_size: Number of items per page
"""
total = len(items)
start = (page - 1) * page_size
end = start + page_size
sliced = items[start:end]
return Page(
items=sliced,
total=total,
page=page,
page_size=page_size,
has_next=end < total,
has_prev=page > 1,
)
@staticmethod
def sql_offset_limit(page: int, page_size: int) -> tuple[int, int]:
"""Return (offset, limit) for SQL queries."""
offset = (max(1, page) - 1) * page_size
return (offset, page_size)
class IDistributedLock(ABC):
"""Interface for distributed locking.
Implementations:
- InProcessLock (default — single-instance)
- Future: RedisLock (multi-instance, requires redis-py)
"""
@abstractmethod
def acquire(self, key: str, ttl_seconds: int = 30) -> bool:
"""Acquire a lock. Returns True if acquired."""
...
@abstractmethod
def release(self, key: str) -> None:
"""Release a previously acquired lock."""
...
@abstractmethod
def is_locked(self, key: str) -> bool:
"""Check if a key is currently locked."""
...
class InProcessLock(IDistributedLock):
"""Thread-safe in-process lock (not distributed, but API-compatible).
Use this as the default implementation when running a single instance.
Swap to RedisLock when scaling to multiple instances.
"""
def __init__(self):
self._locks: dict[str, float] = {}
self._mutex = threading.Lock()
def acquire(self, key: str, ttl_seconds: int = 30) -> bool:
with self._mutex:
now = time.time()
if key in self._locks and self._locks[key] > now:
return False
self._locks[key] = now + ttl_seconds
return True
def release(self, key: str) -> None:
with self._mutex:
self._locks.pop(key, None)
def is_locked(self, key: str) -> bool:
with self._mutex:
expiry = self._locks.get(key, 0)
if expiry > time.time():
return True
self._locks.pop(key, None)
return False
class ICache(ABC):
"""Interface for response caching.
Implementations:
- InMemoryCache (default — LRU with TTL)
- Future: RedisCache
"""
@abstractmethod
def get(self, key: str) -> Any | None:
"""Get a cached value. Returns None on miss."""
...
@abstractmethod
def set(self, key: str, value: Any, ttl_seconds: int = 60) -> None:
"""Set a cached value with TTL."""
...
@abstractmethod
def delete(self, key: str) -> None:
"""Delete a cached value."""
...
@abstractmethod
def clear(self) -> None:
"""Clear all cached values."""
...
@dataclass
class _CacheEntry:
value: Any
expires_at: float
class InMemoryCache(ICache):
"""LRU cache with per-entry TTL.
Thread-safe. Suitable for single-instance deployments.
"""
def __init__(self, max_size: int = 512):
self._max_size = max_size
self._store: OrderedDict[str, _CacheEntry] = OrderedDict()
self._mutex = threading.Lock()
def get(self, key: str) -> Any | None:
with self._mutex:
entry = self._store.get(key)
if entry is None:
return None
if time.time() > entry.expires_at:
self._store.pop(key, None)
return None
self._store.move_to_end(key)
return entry.value
def set(self, key: str, value: Any, ttl_seconds: int = 60) -> None:
with self._mutex:
self._store[key] = _CacheEntry(
value=value, expires_at=time.time() + ttl_seconds
)
self._store.move_to_end(key)
while len(self._store) > self._max_size:
self._store.popitem(last=False)
def delete(self, key: str) -> None:
with self._mutex:
self._store.pop(key, None)
def clear(self) -> None:
with self._mutex:
self._store.clear()
def cache_key(*parts: Any) -> str:
"""Generate a deterministic cache key from parts."""
raw = "|".join(str(p) for p in parts)
return hashlib.sha256(raw.encode()).hexdigest()[:16]
class IAsyncEventDispatcher(ABC):
"""Async-capable event dispatcher interface.
Supports:
- Sync handlers (fire-and-forget in a thread)
- Async handlers (awaited on the event loop)
- Subscriber patterns (subscribe to specific event types or all)
"""
@abstractmethod
def subscribe(
self,
event_type: type[DomainEvent],
handler: Callable[[DomainEvent], Any],
) -> None: ...
@abstractmethod
def subscribe_all(self, handler: Callable[[DomainEvent], Any]) -> None: ...
@abstractmethod
def dispatch(self, event: DomainEvent) -> None:
"""Fire-and-forget dispatch (sync or async internally)."""
...
class EnhancedEventDispatcher(IAsyncEventDispatcher):
"""In-process dispatcher with optional async support.
When an asyncio event loop is running, async handlers are scheduled
on it. Otherwise, all handlers are called synchronously.
For multi-server deployment, replace this with an adapter that
publishes to Redis Pub/Sub, RabbitMQ, or similar.
"""
def __init__(self):
self._handlers: dict[type, list[Callable]] = {}
self._global_handlers: list[Callable] = []
def subscribe(
self,
event_type: type[DomainEvent],
handler: Callable[[DomainEvent], Any],
) -> None:
self._handlers.setdefault(event_type, []).append(handler)
def subscribe_all(self, handler: Callable[[DomainEvent], Any]) -> None:
self._global_handlers.append(handler)
def dispatch(self, event: DomainEvent) -> None:
handlers = list(self._global_handlers)
handlers.extend(self._handlers.get(type(event), []))
for handler in handlers:
try:
result = handler(event)
if asyncio.iscoroutine(result):
try:
loop = asyncio.get_running_loop()
loop.create_task(result)
except RuntimeError:
asyncio.run(result)
except Exception:
pass