|
| 1 | +# fastapi-utils が psutil 5.x に依存している問題が1年以上解決されないため、以下のソースコードをそのまま移植した |
| 2 | +# ref: https://github.com/fastapiutils/fastapi-utils/issues/368 |
| 3 | +# ref: https://github.com/fastapiutils/fastapi-utils/blob/master/fastapi_utils/tasks.py |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import asyncio |
| 8 | +import logging |
| 9 | +import warnings |
| 10 | +from collections.abc import Callable, Coroutine |
| 11 | +from functools import wraps |
| 12 | +from traceback import format_exception |
| 13 | +from typing import Any |
| 14 | + |
| 15 | +from starlette.concurrency import run_in_threadpool |
| 16 | + |
| 17 | + |
| 18 | +NoArgsNoReturnFuncT = Callable[[], None] |
| 19 | +NoArgsNoReturnAsyncFuncT = Callable[[], Coroutine[Any, Any, None]] |
| 20 | +ExcArgNoReturnFuncT = Callable[[Exception], None] |
| 21 | +ExcArgNoReturnAsyncFuncT = Callable[[Exception], Coroutine[Any, Any, None]] |
| 22 | +NoArgsNoReturnAnyFuncT = NoArgsNoReturnFuncT | NoArgsNoReturnAsyncFuncT |
| 23 | +ExcArgNoReturnAnyFuncT = ExcArgNoReturnFuncT | ExcArgNoReturnAsyncFuncT |
| 24 | +NoArgsNoReturnDecorator = Callable[[NoArgsNoReturnAnyFuncT], NoArgsNoReturnAsyncFuncT] |
| 25 | + |
| 26 | + |
| 27 | +async def _handle_func(func: NoArgsNoReturnAnyFuncT) -> None: |
| 28 | + if asyncio.iscoroutinefunction(func): |
| 29 | + await func() |
| 30 | + else: |
| 31 | + await run_in_threadpool(func) |
| 32 | + |
| 33 | + |
| 34 | +async def _handle_exc(exc: Exception, on_exception: ExcArgNoReturnAnyFuncT | None) -> None: |
| 35 | + if on_exception: |
| 36 | + if asyncio.iscoroutinefunction(on_exception): |
| 37 | + await on_exception(exc) |
| 38 | + else: |
| 39 | + await run_in_threadpool(on_exception, exc) |
| 40 | + |
| 41 | + |
| 42 | +def repeat_every( |
| 43 | + *, |
| 44 | + seconds: float, |
| 45 | + wait_first: float | None = None, |
| 46 | + logger: logging.Logger | None = None, |
| 47 | + raise_exceptions: bool = False, |
| 48 | + max_repetitions: int | None = None, |
| 49 | + on_complete: NoArgsNoReturnAnyFuncT | None = None, |
| 50 | + on_exception: ExcArgNoReturnAnyFuncT | None = None, |
| 51 | +) -> NoArgsNoReturnDecorator: |
| 52 | + """ |
| 53 | + This function returns a decorator that modifies a function so it is periodically re-executed after its first call. |
| 54 | +
|
| 55 | + The function it decorates should accept no arguments and return nothing. If necessary, this can be accomplished |
| 56 | + by using `functools.partial` or otherwise wrapping the target function prior to decoration. |
| 57 | +
|
| 58 | + Parameters |
| 59 | + ---------- |
| 60 | + seconds: float |
| 61 | + The number of seconds to wait between repeated calls |
| 62 | + wait_first: float (default None) |
| 63 | + If not None, the function will wait for the given duration before the first call |
| 64 | + logger: Optional[logging.Logger] (default None) |
| 65 | + Warning: This parameter is deprecated and will be removed in the 1.0 release. |
| 66 | + The logger to use to log any exceptions raised by calls to the decorated function. |
| 67 | + If not provided, exceptions will not be logged by this function (though they may be handled by the event loop). |
| 68 | + raise_exceptions: bool (default False) |
| 69 | + Warning: This parameter is deprecated and will be removed in the 1.0 release. |
| 70 | + If True, errors raised by the decorated function will be raised to the event loop's exception handler. |
| 71 | + Note that if an error is raised, the repeated execution will stop. |
| 72 | + Otherwise, exceptions are just logged and the execution continues to repeat. |
| 73 | + See https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.set_exception_handler for more info. |
| 74 | + max_repetitions: Optional[int] (default None) |
| 75 | + The maximum number of times to call the repeated function. If `None`, the function is repeated forever. |
| 76 | + on_complete: Optional[Callable[[], None]] (default None) |
| 77 | + A function to call after the final repetition of the decorated function. |
| 78 | + on_exception: Optional[Callable[[Exception], None]] (default None) |
| 79 | + A function to call when an exception is raised by the decorated function. |
| 80 | + """ |
| 81 | + |
| 82 | + def decorator(func: NoArgsNoReturnAnyFuncT) -> NoArgsNoReturnAsyncFuncT: |
| 83 | + """ |
| 84 | + Converts the decorated function into a repeated, periodically-called version of itself. |
| 85 | + """ |
| 86 | + |
| 87 | + @wraps(func) |
| 88 | + async def wrapped() -> None: |
| 89 | + async def loop() -> None: |
| 90 | + if wait_first is not None: |
| 91 | + await asyncio.sleep(wait_first) |
| 92 | + |
| 93 | + repetitions = 0 |
| 94 | + while max_repetitions is None or repetitions < max_repetitions: |
| 95 | + try: |
| 96 | + await _handle_func(func) |
| 97 | + |
| 98 | + except Exception as exc: |
| 99 | + if logger is not None: |
| 100 | + warnings.warn( |
| 101 | + "'logger' is to be deprecated in favor of 'on_exception' in the 1.0 release.", |
| 102 | + DeprecationWarning, |
| 103 | + ) |
| 104 | + formatted_exception = "".join(format_exception(type(exc), exc, exc.__traceback__)) |
| 105 | + logger.error(formatted_exception) |
| 106 | + if raise_exceptions: |
| 107 | + warnings.warn( |
| 108 | + "'raise_exceptions' is to be deprecated in favor of 'on_exception' in the 1.0 release.", |
| 109 | + DeprecationWarning, |
| 110 | + ) |
| 111 | + raise exc |
| 112 | + await _handle_exc(exc, on_exception) |
| 113 | + |
| 114 | + repetitions += 1 |
| 115 | + await asyncio.sleep(seconds) |
| 116 | + |
| 117 | + if on_complete: |
| 118 | + await _handle_func(on_complete) |
| 119 | + |
| 120 | + asyncio.ensure_future(loop()) # noqa: RUF006 |
| 121 | + |
| 122 | + return wrapped |
| 123 | + |
| 124 | + return decorator |
0 commit comments