Skip to content

Commit

Permalink
core: libs: commonwealth: utils: decorators: Add operation_in_progres…
Browse files Browse the repository at this point in the history
…s_global

Lock all set operations to wait for a set operation to finish

Signed-off-by: Patrick José Pereira <[email protected]>
  • Loading branch information
patrickelectric committed Apr 11, 2024
1 parent 9b7bcef commit 363834d
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions core/libs/commonwealth/commonwealth/utils/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,32 @@ async def wrapper(*args: Any, **kwargs: Any) -> Any:
return wrapper

return inner_function


__commonwealth_operation_in_progress_global_lock = Lock()
def operation_in_progress_global(callback: Callable[[Any], Any]) -> Callable[[Callable[[Any], Any]], Any]:
"""
Decorator to ensure that a function cannot be called in parallel. If the function is
already running, the decorator calls the provided callback function if any and returns its return value.
Args:
callback (Callable[[Any], Any]): Callback to be called when the operation is already in progress.
Returns:
A decorator that wraps the original function.
"""

def inner_function(function: Callable[[Any], Any]) -> Callable[[Callable[[Any], Any]], Any]:
@wraps(function)
async def wrapper(*args: Any, **kwargs: Any) -> Any:
# pylint: disable=consider-using-with
if not __commonwealth_operation_in_progress_global_lock.acquire(blocking=False):
return await callback(*args, **kwargs)
try:
return await function(*args, **kwargs)
finally:
__commonwealth_operation_in_progress_global_lock.release()

return wrapper

return inner_function

0 comments on commit 363834d

Please sign in to comment.