-
Notifications
You must be signed in to change notification settings - Fork 2.6k
MultiDbClient implementation #3696
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vladvildanov
wants to merge
20
commits into
feat/active-active
Choose a base branch
from
vv-multi-db-client
base: feat/active-active
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
ac86280
Added Database, Healthcheck, CircuitBreaker, FailureDetector
vladvildanov 4f4a53c
Added DatabaseSelector, exceptions, refactored existing entities
vladvildanov acc68ef
Added MultiDbConfig
vladvildanov 255bb0e
Added DatabaseConfig
vladvildanov 79db257
Added DatabaseConfig test coverage
vladvildanov 8790db1
Renamed DatabaseSelector into FailoverStrategy
vladvildanov b3ad8da
Added CommandExecutor
vladvildanov 3a1dc9c
Updated healthcheck to close circuit on success
vladvildanov 9bb9235
Added thread-safeness
vladvildanov 3218e36
Added missing thread-safeness
vladvildanov 4cdb6f4
Added missing thread-safenes for dispatcher
vladvildanov 6914467
Refactored client to keep databases in WeightedList
vladvildanov 5b94757
Added database CRUD operations
vladvildanov daba501
Added on-fly configuration
vladvildanov 061e518
Added background health checks
vladvildanov a562774
Added background healthcheck + half-open event
vladvildanov 3ab1367
Refactored background scheduling
vladvildanov 3a55dcd
Merge branch 'feat/active-active' of github.com:redis/redis-py into v…
vladvildanov badef0e
Refactored healthchecks
vladvildanov fcc6035
Removed code repetitions, fixed weight assignment, added loops enhanc…
vladvildanov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
import asyncio | ||
import threading | ||
from typing import Callable | ||
|
||
class BackgroundScheduler: | ||
""" | ||
Schedules background tasks execution either in separate thread or in the running event loop. | ||
""" | ||
def __init__(self): | ||
self._next_timer = None | ||
|
||
def __del__(self): | ||
if self._next_timer: | ||
self._next_timer.cancel() | ||
|
||
def run_once(self, delay: float, callback: Callable, *args): | ||
""" | ||
Runs callable task once after certain delay in seconds. | ||
""" | ||
# Run loop in a separate thread to unblock main thread. | ||
loop = asyncio.new_event_loop() | ||
thread = threading.Thread( | ||
target=_start_event_loop_in_thread, | ||
args=(loop, self._call_later, delay, callback, *args), | ||
daemon=True | ||
) | ||
thread.start() | ||
|
||
def run_recurring( | ||
self, | ||
interval: float, | ||
callback: Callable, | ||
*args | ||
): | ||
""" | ||
Runs recurring callable task with given interval in seconds. | ||
""" | ||
# Run loop in a separate thread to unblock main thread. | ||
loop = asyncio.new_event_loop() | ||
|
||
thread = threading.Thread( | ||
target=_start_event_loop_in_thread, | ||
args=(loop, self._call_later_recurring, interval, callback, *args), | ||
daemon=True | ||
) | ||
thread.start() | ||
|
||
def _call_later(self, loop: asyncio.AbstractEventLoop, delay: float, callback: Callable, *args): | ||
self._next_timer = loop.call_later(delay, callback, *args) | ||
|
||
def _call_later_recurring( | ||
self, | ||
loop: asyncio.AbstractEventLoop, | ||
interval: float, | ||
callback: Callable, | ||
*args | ||
): | ||
self._call_later( | ||
loop, interval, self._execute_recurring, loop, interval, callback, *args | ||
) | ||
|
||
def _execute_recurring( | ||
self, | ||
loop: asyncio.AbstractEventLoop, | ||
interval: float, | ||
callback: Callable, | ||
*args | ||
): | ||
""" | ||
Executes recurring callable task with given interval in seconds. | ||
""" | ||
callback(*args) | ||
|
||
self._call_later( | ||
loop, interval, self._execute_recurring, loop, interval, callback, *args | ||
) | ||
|
||
|
||
def _start_event_loop_in_thread(event_loop: asyncio.AbstractEventLoop, call_soon_cb: Callable, *args): | ||
""" | ||
Starts event loop in a thread and schedule callback as soon as event loop is ready. | ||
Used to be able to schedule tasks using loop.call_later. | ||
|
||
:param event_loop: | ||
:return: | ||
""" | ||
asyncio.set_event_loop(event_loop) | ||
event_loop.call_soon(call_soon_cb, event_loop, *args) | ||
event_loop.run_forever() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
import threading | ||
from typing import List, Any, TypeVar, Generic, Union | ||
|
||
from redis.typing import Number | ||
|
||
T = TypeVar('T') | ||
|
||
class WeightedList(Generic[T]): | ||
""" | ||
Thread-safe weighted list. | ||
""" | ||
def __init__(self): | ||
self._items: List[tuple[Any, Number]] = [] | ||
self._lock = threading.RLock() | ||
|
||
def add(self, item: Any, weight: float) -> None: | ||
"""Add item with weight, maintaining sorted order""" | ||
with self._lock: | ||
# Find insertion point using binary search | ||
left, right = 0, len(self._items) | ||
while left < right: | ||
mid = (left + right) // 2 | ||
if self._items[mid][1] < weight: | ||
right = mid | ||
else: | ||
left = mid + 1 | ||
|
||
self._items.insert(left, (item, weight)) | ||
|
||
def remove(self, item): | ||
"""Remove first occurrence of item""" | ||
with self._lock: | ||
for i, (stored_item, weight) in enumerate(self._items): | ||
if stored_item == item: | ||
self._items.pop(i) | ||
return weight | ||
raise ValueError("Item not found") | ||
|
||
def get_by_weight_range(self, min_weight: float, max_weight: float) -> List[tuple[Any, Number]]: | ||
"""Get all items within weight range""" | ||
with self._lock: | ||
result = [] | ||
for item, weight in self._items: | ||
if min_weight <= weight <= max_weight: | ||
result.append((item, weight)) | ||
return result | ||
|
||
def get_top_n(self, n: int) -> List[tuple[Any, Number]]: | ||
"""Get top N the highest weighted items""" | ||
with self._lock: | ||
return [(item, weight) for item, weight in self._items[:n]] | ||
|
||
def update_weight(self, item, new_weight: float): | ||
with self._lock: | ||
"""Update weight of an item""" | ||
old_weight = self.remove(item) | ||
vladvildanov marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.add(item, new_weight) | ||
return old_weight | ||
|
||
def __iter__(self): | ||
"""Iterate in descending weight order""" | ||
with self._lock: | ||
items_copy = self._items.copy() # Create snapshot as lock released after each 'yield' | ||
|
||
for item, weight in items_copy: | ||
yield item, weight | ||
|
||
def __len__(self): | ||
with self._lock: | ||
return len(self._items) | ||
|
||
def __getitem__(self, index) -> tuple[Any, Number]: | ||
with self._lock: | ||
item, weight = self._items[index] | ||
return item, weight |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.