Skip to content

Commit

Permalink
decorator: get rid of inheritance
Browse files Browse the repository at this point in the history
Signed-off-by: Isabella do Amaral <[email protected]>
  • Loading branch information
isinyaaa committed Nov 13, 2024
1 parent 96ebf63 commit 3ea4643
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 45 deletions.
52 changes: 8 additions & 44 deletions oras/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,72 +3,36 @@
__license__ = "Apache-2.0"

import time
from functools import partial, update_wrapper
from functools import wraps

import oras.auth
from oras.logger import logger


class Decorator:
"""
Shared parent decorator class
"""

def __init__(self, func):
update_wrapper(self, func)
self.func = func

def __get__(self, obj, objtype):
return partial(self.__call__, obj)


class ensure_container(Decorator):
def ensure_container(func):
"""
Ensure the first argument is a container, and not a string.
"""

def __call__(self, cls, *args, **kwargs):
@wraps(func)
def wrapper(cls, *args, **kwargs):
if "container" in kwargs:
kwargs["container"] = cls.get_container(kwargs["container"])
elif args:
container = cls.get_container(args[0])
args = (container, *args[1:])
return self.func(cls, *args, **kwargs)


class classretry(Decorator):
"""
Retry a function that is part of a class
"""

def __init__(self, func, attempts=5, timeout=2):
super().__init__(func)
self.attempts = attempts
self.timeout = timeout
return func(cls, *args, **kwargs)

def __call__(self, cls, *args, **kwargs):
attempt = 0
attempts = self.attempts
timeout = self.timeout
while attempt < attempts:
try:
return self.func(cls, *args, **kwargs)
except oras.auth.AuthenticationException as e:
raise e
except Exception as e:
sleep = timeout + 3**attempt
logger.info(f"Retrying in {sleep} seconds - error: {e}")
time.sleep(sleep)
attempt += 1
return self.func(cls, *args, **kwargs)
return wrapper


def retry(attempts, timeout=2):
def retry(attempts=5, timeout=2):
"""
A simple retry decorator
"""

def decorator(func):
@wraps(func)
def inner(*args, **kwargs):
attempt = 0
while attempt < attempts:
Expand Down
2 changes: 1 addition & 1 deletion oras/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -938,7 +938,7 @@ def get_manifest(
jsonschema.validate(manifest, schema=oras.schemas.manifest)
return manifest

@decorator.classretry
@decorator.retry()
def do_request(
self,
url: str,
Expand Down

0 comments on commit 3ea4643

Please sign in to comment.