papilio-tasks 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. papilio_tasks/__init__.py +0 -0
  2. papilio_tasks/faststream/__init__.py +0 -0
  3. papilio_tasks/faststream/brokers/__init__.py +0 -0
  4. papilio_tasks/faststream/dependencies/__init__.py +0 -0
  5. papilio_tasks/faststream/middlewares/__init__.py +0 -0
  6. papilio_tasks/faststream/router/__init__.py +0 -0
  7. papilio_tasks/py.typed +0 -0
  8. papilio_tasks/taskiq/__init__.py +4 -0
  9. papilio_tasks/taskiq/_tools/__init__.py +0 -0
  10. papilio_tasks/taskiq/_tools/_publication.py +24 -0
  11. papilio_tasks/taskiq/_tools/capo.py +33 -0
  12. papilio_tasks/taskiq/_tools/publishing.py +94 -0
  13. papilio_tasks/taskiq/_tools/registration.py +51 -0
  14. papilio_tasks/taskiq/_tools/retry.py +64 -0
  15. papilio_tasks/taskiq/_tools/wire.py +17 -0
  16. papilio_tasks/taskiq/_tools/ydb.py +27 -0
  17. papilio_tasks/taskiq/brokers/__init__.py +0 -0
  18. papilio_tasks/taskiq/brokers/kafka/__init__.py +7 -0
  19. papilio_tasks/taskiq/brokers/kafka/_admin.py +91 -0
  20. papilio_tasks/taskiq/brokers/kafka/_app.py +107 -0
  21. papilio_tasks/taskiq/brokers/kafka/_broker.py +134 -0
  22. papilio_tasks/taskiq/brokers/kafka/_native.py +33 -0
  23. papilio_tasks/taskiq/brokers/kafka/_producer.py +43 -0
  24. papilio_tasks/taskiq/brokers/kafka/_router.py +93 -0
  25. papilio_tasks/taskiq/brokers/memory/__init__.py +4 -0
  26. papilio_tasks/taskiq/brokers/memory/_native.py +22 -0
  27. papilio_tasks/taskiq/brokers/memory/_router.py +55 -0
  28. papilio_tasks/taskiq/brokers/memory/_runner.py +28 -0
  29. papilio_tasks/taskiq/brokers/memory/_runtime.py +124 -0
  30. papilio_tasks/taskiq/brokers/memory/_scheduler.py +28 -0
  31. papilio_tasks/taskiq/brokers/nats/__init__.py +8 -0
  32. papilio_tasks/taskiq/brokers/nats/_app.py +167 -0
  33. papilio_tasks/taskiq/brokers/nats/_brokers.py +141 -0
  34. papilio_tasks/taskiq/brokers/nats/_native.py +32 -0
  35. papilio_tasks/taskiq/brokers/nats/_producer.py +47 -0
  36. papilio_tasks/taskiq/brokers/nats/_router.py +107 -0
  37. papilio_tasks/taskiq/brokers/postgresql/__init__.py +4 -0
  38. papilio_tasks/taskiq/brokers/postgresql/_app.py +100 -0
  39. papilio_tasks/taskiq/brokers/postgresql/_broker.py +56 -0
  40. papilio_tasks/taskiq/brokers/postgresql/_producer.py +59 -0
  41. papilio_tasks/taskiq/brokers/postgresql/_router.py +83 -0
  42. papilio_tasks/taskiq/brokers/rabbit/__init__.py +7 -0
  43. papilio_tasks/taskiq/brokers/rabbit/_app.py +71 -0
  44. papilio_tasks/taskiq/brokers/rabbit/_broker.py +41 -0
  45. papilio_tasks/taskiq/brokers/rabbit/_native.py +13 -0
  46. papilio_tasks/taskiq/brokers/rabbit/_producer.py +77 -0
  47. papilio_tasks/taskiq/brokers/rabbit/_router.py +68 -0
  48. papilio_tasks/taskiq/brokers/rabbit/_topology.py +123 -0
  49. papilio_tasks/taskiq/brokers/rabbit/dishka/__init__.py +1 -0
  50. papilio_tasks/taskiq/brokers/rabbit/dishka/_provider.py +28 -0
  51. papilio_tasks/taskiq/brokers/redis/__init__.py +11 -0
  52. papilio_tasks/taskiq/brokers/redis/_app.py +155 -0
  53. papilio_tasks/taskiq/brokers/redis/_native.py +32 -0
  54. papilio_tasks/taskiq/brokers/redis/_producer.py +33 -0
  55. papilio_tasks/taskiq/brokers/redis/_router.py +82 -0
  56. papilio_tasks/taskiq/brokers/redis/_sentinel.py +33 -0
  57. papilio_tasks/taskiq/brokers/service_bus/__init__.py +10 -0
  58. papilio_tasks/taskiq/brokers/service_bus/_app.py +119 -0
  59. papilio_tasks/taskiq/brokers/service_bus/_broker.py +212 -0
  60. papilio_tasks/taskiq/brokers/service_bus/_entities.py +43 -0
  61. papilio_tasks/taskiq/brokers/service_bus/_native.py +31 -0
  62. papilio_tasks/taskiq/brokers/service_bus/_producer.py +26 -0
  63. papilio_tasks/taskiq/brokers/service_bus/_router.py +89 -0
  64. papilio_tasks/taskiq/brokers/sqs/__init__.py +3 -0
  65. papilio_tasks/taskiq/brokers/sqs/_app.py +109 -0
  66. papilio_tasks/taskiq/brokers/sqs/_binding.py +49 -0
  67. papilio_tasks/taskiq/brokers/sqs/_producer.py +32 -0
  68. papilio_tasks/taskiq/brokers/sqs/_router.py +114 -0
  69. papilio_tasks/taskiq/brokers/sqs/aio/__init__.py +2 -0
  70. papilio_tasks/taskiq/brokers/sqs/aio/_broker.py +84 -0
  71. papilio_tasks/taskiq/brokers/sqs/capo/__init__.py +2 -0
  72. papilio_tasks/taskiq/brokers/sqs/capo/_broker.py +65 -0
  73. papilio_tasks/taskiq/brokers/ydb/__init__.py +5 -0
  74. papilio_tasks/taskiq/brokers/ydb/_app.py +113 -0
  75. papilio_tasks/taskiq/brokers/ydb/_broker.py +209 -0
  76. papilio_tasks/taskiq/brokers/ydb/_native.py +30 -0
  77. papilio_tasks/taskiq/brokers/ydb/_producer.py +26 -0
  78. papilio_tasks/taskiq/brokers/ydb/_router.py +84 -0
  79. papilio_tasks/taskiq/brokers/zmq/__init__.py +4 -0
  80. papilio_tasks/taskiq/brokers/zmq/_app.py +84 -0
  81. papilio_tasks/taskiq/brokers/zmq/_broker.py +61 -0
  82. papilio_tasks/taskiq/brokers/zmq/_native.py +24 -0
  83. papilio_tasks/taskiq/brokers/zmq/_producer.py +35 -0
  84. papilio_tasks/taskiq/brokers/zmq/_router.py +61 -0
  85. papilio_tasks/taskiq/cli/__init__.py +0 -0
  86. papilio_tasks/taskiq/cli/_banner.py +48 -0
  87. papilio_tasks/taskiq/cli/_logging.py +54 -0
  88. papilio_tasks/taskiq/cli/_main.py +58 -0
  89. papilio_tasks/taskiq/cli/_receiver.py +14 -0
  90. papilio_tasks/taskiq/cli/_scheduler.py +60 -0
  91. papilio_tasks/taskiq/cli/_validation.py +24 -0
  92. papilio_tasks/taskiq/cli/_worker.py +33 -0
  93. papilio_tasks/taskiq/dependencies/__init__.py +0 -0
  94. papilio_tasks/taskiq/dependencies/dishka/__init__.py +5 -0
  95. papilio_tasks/taskiq/dependencies/dishka/_inject.py +50 -0
  96. papilio_tasks/taskiq/dependencies/dishka/_native.py +28 -0
  97. papilio_tasks/taskiq/dependencies/dishka/_signature.py +64 -0
  98. papilio_tasks/taskiq/dependencies/dishka/_worker.py +129 -0
  99. papilio_tasks/taskiq/dependencies/dishka/service.py +48 -0
  100. papilio_tasks/taskiq/middlewares/__init__.py +2 -0
  101. papilio_tasks/taskiq/middlewares/__init__.pyi +3 -0
  102. papilio_tasks/taskiq/middlewares/_exports.py +15 -0
  103. papilio_tasks/taskiq/middlewares/logging.py +57 -0
  104. papilio_tasks/taskiq/middlewares/retry/__init__.py +10 -0
  105. papilio_tasks/taskiq/middlewares/retry/_policy.py +35 -0
  106. papilio_tasks/taskiq/middlewares/retry/middleware.py +141 -0
  107. papilio_tasks/taskiq/options.py +35 -0
  108. papilio_tasks/taskiq/results/__init__.py +0 -0
  109. papilio_tasks/taskiq/results/local/__init__.py +2 -0
  110. papilio_tasks/taskiq/results/local/_native.py +13 -0
  111. papilio_tasks/taskiq/results/nats/__init__.py +2 -0
  112. papilio_tasks/taskiq/results/nats/_backend.py +89 -0
  113. papilio_tasks/taskiq/results/postgresql/__init__.py +1 -0
  114. papilio_tasks/taskiq/results/postgresql/_backend.py +37 -0
  115. papilio_tasks/taskiq/results/reader/__init__.py +3 -0
  116. papilio_tasks/taskiq/results/reader/_reader.py +76 -0
  117. papilio_tasks/taskiq/results/redis/__init__.py +3 -0
  118. papilio_tasks/taskiq/results/redis/_native.py +19 -0
  119. papilio_tasks/taskiq/results/s3/__init__.py +0 -0
  120. papilio_tasks/taskiq/results/s3/aio/__init__.py +1 -0
  121. papilio_tasks/taskiq/results/s3/aio/_backend.py +31 -0
  122. papilio_tasks/taskiq/results/s3/capo/__init__.py +2 -0
  123. papilio_tasks/taskiq/results/s3/capo/_backend.py +69 -0
  124. papilio_tasks/taskiq/results/ydb/__init__.py +3 -0
  125. papilio_tasks/taskiq/results/ydb/_backend.py +152 -0
  126. papilio_tasks/taskiq/schedulers/__init__.py +6 -0
  127. papilio_tasks/taskiq/schedulers/__init__.pyi +8 -0
  128. papilio_tasks/taskiq/schedulers/_exports.py +29 -0
  129. papilio_tasks/taskiq/schedulers/_inline.py +19 -0
  130. papilio_tasks/taskiq/schedulers/_managed.py +55 -0
  131. papilio_tasks/taskiq/schedulers/composition/__init__.py +8 -0
  132. papilio_tasks/taskiq/schedulers/composition/_dispatch.py +168 -0
  133. papilio_tasks/taskiq/schedulers/composition/_records.py +172 -0
  134. papilio_tasks/taskiq/schedulers/composition/_router.py +38 -0
  135. papilio_tasks/taskiq/schedulers/composition/_scheduler.py +145 -0
  136. papilio_tasks/taskiq/schedulers/composition/_source.py +27 -0
  137. papilio_tasks/taskiq/schedulers/composition/handle.py +79 -0
  138. papilio_tasks/taskiq/schedulers/sources/__init__.py +0 -0
  139. papilio_tasks/taskiq/schedulers/sources/_payload.py +28 -0
  140. papilio_tasks/taskiq/schedulers/sources/nats/__init__.py +1 -0
  141. papilio_tasks/taskiq/schedulers/sources/nats/_source.py +150 -0
  142. papilio_tasks/taskiq/schedulers/sources/postgresql/__init__.py +1 -0
  143. papilio_tasks/taskiq/schedulers/sources/postgresql/_source.py +174 -0
  144. papilio_tasks/taskiq/schedulers/sources/redis/__init__.py +4 -0
  145. papilio_tasks/taskiq/schedulers/sources/redis/_list.py +213 -0
  146. papilio_tasks/taskiq/schedulers/sources/redis/_native.py +188 -0
  147. papilio_tasks/taskiq/schedulers/sources/redis/_records.py +41 -0
  148. papilio_tasks/taskiq/schedulers/sources/ydb/__init__.py +1 -0
  149. papilio_tasks/taskiq/schedulers/sources/ydb/_records.py +63 -0
  150. papilio_tasks/taskiq/schedulers/sources/ydb/_source.py +226 -0
  151. papilio_tasks/taskiq/schedulers/triggers.py +39 -0
  152. papilio_tasks-3.0.0.dist-info/METADATA +175 -0
  153. papilio_tasks-3.0.0.dist-info/RECORD +157 -0
  154. papilio_tasks-3.0.0.dist-info/WHEEL +5 -0
  155. papilio_tasks-3.0.0.dist-info/entry_points.txt +2 -0
  156. papilio_tasks-3.0.0.dist-info/licenses/LICENSE +21 -0
  157. papilio_tasks-3.0.0.dist-info/top_level.txt +1 -0
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
papilio_tasks/py.typed ADDED
File without changes
@@ -0,0 +1,4 @@
1
+ from .options import Retry as Retry
2
+ from .options import TaskOptions as TaskOptions
3
+ from .schedulers.triggers import Cron as Cron
4
+ from .schedulers.triggers import Interval as Interval
File without changes
@@ -0,0 +1,24 @@
1
+ from collections.abc import AsyncGenerator
2
+
3
+ from taskiq import AsyncBroker, BrokerMessage
4
+ from taskiq.acks import AckableMessage
5
+
6
+
7
+ class TrackedPublication(AsyncBroker):
8
+ """Record one kicker's transport outcome without changing the running broker."""
9
+
10
+ def __init__(self, broker: AsyncBroker) -> None:
11
+ super().__init__()
12
+ self._broker = broker
13
+ self.middlewares = broker.middlewares
14
+ self.formatter = broker.formatter
15
+ self.result_backend = broker.result_backend
16
+ self.id_generator = broker.id_generator
17
+ self.confirmed = False
18
+
19
+ async def kick(self, message: BrokerMessage) -> None:
20
+ await self._broker.kick(message)
21
+ self.confirmed = True
22
+
23
+ def listen(self) -> AsyncGenerator[bytes | AckableMessage, None]:
24
+ return self._broker.listen()
@@ -0,0 +1,33 @@
1
+ from collections.abc import Generator
2
+ from contextlib import ExitStack, contextmanager
3
+ from importlib.metadata import PackageNotFoundError, version
4
+ from typing import TypeVar
5
+
6
+ from pydantic import BaseModel
7
+ from taskiq import compat
8
+
9
+ _Model = TypeVar("_Model", bound=BaseModel)
10
+
11
+
12
+ def _model_validate(model: type[_Model], data: object) -> _Model:
13
+ return model.model_validate(data)
14
+
15
+
16
+ @contextmanager
17
+ def support_legacy_import() -> Generator[None, None, None]:
18
+ """Supply the removed Pydantic aliases only while importing taskiq-sqs 0.1.0."""
19
+ try:
20
+ needs_aliases = version("taskiq-sqs") == "0.1.0"
21
+ except PackageNotFoundError:
22
+ needs_aliases = False
23
+ with ExitStack() as stack:
24
+ if needs_aliases:
25
+ aliases = {
26
+ "model_dump": BaseModel.model_dump,
27
+ "model_validate": _model_validate,
28
+ }
29
+ for name, function in aliases.items():
30
+ if not hasattr(compat, name):
31
+ setattr(compat, name, function)
32
+ stack.callback(delattr, compat, name)
33
+ yield
@@ -0,0 +1,94 @@
1
+ from abc import ABC, abstractmethod
2
+ from collections.abc import Callable, Coroutine, Mapping
3
+ from dataclasses import dataclass
4
+ from types import FunctionType
5
+ from typing import ParamSpec, TypeVar, cast, get_type_hints, overload
6
+
7
+ from taskiq import AsyncBroker
8
+ from taskiq.kicker import AsyncKicker
9
+ from taskiq.task import AsyncTaskiqTask
10
+
11
+ from .wire import validate_wire_arguments
12
+
13
+ _Parameters = ParamSpec("_Parameters")
14
+ _Result = TypeVar("_Result")
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class Publication:
19
+ name: str
20
+ labels: Mapping[str, object]
21
+ return_type: type[object] | None
22
+
23
+
24
+ def publication(
25
+ handler: Callable[..., object], name: str, /, **labels: object
26
+ ) -> Publication:
27
+ return_type = get_type_hints(handler).get("return")
28
+ return Publication(name, labels, return_type)
29
+
30
+
31
+ class TaskPublisher(ABC):
32
+ @abstractmethod
33
+ def kicker(
34
+ self, handler: Callable[_Parameters, _Result], /
35
+ ) -> AsyncKicker[_Parameters, _Result]: ...
36
+
37
+ @overload
38
+ async def send(
39
+ self,
40
+ handler: Callable[_Parameters, Coroutine[object, object, _Result]],
41
+ /,
42
+ *args: _Parameters.args,
43
+ **kwargs: _Parameters.kwargs,
44
+ ) -> AsyncTaskiqTask[_Result]: ...
45
+
46
+ @overload
47
+ async def send(
48
+ self,
49
+ handler: Callable[_Parameters, _Result],
50
+ /,
51
+ *args: _Parameters.args,
52
+ **kwargs: _Parameters.kwargs,
53
+ ) -> AsyncTaskiqTask[_Result]: ...
54
+
55
+ async def send(
56
+ self,
57
+ handler: Callable[_Parameters, object],
58
+ /,
59
+ *args: _Parameters.args,
60
+ **kwargs: _Parameters.kwargs,
61
+ ) -> object:
62
+ """Publish a registered task using the producer's existing broker."""
63
+ kicker = self.kicker(handler)
64
+ validate_wire_arguments(handler, args, kwargs)
65
+ return await kicker.kiq(*args, **kwargs)
66
+
67
+
68
+ class TaskProducer(TaskPublisher):
69
+ _kicker_type: type[AsyncKicker[..., object]] = AsyncKicker
70
+
71
+ def __init__(
72
+ self,
73
+ broker: AsyncBroker,
74
+ publications: Mapping[Callable[..., object], Publication],
75
+ ) -> None:
76
+ self._broker = broker
77
+ self._publications = publications
78
+
79
+ def kicker(
80
+ self, handler: Callable[_Parameters, _Result], /
81
+ ) -> AsyncKicker[_Parameters, _Result]:
82
+ """Build a native kicker with the resolved destination and independent labels."""
83
+ target = (
84
+ self._publications.get(handler)
85
+ if isinstance(handler, FunctionType)
86
+ else None
87
+ )
88
+ if target is None:
89
+ raise ValueError(f"Task {handler!r} is not registered with this producer.")
90
+ labels = dict(target.labels)
91
+ kicker = self._kicker_type(
92
+ target.name, self._broker, labels, target.return_type
93
+ )
94
+ return cast("AsyncKicker[_Parameters, _Result]", kicker)
@@ -0,0 +1,51 @@
1
+ from collections.abc import Callable, Mapping
2
+ from functools import update_wrapper
3
+ from types import FunctionType
4
+ from typing import cast
5
+
6
+ from ..options import TaskOptions
7
+ from ..schedulers.triggers import Cron, Interval
8
+ from .retry import RETRY_LABELS, retry_labels
9
+
10
+
11
+ def registration_name(handler: Callable[..., object], options: TaskOptions) -> str:
12
+ name = options.get("name")
13
+ if name is None:
14
+ name = f"{handler.__module__}:{handler.__name__}"
15
+ if not name.strip():
16
+ raise ValueError("A task name must be nonempty.")
17
+ return name
18
+
19
+
20
+ def registration_options(
21
+ name: str, options: TaskOptions, *, route_labels: set[str]
22
+ ) -> tuple[Cron | Interval | None, dict[str, object]]:
23
+ schedule = cast("Mapping[str, object]", options).get("schedule")
24
+ if schedule is not None and not isinstance(schedule, (Cron, Interval)):
25
+ raise TypeError(f"Task {name!r} requires a Cron or Interval schedule.")
26
+ labels = dict(options.get("labels", {}))
27
+ reserved = route_labels | {"task_name", "func"}
28
+ if schedule is not None:
29
+ reserved.add("schedule")
30
+ if "retry" in options:
31
+ reserved.update(RETRY_LABELS)
32
+ conflicts = reserved.intersection(labels)
33
+ if conflicts:
34
+ raise ValueError(f"Task {name!r} uses reserved labels {sorted(conflicts)}.")
35
+ if "retry" in options:
36
+ labels.update(retry_labels(options["retry"]))
37
+ return schedule, labels
38
+
39
+
40
+ def copy_task_function(handler: FunctionType) -> FunctionType:
41
+ """Keep Taskiq's native registration changes on a separate function."""
42
+ function = FunctionType(
43
+ handler.__code__,
44
+ handler.__globals__,
45
+ handler.__name__,
46
+ handler.__defaults__,
47
+ handler.__closure__,
48
+ )
49
+ update_wrapper(function, handler)
50
+ function.__kwdefaults__ = handler.__kwdefaults__
51
+ return function
@@ -0,0 +1,64 @@
1
+ from logging import INFO, WARNING, getLogger
2
+ from typing import Literal
3
+
4
+ from ..options import Retry
5
+
6
+ RETRY_LABELS = frozenset({"retry_on_error", "max_retries", "types_of_exceptions"})
7
+ _logger = getLogger("papilio_tasks.taskiq.retries")
8
+
9
+
10
+ def retry_labels(policy: object) -> dict[str, object]:
11
+ if policy is False:
12
+ return {"retry_on_error": False}
13
+ if isinstance(policy, Retry):
14
+ return {
15
+ "retry_on_error": True,
16
+ "max_retries": policy.max_retries + 1,
17
+ "types_of_exceptions": policy.on,
18
+ }
19
+ raise TypeError("retry requires a Retry policy or False.")
20
+
21
+
22
+ def log_retry_handoff(
23
+ *,
24
+ task_id: str | None,
25
+ task_name: str,
26
+ attempt: object,
27
+ phase: Literal["publish", "store", "dispatch"],
28
+ confirmed: bool,
29
+ error: BaseException | None = None,
30
+ ) -> None:
31
+ if isinstance(attempt, str):
32
+ try:
33
+ attempt = int(attempt)
34
+ except ValueError:
35
+ return
36
+ if task_id is None or type(attempt) is not int or attempt < 1:
37
+ return
38
+
39
+ outcome = "confirmed" if confirmed else "unconfirmed"
40
+ level = INFO if confirmed and error is None else WARNING
41
+ error_type: str | None = None
42
+ if error is not None:
43
+ cause = error.__cause__ or error
44
+ error_type = type(cause).__name__
45
+ try:
46
+ _logger.log(
47
+ level,
48
+ "Retry %s %s for %s",
49
+ phase,
50
+ outcome,
51
+ task_name,
52
+ extra={
53
+ "task_id": task_id,
54
+ "task_name": task_name,
55
+ "task_retry_count": attempt,
56
+ "retry_phase": phase,
57
+ "retry_outcome": outcome,
58
+ "retry_error_type": error_type,
59
+ },
60
+ )
61
+ except Exception: # noqa: BLE001
62
+ # Application log handlers run synchronously. A handler failure cannot
63
+ # change the retry outcome or the result saved by Taskiq.
64
+ return
@@ -0,0 +1,17 @@
1
+ from collections.abc import Callable, Mapping
2
+ from inspect import Signature
3
+
4
+
5
+ def validate_wire_arguments(
6
+ handler: Callable[..., object],
7
+ args: tuple[object, ...],
8
+ kwargs: Mapping[str, object],
9
+ ) -> None:
10
+ wire = getattr(handler, "__papilio_wire_signature__", None)
11
+ if isinstance(wire, Signature):
12
+ dependency_names: tuple[str, ...] = getattr(
13
+ handler, "__papilio_dependency_parameters__", ()
14
+ )
15
+ if any(name in kwargs for name in dependency_names):
16
+ raise TypeError("Dishka task dependencies are provided by the worker.")
17
+ wire.bind(*args, **kwargs)
@@ -0,0 +1,27 @@
1
+ from collections.abc import AsyncGenerator
2
+ from contextlib import asynccontextmanager
3
+
4
+ from taskiq_ydb.exceptions import DatabaseConnectionError
5
+ from ydb.aio.driver import Driver, DriverConfig
6
+ from ydb.aio.query import QuerySessionPool
7
+ from ydb.issues import ConnectionLost
8
+
9
+
10
+ @asynccontextmanager
11
+ async def open_query_pool(
12
+ config: DriverConfig, *, pool_size: int, connection_timeout: float
13
+ ) -> AsyncGenerator[QuerySessionPool, None]:
14
+ """Own a YDB driver and its query sessions for one runtime scope."""
15
+ driver = Driver(driver_config=config)
16
+ try:
17
+ try:
18
+ await driver.wait(fail_fast=True, timeout=connection_timeout)
19
+ except (ConnectionLost, TimeoutError) as error:
20
+ raise DatabaseConnectionError("Could not connect to YDB.") from error
21
+ pool = QuerySessionPool(driver, size=pool_size)
22
+ try:
23
+ yield pool
24
+ finally:
25
+ await pool.stop()
26
+ finally:
27
+ await driver.stop()
File without changes
@@ -0,0 +1,7 @@
1
+ from ._app import KafkaApp as KafkaApp
2
+ from ._broker import AioKafkaBroker as AioKafkaBroker
3
+ from ._native import NewTopic as NewTopic
4
+ from ._native import Topic as Topic
5
+ from ._native import TopicConfig as TopicConfig
6
+ from ._producer import KafkaProducer as KafkaProducer
7
+ from ._router import KafkaRouter as KafkaRouter
@@ -0,0 +1,91 @@
1
+ from collections.abc import Generator, Sequence
2
+ from contextlib import contextmanager
3
+ from threading import Lock
4
+ from typing import Protocol, cast
5
+
6
+ from ._native import KafkaAdminClient, NewTopic, TopicAlreadyExistsError
7
+
8
+
9
+ class _Admin(Protocol):
10
+ def list_topics(self) -> list[str]: ...
11
+
12
+ def create_topics(
13
+ self, new_topics: Sequence[NewTopic], *, validate_only: bool
14
+ ) -> object: ...
15
+
16
+ def delete_topics(self, topics: Sequence[str]) -> object: ...
17
+
18
+ def close(self) -> None: ...
19
+
20
+
21
+ class TopicAdmin:
22
+ """Supply Taskiq with a topic snapshot and perform Kafka admin I/O in a thread."""
23
+
24
+ def __init__(
25
+ self, servers: str | list[str] | None, client: KafkaAdminClient | None
26
+ ) -> None:
27
+ self._servers = servers
28
+ self._client = cast("_Admin | None", client)
29
+ self._lock = Lock()
30
+ self._known: set[str] = set()
31
+
32
+ @contextmanager
33
+ def _connection(self) -> Generator[_Admin, None, None]:
34
+ if self._client is not None:
35
+ yield self._client
36
+ return
37
+ client = KafkaAdminClient(
38
+ bootstrap_servers=self._servers or "localhost:9092",
39
+ client_id="papilio-taskiq-kafka",
40
+ )
41
+ admin = cast(_Admin, client)
42
+ try:
43
+ yield admin
44
+ finally:
45
+ admin.close()
46
+
47
+ def prepare(self, topics: Sequence[NewTopic]) -> None:
48
+ if not topics:
49
+ return
50
+ with self._lock, self._connection() as admin:
51
+ known = set(admin.list_topics())
52
+ pending: dict[str, NewTopic] = {
53
+ topic.name: topic for topic in topics if topic.name not in known
54
+ }
55
+ while pending:
56
+ try:
57
+ admin.create_topics(list(pending.values()), validate_only=False)
58
+ except TopicAlreadyExistsError:
59
+ known = set(admin.list_topics())
60
+ remaining: dict[str, NewTopic] = {
61
+ name: topic
62
+ for name, topic in pending.items()
63
+ if name not in known
64
+ }
65
+ if len(remaining) == len(pending):
66
+ raise
67
+ pending = remaining
68
+ else:
69
+ known.update(pending)
70
+ break
71
+ self._known = known
72
+
73
+ def list_topics(self) -> list[str]:
74
+ return list(self._known)
75
+
76
+ def close(self) -> None:
77
+ """Taskiq's sync shutdown hook uses the snapshot, which owns no sockets."""
78
+
79
+ def finish(self, delete: Sequence[str]) -> None:
80
+ with self._lock:
81
+ try:
82
+ if delete:
83
+ with self._connection() as admin:
84
+ known = set(admin.list_topics())
85
+ topics = [name for name in delete if name in known]
86
+ if topics:
87
+ admin.delete_topics(topics)
88
+ finally:
89
+ if self._client is not None:
90
+ self._client.close()
91
+ self._known.clear()
@@ -0,0 +1,107 @@
1
+ from collections.abc import Sequence
2
+ from contextlib import AbstractAsyncContextManager
3
+ from functools import partial
4
+ from types import FunctionType
5
+ from typing import TYPE_CHECKING, Protocol, cast
6
+
7
+ from ... import schedulers
8
+ from ..._tools.registration import (
9
+ copy_task_function,
10
+ registration_name,
11
+ registration_options,
12
+ )
13
+ from ...schedulers._inline import store_inline_schedules
14
+ from ._broker import AioKafkaBroker
15
+ from ._native import TASK_TOPIC_LABEL
16
+ from ._producer import KafkaProducer, open_producer
17
+ from ._router import KafkaRouter, Route, validate_topic
18
+
19
+ if TYPE_CHECKING:
20
+ from taskiq import ScheduleSource
21
+
22
+
23
+ class _BrokerFactory(Protocol):
24
+ def __call__(
25
+ self, *, kafka_topic: str, kafka_topics: tuple[str, ...]
26
+ ) -> AioKafkaBroker: ...
27
+
28
+
29
+ class KafkaApp:
30
+ """Compose module routers using Kafka topics and native broker settings."""
31
+
32
+ def __init__(self, *, topic: str, broker_factory: _BrokerFactory) -> None:
33
+ self._topic = validate_topic(topic)
34
+ self._broker_factory = broker_factory
35
+ self._routes: dict[str, Route] = {}
36
+
37
+ def include_router(self, router: KafkaRouter) -> None:
38
+ """Resolve task, router and application defaults in that order."""
39
+ topic = self._topic if router.topic is None else validate_topic(router.topic)
40
+ routes = self._routes.copy()
41
+ handlers = {route.handler for route in routes.values()}
42
+ for declaration in router.declarations:
43
+ handler = declaration.handler
44
+ options = declaration.options
45
+ name = registration_name(handler, options)
46
+ if name in routes:
47
+ raise ValueError(f"Task {name!r} is already registered.")
48
+ if handler in handlers:
49
+ raise ValueError(f"Task handler for {name!r} is already registered.")
50
+ override = declaration.topic
51
+ destination = topic if override is None else validate_topic(override)
52
+ schedule, labels = registration_options(
53
+ name, options, route_labels={TASK_TOPIC_LABEL}
54
+ )
55
+ routes[name] = Route(handler, name, destination, schedule, labels)
56
+ handlers.add(handler)
57
+ self._routes = routes
58
+
59
+ def _broker(self, topics: tuple[str, ...]) -> AioKafkaBroker:
60
+ broker = self._broker_factory(kafka_topic=topics[0], kafka_topics=topics[1:])
61
+ if set(broker.topics) != set(topics):
62
+ raise ValueError("Kafka broker factory must configure the selected topics.")
63
+ return broker
64
+
65
+ def create_broker(
66
+ self, *, topics: Sequence[str] | str | None = None
67
+ ) -> AioKafkaBroker:
68
+ """Create a native worker for all registered topics or a selection."""
69
+ available = tuple(dict.fromkeys(route.topic for route in self._routes.values()))
70
+ if topics is None:
71
+ selected = available
72
+ elif isinstance(topics, str):
73
+ selected = (topics,)
74
+ else:
75
+ selected = tuple(dict.fromkeys(topics))
76
+ if not selected or set(selected).difference(available):
77
+ raise ValueError("Kafka worker requires topics with registered tasks.")
78
+ broker = self._broker(selected)
79
+ routes = [route for route in self._routes.values() if route.topic in selected]
80
+ for route in routes:
81
+ original = cast(FunctionType, route.handler)
82
+ handler = copy_task_function(original)
83
+ labels = {TASK_TOPIC_LABEL: route.topic, **route.labels}
84
+ broker.register_task(handler, task_name=route.name, **labels)
85
+ inline = {
86
+ route.name: route.schedule for route in routes if route.schedule is not None
87
+ }
88
+ if inline:
89
+ store_inline_schedules(broker, inline)
90
+ return broker
91
+
92
+ def create_scheduler(
93
+ self,
94
+ *,
95
+ topics: Sequence[str] | str | None = None,
96
+ sources: Sequence["ScheduleSource"] = (),
97
+ labels: bool = False,
98
+ ) -> schedulers.Scheduler:
99
+ """Create a Taskiq scheduler for the selected destinations."""
100
+ broker = self.create_broker(topics=topics)
101
+ return schedulers.Scheduler(broker, sources=sources, labels=labels)
102
+
103
+ def producer(self) -> AbstractAsyncContextManager[KafkaProducer]:
104
+ """Create one Kafka producer for the sending application's lifespan."""
105
+ topics = tuple(dict.fromkeys(route.topic for route in self._routes.values()))
106
+ factory = partial(self._broker, topics or (self._topic,))
107
+ return open_producer(factory, self._routes)
@@ -0,0 +1,134 @@
1
+ from asyncio import AbstractEventLoop, to_thread
2
+ from collections.abc import Callable, Iterable
3
+ from contextlib import AsyncExitStack
4
+ from typing import Protocol, TypeVar, cast
5
+
6
+ from ._admin import TopicAdmin
7
+ from ._native import AioKafkaBroker as _NativeBroker
8
+ from ._native import (
9
+ AsyncBroker,
10
+ AsyncResultBackend,
11
+ DefaultPartitioner,
12
+ KafkaAdminClient,
13
+ NewTopic,
14
+ RoundRobinPartitionAssignor,
15
+ Topic,
16
+ TopicConfig,
17
+ )
18
+
19
+ TopicType = str | NewTopic | Topic
20
+ _Result = TypeVar("_Result")
21
+
22
+
23
+ class _Stoppable(Protocol):
24
+ async def stop(self) -> None: ...
25
+
26
+
27
+ def _topic_declaration(topic: Topic) -> NewTopic:
28
+ config = topic.topic_config
29
+ replicas = config.replica_assignments or None
30
+ return NewTopic(
31
+ topic.name,
32
+ num_partitions=-1 if replicas else config.num_partitions,
33
+ replication_factor=-1 if replicas else config.replication_factor,
34
+ replica_assignments=replicas,
35
+ topic_configs=config.topic_configs,
36
+ )
37
+
38
+
39
+ class AioKafkaBroker(_NativeBroker):
40
+ """Taskiq's Kafka broker with deferred topic administration and scoped cleanup."""
41
+
42
+ def __init__(
43
+ self,
44
+ bootstrap_servers: str | list[str] | None,
45
+ kafka_topic: TopicType | None = None,
46
+ kafka_topics: Iterable[TopicType] | None = None,
47
+ result_backend: AsyncResultBackend[_Result] | None = None,
48
+ task_id_generator: Callable[[], str] | None = None,
49
+ kafka_admin_client: KafkaAdminClient | None = None,
50
+ loop: AbstractEventLoop | None = None,
51
+ delete_topic_on_shutdown: bool = False,
52
+ ) -> None:
53
+ self._admin = TopicAdmin(bootstrap_servers, kafka_admin_client)
54
+ extra_topics = (
55
+ Topic(topic, TopicConfig(declare=True)) if isinstance(topic, str) else topic
56
+ for topic in kafka_topics or ()
57
+ )
58
+ # Taskiq uses the admin facade's snapshot during its native startup.
59
+ snapshot = cast(KafkaAdminClient, self._admin)
60
+ super().__init__(
61
+ bootstrap_servers or "localhost:9092",
62
+ kafka_topic=kafka_topic,
63
+ kafka_topics=extra_topics,
64
+ result_backend=result_backend,
65
+ task_id_generator=task_id_generator,
66
+ kafka_admin_client=snapshot,
67
+ loop=loop,
68
+ )
69
+ if isinstance(kafka_topic, Topic) and not kafka_topic.topic_config.declare:
70
+ self._kafka_topics[kafka_topic.name] = kafka_topic
71
+ self._remove_topics = delete_topic_on_shutdown
72
+ self._running = False
73
+ self._taskiq_started = False
74
+
75
+ @classmethod
76
+ def _normalize_default_topic(cls, kafka_topic: TopicType | None) -> NewTopic:
77
+ if isinstance(kafka_topic, Topic) and kafka_topic.topic_config.declare:
78
+ return _topic_declaration(kafka_topic)
79
+ return super()._normalize_default_topic(kafka_topic)
80
+
81
+ @classmethod
82
+ def _get_declaration_topic(cls, topic: TopicType) -> NewTopic | None:
83
+ if isinstance(topic, Topic) and topic.topic_config.declare:
84
+ return _topic_declaration(topic)
85
+ return super()._get_declaration_topic(topic)
86
+
87
+ @property
88
+ def topics(self) -> tuple[str, ...]:
89
+ """Kafka topics that the native worker subscribes to."""
90
+ return tuple(self._kafka_topics)
91
+
92
+ async def startup(self) -> None:
93
+ self._running = True
94
+ try:
95
+ declarations = [
96
+ candidate
97
+ for topic in self._kafka_topics.values()
98
+ if (candidate := self._get_declaration_topic(topic)) is not None
99
+ ]
100
+ await to_thread(self._admin.prepare, declarations)
101
+ if self._aiokafka_producer_params.partitioner is None:
102
+ self._aiokafka_producer_params.partitioner = DefaultPartitioner()
103
+ if self._aiokafka_consumer_params.partition_assignment_strategy is None:
104
+ self._aiokafka_consumer_params.partition_assignment_strategy = (
105
+ RoundRobinPartitionAssignor,
106
+ )
107
+ self._taskiq_started = True
108
+ await super().startup()
109
+ except BaseException:
110
+ await self.shutdown()
111
+ raise
112
+
113
+ async def shutdown(self) -> None:
114
+ if not self._running:
115
+ return
116
+ self._running = False
117
+ deletes = (
118
+ self.topics if self._remove_topics and self._is_producer_started else ()
119
+ )
120
+ producer = cast("_Stoppable | None", getattr(self, "_aiokafka_producer", None))
121
+ consumer = cast("_Stoppable | None", getattr(self, "_aiokafka_consumer", None))
122
+ try:
123
+ async with AsyncExitStack() as cleanup:
124
+ cleanup.push_async_callback(to_thread, self._admin.finish, deletes)
125
+ if producer is not None:
126
+ cleanup.push_async_callback(producer.stop)
127
+ if consumer is not None:
128
+ cleanup.push_async_callback(consumer.stop)
129
+ if self._taskiq_started:
130
+ await AsyncBroker.shutdown(self)
131
+ finally:
132
+ self._taskiq_started = False
133
+ self._is_producer_started = False
134
+ self._is_consumer_started = False