|
| 1 | +import inspect |
| 2 | +import logging |
| 3 | +from functools import wraps |
| 4 | +from typing import Callable, Optional |
| 5 | + |
| 6 | +from ray._common.utils import import_attr |
| 7 | +from ray.serve._private.constants import SERVE_LOGGER_NAME |
| 8 | +from ray.serve.schema import TaskProcessorConfig |
| 9 | +from ray.serve.task_processor import TaskProcessorAdapter |
| 10 | +from ray.util.annotations import PublicAPI |
| 11 | + |
| 12 | +logger = logging.getLogger(SERVE_LOGGER_NAME) |
| 13 | + |
| 14 | + |
| 15 | +@PublicAPI(stability="alpha") |
| 16 | +def instantiate_adapter_from_config( |
| 17 | + task_processor_config: TaskProcessorConfig, |
| 18 | +) -> TaskProcessorAdapter: |
| 19 | + """ |
| 20 | + Create a TaskProcessorAdapter instance from the provided configuration and call .initialize(). This function supports two ways to specify an adapter: |
| 21 | +
|
| 22 | + 1. String path: A fully qualified module path to an adapter class |
| 23 | + Example: "ray.serve.task_processor.CeleryTaskProcessorAdapter" |
| 24 | +
|
| 25 | + 2. Class reference: A direct reference to an adapter class |
| 26 | + Example: CeleryTaskProcessorAdapter |
| 27 | +
|
| 28 | + Args: |
| 29 | + task_processor_config: Configuration object containing adapter specification. |
| 30 | +
|
| 31 | + Returns: |
| 32 | + An initialized TaskProcessorAdapter instance ready for use. |
| 33 | +
|
| 34 | + Raises: |
| 35 | + ValueError: If the adapter string path is malformed or cannot be imported. |
| 36 | + TypeError: If the adapter is not a string or callable class. |
| 37 | +
|
| 38 | + Example: |
| 39 | + .. code-block:: python |
| 40 | +
|
| 41 | + config = TaskProcessorConfig( |
| 42 | + adapter="my.module.CustomAdapter", |
| 43 | + adapter_config={"param": "value"}, |
| 44 | + queue_name="my_queue" |
| 45 | + ) |
| 46 | + adapter = instantiate_adapter_from_config(config) |
| 47 | + """ |
| 48 | + |
| 49 | + adapter = task_processor_config.adapter |
| 50 | + |
| 51 | + # Handle string-based adapter specification (module path) |
| 52 | + if isinstance(adapter, str): |
| 53 | + adapter_class = import_attr(adapter) |
| 54 | + |
| 55 | + elif callable(adapter): |
| 56 | + adapter_class = adapter |
| 57 | + |
| 58 | + else: |
| 59 | + raise TypeError( |
| 60 | + f"Adapter must be either a string path or a callable class, got {type(adapter).__name__}: {adapter}" |
| 61 | + ) |
| 62 | + |
| 63 | + try: |
| 64 | + adapter_instance = adapter_class(config=task_processor_config) |
| 65 | + except Exception as e: |
| 66 | + raise RuntimeError(f"Failed to instantiate {adapter_class.__name__}: {e}") |
| 67 | + |
| 68 | + if not isinstance(adapter_instance, TaskProcessorAdapter): |
| 69 | + raise TypeError( |
| 70 | + f"{adapter_class.__name__} must inherit from TaskProcessorAdapter, got {type(adapter_instance).__name__}" |
| 71 | + ) |
| 72 | + |
| 73 | + try: |
| 74 | + adapter_instance.initialize(config=task_processor_config) |
| 75 | + except Exception as e: |
| 76 | + raise RuntimeError(f"Failed to initialize {adapter_class.__name__}: {e}") |
| 77 | + |
| 78 | + return adapter_instance |
| 79 | + |
| 80 | + |
| 81 | +@PublicAPI(stability="alpha") |
| 82 | +def task_consumer(*, task_processor_config: TaskProcessorConfig): |
| 83 | + """ |
| 84 | + Decorator to mark a class as a TaskConsumer. |
| 85 | +
|
| 86 | + Args: |
| 87 | + task_processor_config: Configuration for the task processor (required) |
| 88 | +
|
| 89 | + Note: |
| 90 | + This decorator must be used with parentheses: |
| 91 | + @task_consumer(task_processor_config=config) |
| 92 | +
|
| 93 | + Returns: |
| 94 | + A wrapper class that inherits from the target class and implements the task consumer functionality. |
| 95 | +
|
| 96 | + Example: |
| 97 | + .. code-block:: python |
| 98 | +
|
| 99 | + from ray import serve |
| 100 | + from ray.serve.task_consumer import task_consumer, task_handler |
| 101 | +
|
| 102 | + @serve.deployment |
| 103 | + @task_consumer(task_processor_config=config) |
| 104 | + class MyTaskConsumer: |
| 105 | +
|
| 106 | + @task_handler(name="my_task") |
| 107 | + def my_task(self, *args, **kwargs): |
| 108 | + pass |
| 109 | +
|
| 110 | + """ |
| 111 | + |
| 112 | + def decorator(target_cls): |
| 113 | + class TaskConsumerWrapper(target_cls): |
| 114 | + _adapter: TaskProcessorAdapter |
| 115 | + |
| 116 | + def __init__(self, *args, **kwargs): |
| 117 | + target_cls.__init__(self, *args, **kwargs) |
| 118 | + |
| 119 | + self._adapter = instantiate_adapter_from_config(task_processor_config) |
| 120 | + |
| 121 | + for name, method in inspect.getmembers( |
| 122 | + target_cls, predicate=inspect.isfunction |
| 123 | + ): |
| 124 | + if getattr(method, "_is_task_handler", False): |
| 125 | + task_name = getattr(method, "_task_name", name) |
| 126 | + |
| 127 | + # Create a callable that properly binds the method to this instance |
| 128 | + bound_method = getattr(self, name) |
| 129 | + |
| 130 | + self._adapter.register_task_handle(bound_method, task_name) |
| 131 | + |
| 132 | + try: |
| 133 | + self._adapter.start_consumer() |
| 134 | + logger.info("task consumer started successfully") |
| 135 | + except Exception as e: |
| 136 | + logger.error(f"Failed to start task consumer: {e}") |
| 137 | + raise |
| 138 | + |
| 139 | + def __del__(self): |
| 140 | + self._adapter.stop_consumer() |
| 141 | + self._adapter.shutdown() |
| 142 | + |
| 143 | + if hasattr(target_cls, "__del__"): |
| 144 | + target_cls.__del__(self) |
| 145 | + |
| 146 | + return TaskConsumerWrapper |
| 147 | + |
| 148 | + return decorator |
| 149 | + |
| 150 | + |
| 151 | +@PublicAPI(stability="alpha") |
| 152 | +def task_handler( |
| 153 | + _func: Optional[Callable] = None, *, name: Optional[str] = None |
| 154 | +) -> Callable: |
| 155 | + """ |
| 156 | + Decorator to mark a method as a task handler. |
| 157 | + Optionally specify a task name. Default is the method name. |
| 158 | +
|
| 159 | + Arguments: |
| 160 | + _func: The function to decorate. |
| 161 | + name: The name of the task. |
| 162 | +
|
| 163 | + Returns: |
| 164 | + A wrapper function that is marked as a task handler. |
| 165 | +
|
| 166 | + Example: |
| 167 | + .. code-block:: python |
| 168 | +
|
| 169 | + from ray import serve |
| 170 | + from ray.serve.task_consumer import task_consumer, task_handler |
| 171 | +
|
| 172 | + @serve.deployment |
| 173 | + @task_consumer(task_processor_config=config) |
| 174 | + class MyTaskConsumer: |
| 175 | +
|
| 176 | + @task_handler(name="my_task") |
| 177 | + def my_task(self, *args, **kwargs): |
| 178 | + pass |
| 179 | +
|
| 180 | + """ |
| 181 | + |
| 182 | + # Validate name parameter if provided |
| 183 | + if name is not None and (not isinstance(name, str) or not name.strip()): |
| 184 | + raise ValueError(f"Task name must be a non-empty string, got {name}") |
| 185 | + |
| 186 | + def decorator(f): |
| 187 | + # async functions are not supported yet in celery `threads` worker pool |
| 188 | + if not inspect.iscoroutinefunction(f): |
| 189 | + |
| 190 | + @wraps(f) |
| 191 | + def wrapper(*args, **kwargs): |
| 192 | + return f(*args, **kwargs) |
| 193 | + |
| 194 | + wrapper._is_task_handler = True # type: ignore |
| 195 | + wrapper._task_name = name or f.__name__ # type: ignore |
| 196 | + return wrapper |
| 197 | + |
| 198 | + else: |
| 199 | + raise NotImplementedError("Async task handlers are not supported yet") |
| 200 | + |
| 201 | + if _func is not None: |
| 202 | + # Used without arguments: @task_handler |
| 203 | + return decorator(_func) |
| 204 | + else: |
| 205 | + # Used with arguments: @task_handler(name="...") |
| 206 | + return decorator |
0 commit comments