task_consumer.py 7.0 KB

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